text
stringlengths 184
4.48M
|
---|
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Windows.Forms;
using IniParser;
using IniParser.Model;
using Nefarius.ViGEm.Client;
using Nefarius.ViGEm.Client.Targets;
using Nefarius.ViGEm.Client.Targets.Xbox360;
using Nefarius.ViGEm.Client.Exceptions;
using Keyboard2XinputLib.Exceptions;
using System.Drawing;
using System.IO;
namespace Keyboard2XinputLib
{
public class Keyboard2Xinput
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private const short AXIS_POS_VALUE = 0x7530;
private const short AXIS_NEG_VALUE = -0x7530;
private const byte TRIGGER_VALUE = 0xFF;
private static System.Threading.Timer timer;
public const int WM_KEYDOWN = 0x0100;
public const int WM_KEYUP = 0x0101;
public const int WM_SYSKEYDOWN = 0x0104;
private Dictionary<string, Xbox360Button> buttonsDict = new Dictionary<string, Xbox360Button>();
private Dictionary<string, KeyValuePair<Xbox360Axis, short>> axesDict = new Dictionary<string, KeyValuePair<Xbox360Axis, short>>();
private Dictionary<string, KeyValuePair<Xbox360Slider, byte>> slidersDict = new Dictionary<string, KeyValuePair<Xbox360Slider, byte>>();
// Windows introduces a delay when notifying us of each key press (usually 7-15ms between each key), which causes problems with games
// like Mortal Kombat XI and Injustice 2 (at least)
// To work around this, a "poll interval" is used: when >0, inputs are buffered and sent each pollInterval millisecond
private int pollInterval = 0;
// the object that stores the pad states when they are buffered
private PadsStates padsStates;
// The mutex used when buffering inputs so that the PadsStates List is not modified concurrently by the thread listening to inputs and the one that regularly updates the virtual pads
private static readonly Mutex Mutex = new Mutex();
private ViGEmClient client;
private List<IXbox360Controller> controllers;
private List<ISet<Xbox360Button>> pressedButtons;
private Config config;
private bool enabled = true;
private List<StateListener> listeners;
public Keyboard2Xinput(String mappingFile)
{
config = new Config(mappingFile);
string pollIntervalStr = config.getCurrentMapping()["config"]["pollInterval"];
if (pollIntervalStr != null)
{
try
{
pollInterval = Int16.Parse(pollIntervalStr);
} catch (FormatException e)
{
log.Error($"Error parsing poll interval: {pollIntervalStr} is not an integer", e);
}
}
if (pollInterval > 0)
{
log.Info($"Using a poll interval of {pollInterval}");
}
else
{
log.Info($"Poll interval is 0: inputs will not be buffered");
}
InitializeAxesDict();
InitializeButtonsDict();
log.Debug("initialize dicts done.");
// start enabled?
String startEnabledStr = config.getCurrentMapping()["startup"]["enabled"];
// only start disabled if explicitly configured as such
if ((startEnabledStr != null) && ("false".Equals(startEnabledStr.ToLower())))
{
enabled = false;
}
// try to init ViGEm
try
{
client = new ViGEmClient();
}
catch (VigemBusNotFoundException e)
{
throw new ViGEmBusNotFoundException("ViGEm bus not found, please make sure ViGEm is correctly installed.", e);
}
// create pads
controllers = new List<IXbox360Controller>(config.PadCount);
string XinputData = "";
for (int i = 1; i <= config.PadCount; i++)
{
IXbox360Controller controller = client.CreateXbox360Controller();
controllers.Add(controller);
controller.FeedbackReceived +=
(sender, eventArgs) => log.Debug(
$"LM: {eventArgs.LargeMotor}, SM: {eventArgs.SmallMotor}, LED: {eventArgs.LedNumber}");
controller.Connect();
// Do NOT auto submit reports, as each submits takes milliseconds et prevents simultaneous inputs to work correctly
controller.AutoSubmitReport = false;
Thread.Sleep(1000);
int XinputSlotNum = -1;
try
{
XinputSlotNum = controller.UserIndex + 1;
XinputData += $"XINPUT{XinputSlotNum} = {i}";
XinputData += "\n";
}
catch (Exception){ }
}
File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"xinput.txt"),XinputData.ToString());
// the pressed buttons (to avoid sending reports if the pressed buttons haven't changed)
pressedButtons = new List<ISet<Xbox360Button>>(config.PadCount);
for (int i = 0; i < config.PadCount; i++)
{
pressedButtons.Add(new HashSet<Xbox360Button>());
}
// if poll interval is > 0, start the polling thread
if (pollInterval > 0)
{
padsStates = new PadsStates(controllers, pollInterval);
timer = new System.Threading.Timer(
callback: new TimerCallback(TimerTask),
state: padsStates,
dueTime: 100,
period: 2);
}
listeners = new List<StateListener>();
}
private static void TimerTask(object timerState)
{
var state = timerState as PadsStates;
List<PadState> padStates = state.GetAndFlushBuffer();
if (padStates.Count > 0)
{
bool[] padInputsChanged = new bool[state.Controllers.Count];
if (log.IsDebugEnabled)
{
log.Debug("Changing virtual controller(s) state");
}
foreach (var padState in padStates)
{
if (padState.property is Xbox360Button)
{
state.Controllers[padState.padNumber].SetButtonState((Xbox360Button)padState.property, (bool)padState.value);
}
else if (padState.property is Xbox360Axis)
{
state.Controllers[padState.padNumber].SetAxisValue((Xbox360Axis)padState.property, (short)padState.value);
}
else if (padState.property is Xbox360Slider)
{
state.Controllers[padState.padNumber].SetSliderValue((Xbox360Slider)padState.property, (byte)padState.value);
}
padInputsChanged[padState.padNumber] = true;
if (log.IsDebugEnabled)
{
log.Debug($"\t pad{padState.padNumber + 1} {padState.property.Name} {padState.value}");
}
};
submitReports(padInputsChanged, state.Controllers);
}
}
public void AddListener(StateListener listener)
{
listeners.Add(listener);
}
private void NotifyListeners(Boolean enabled)
{
listeners.ForEach(delegate (StateListener listener)
{
listener.NotifyEnabled(enabled);
});
}
/// <summary>
/// handles key events
/// </summary>
/// <param name="eventType"></param>
/// <param name="vkCode"></param>
/// <returns>1 if the event has been handled, 0 if the key was not mapped, and -1 if the exit key has been pressed</returns>
public int keyEvent(int eventType, Keys vkCode)
{
int handled = 0;
if (enabled)
{
bool[] padInputsChanged = new bool[config.PadCount];
for (int i = 0; i < config.PadCount; i++)
{
int padNumberForDisplay = i + 1;
string sectionName = "pad" + (padNumberForDisplay);
// is the key pressed mapped to a button?
string mappedButton = config.getCurrentMapping()[sectionName][vkCode.ToString()];
if (mappedButton != null)
{
if (buttonsDict.ContainsKey(mappedButton))
{
if ((eventType == WM_KEYDOWN) || (eventType == WM_SYSKEYDOWN))
{
// if we already notified the virtual pad, don't do it again
Xbox360Button pressedButton = buttonsDict[mappedButton];
if (pressedButtons[i].Contains(pressedButton))
{
handled = 1;
break;
}
// store the state of the button
pressedButtons[i].Add(pressedButton);
// only buffer inputs if pollInterval > 0
if (pollInterval == 0)
{
controllers[i].SetButtonState(pressedButton, true);
padInputsChanged[i] = true;
}
else
{
padsStates.PushState(i, pressedButton, true);
}
if (log.IsDebugEnabled)
{
log.Debug($"pad{padNumberForDisplay} {mappedButton} down");
}
}
else
{
Xbox360Button pressedButton = buttonsDict[mappedButton];
if (pollInterval == 0)
{
controllers[i].SetButtonState(pressedButton, false);
padInputsChanged[i] = true;
}
else
{
padsStates.PushState(i, pressedButton, false);
}
// remove the button state from our own set
pressedButtons[i].Remove(pressedButton);
if (log.IsDebugEnabled)
{
log.Debug($"pad{padNumberForDisplay} {mappedButton} up");
}
}
handled = 1;
break;
}
else if (axesDict.ContainsKey(mappedButton))
{
KeyValuePair<Xbox360Axis, short> axisValuePair = axesDict[mappedButton];
if ((eventType == WM_KEYDOWN) || (eventType == WM_SYSKEYDOWN))
{
if (pollInterval == 0)
{
controllers[i].SetAxisValue(axisValuePair.Key, axisValuePair.Value);
padInputsChanged[i] = true;
}
else
{
padsStates.PushState(i, axisValuePair.Key, axisValuePair.Value);
}
if (log.IsDebugEnabled)
{
log.Debug($"pad{padNumberForDisplay} {mappedButton} down");
}
}
else
{
if (pollInterval == 0)
{
controllers[i].SetAxisValue(axisValuePair.Key, 0x0);
padInputsChanged[i] = true;
}
else
{
padsStates.PushState(i, axisValuePair.Key, (short)0x0);
}
if (log.IsDebugEnabled)
{
log.Debug($"pad{padNumberForDisplay} {mappedButton} up");
}
}
handled = 1;
break;
}
else if (slidersDict.ContainsKey(mappedButton))
{
KeyValuePair<Xbox360Slider, byte> sliderValuePair = slidersDict[mappedButton];
if ((eventType == WM_KEYDOWN) || (eventType == WM_SYSKEYDOWN))
{
if (pollInterval == 0)
{
controllers[i].SetSliderValue(sliderValuePair.Key, sliderValuePair.Value);
padInputsChanged[i] = true;
}
else
{
padsStates.PushState(i, sliderValuePair.Key, sliderValuePair.Value);
}
if (log.IsDebugEnabled)
{
log.Debug($"pad{padNumberForDisplay} {mappedButton} down");
}
}
else
{
if (pollInterval == 0)
{
controllers[i].SetSliderValue(sliderValuePair.Key, 0x0);
padInputsChanged[i] = true;
}
else
{
padsStates.PushState(i, sliderValuePair.Key, (byte)0x0);
}
if (log.IsDebugEnabled)
{
log.Debug($"pad{padNumberForDisplay} {mappedButton} up");
}
}
handled = 1;
break;
}
}
}
if ((pollInterval == 0))
{
// no buffering of inputs: submit reports now
submitReports(padInputsChanged, controllers);
}
}
if (handled == 0)
{
// handle the enable toggle key even if disabled (otherwise there's not much point to it...)
string enableButton = config.getCurrentMapping()["config"][vkCode.ToString()];
if ("enableToggle".Equals(enableButton))
{
if ((eventType == WM_KEYDOWN) || (eventType == WM_SYSKEYDOWN))
{
ToggleEnabled();
if (log.IsInfoEnabled)
{
log.Info($"enableToggle down; enabled={enabled}");
}
}
handled = 1;
}
else if ("enable".Equals(enableButton))
{
if ((eventType == WM_KEYDOWN) || (eventType == WM_SYSKEYDOWN))
{
Enable();
if (log.IsInfoEnabled)
{
log.Info($"enable down; enabled={enabled}");
}
}
handled = 1;
}
else if ("disable".Equals(enableButton))
{
if ((eventType == WM_KEYDOWN) || (eventType == WM_SYSKEYDOWN))
{
Disable();
if (log.IsInfoEnabled)
{
log.Info($"disable down; enabled={enabled}");
}
}
handled = 1;
}
// key that exits the software
string configButton = config.getCurrentMapping()["config"][vkCode.ToString()];
if ("exit".Equals(configButton))
{
handled = -1;
}
else if ((configButton != null) && configButton.StartsWith("config"))
{
if ((eventType == WM_KEYDOWN) || (eventType == WM_SYSKEYDOWN))
{
int index = Int32.Parse(configButton.Substring(configButton.Length - 1));
if (log.IsInfoEnabled)
{
log.Info($"Switching to mapping {index}");
}
config.CurrentMappingIndex = index;
}
handled = 1;
}
}
if (handled == 0 && enabled && log.IsWarnEnabled)
{
log.Warn($"unmapped button {vkCode.ToString()}");
}
return handled;
}
private static void submitReports(bool[] padInputsChanged, List<IXbox360Controller> controllers)
{
for (int i = 0; i < padInputsChanged.Length; i++)
{
if (padInputsChanged[i])
{
controllers[i].SubmitReport();
if (log.IsDebugEnabled)
{
log.Debug($"Virtual controller {i + 1} state changed");
}
}
}
}
private void InitializeAxesDict()
{
// TODO create slider dict
slidersDict.Add("LT", new KeyValuePair<Xbox360Slider, byte>(Xbox360Slider.LeftTrigger, TRIGGER_VALUE));
slidersDict.Add("RT", new KeyValuePair<Xbox360Slider, byte>(Xbox360Slider.RightTrigger, TRIGGER_VALUE));
axesDict.Add("LLEFT", new KeyValuePair<Xbox360Axis, short>(Xbox360Axis.LeftThumbX, AXIS_NEG_VALUE));
axesDict.Add("LRIGHT", new KeyValuePair<Xbox360Axis, short>(Xbox360Axis.LeftThumbX, AXIS_POS_VALUE));
axesDict.Add("LUP", new KeyValuePair<Xbox360Axis, short>(Xbox360Axis.LeftThumbY, AXIS_POS_VALUE));
axesDict.Add("LDOWN", new KeyValuePair<Xbox360Axis, short>(Xbox360Axis.LeftThumbY, AXIS_NEG_VALUE));
axesDict.Add("RLEFT", new KeyValuePair<Xbox360Axis, short>(Xbox360Axis.RightThumbX, AXIS_NEG_VALUE));
axesDict.Add("RRIGHT", new KeyValuePair<Xbox360Axis, short>(Xbox360Axis.RightThumbX, AXIS_POS_VALUE));
axesDict.Add("RUP", new KeyValuePair<Xbox360Axis, short>(Xbox360Axis.RightThumbY, AXIS_POS_VALUE));
axesDict.Add("RDOWN", new KeyValuePair<Xbox360Axis, short>(Xbox360Axis.RightThumbY, AXIS_NEG_VALUE));
}
private void InitializeButtonsDict()
{
buttonsDict.Add("UP", Xbox360Button.Up);
buttonsDict.Add("DOWN", Xbox360Button.Down);
buttonsDict.Add("LEFT", Xbox360Button.Left);
buttonsDict.Add("RIGHT", Xbox360Button.Right);
buttonsDict.Add("A", Xbox360Button.A);
buttonsDict.Add("B", Xbox360Button.B);
buttonsDict.Add("X", Xbox360Button.X);
buttonsDict.Add("Y", Xbox360Button.Y);
buttonsDict.Add("START", Xbox360Button.Start);
buttonsDict.Add("BACK", Xbox360Button.Back);
buttonsDict.Add("GUIDE", Xbox360Button.Guide);
buttonsDict.Add("LB", Xbox360Button.LeftShoulder);
buttonsDict.Add("LTB", Xbox360Button.LeftThumb);
buttonsDict.Add("RB", Xbox360Button.RightShoulder);
buttonsDict.Add("RTB", Xbox360Button.RightThumb);
}
public void Close()
{
log.Info("Closing");
foreach (IXbox360Controller controller in controllers)
{
log.Debug($"Disconnecting {controller.ToString()}");
controller.Disconnect();
}
log.Debug("Disposing of ViGEm client");
client.Dispose();
}
public void Enable()
{
enabled = true;
NotifyListeners(enabled);
}
public void Disable()
{
enabled = false;
NotifyListeners(enabled);
}
public void ToggleEnabled()
{
enabled = !enabled;
NotifyListeners(enabled);
}
public Boolean IsEnabled()
{
return enabled;
}
/// <summary>Class <c>PadState</c> represents a XBox360 button, axis or trigger states.<br/>
/// It's used when the poll intervall is >0 to store the pad states that will be passed to the virtual pads during the next update.</summary>
private class PadState : IEquatable<PadState>
{
public int padNumber;
public Xbox360Property property;
public Object value;
public DateTime timestamp;
public PadState(int padNumber, Xbox360Property button, Object state)
{
this.padNumber = padNumber;
this.property = button;
this.value = state;
timestamp = DateTime.UtcNow;
}
public bool Equals(PadState other)
{
// ignore value for equals, as equals is used to check if a state is already in a list to avoid having both 'button down' and a 'button up' states in the list
return (padNumber == other.padNumber) && (property.Equals(other.property));
}
}
private class PadsStates
{
public readonly List<PadState> Buffer = new List<PadState>();
private int PollInterval;
public List<IXbox360Controller> Controllers { get; }
public PadsStates(List<IXbox360Controller> controllers, int pollInteval)
{
Controllers = controllers;
PollInterval = pollInteval;
}
public void PushState(int padNumber, Xbox360Property button, Object state)
{
PadState padState = new PadState(padNumber, button, state);
Mutex.WaitOne();
Buffer.Add(padState);
Mutex.ReleaseMutex();
}
public List<PadState> GetAndFlushBuffer()
{
List<PadState> result = new List<PadState>();
DateTime now = DateTime.UtcNow;
Mutex.WaitOne();
try
{
if (Buffer.Count > 0)
{
DateTime firstEntryTime = Buffer[0].timestamp;
TimeSpan timeSpan = now.Subtract(firstEntryTime);
if (timeSpan.TotalMilliseconds < PollInterval)
{
// too soon: nothing to actually process
if (log.IsDebugEnabled)
{
log.Debug($"Buffer has {Buffer.Count} inputs, but it's not time yet to consume it");
}
return result;
}
List<PadState> newBuffer = new List<PadState>(Buffer);
Buffer.Clear();
result.Add(newBuffer[0]);
for (int i = 1; i < newBuffer.Count; i++)
{
PadState padState = newBuffer[i];
// only add input if the same XBox360Property isn't already in result, so that if things go too fast, we don't process button down and up at the same time (which would appear as if the button hadn't been pressed)
timeSpan = padState.timestamp.Subtract(firstEntryTime);
if ((timeSpan.TotalMilliseconds <= PollInterval) && (!result.Contains(padState)))
{
result.Add(padState);
} else
{
Buffer.Add(padState);
}
}
}
}
finally
{
Mutex.ReleaseMutex();
}
return result;
}
}
}
} |
#include "Timestamp.h"
#include <time.h>
Timestamp::Timestamp():microSecondsSinceEpoch_(0){}
// 构造函数初始化列表的语法
Timestamp::Timestamp(int64_t microSecondsSinceEpoch):microSecondsSinceEpoch_(microSecondsSinceEpoch){}
Timestamp Timestamp::now(){
time_t ti=time(NULL);
// 获取当前时间
return Timestamp(ti);
}
std::string Timestamp::toString() const{
char buf[128]={0};
tm *tm_time=localtime(µSecondsSinceEpoch_);
snprintf(buf, 128, "%4d/%02d/%02d %02d:%02d:%02d",
// tm结构体里的原因,所以要年+1900,月+1
tm_time->tm_year + 1900,
tm_time->tm_mon + 1,
tm_time->tm_mday,
tm_time->tm_hour,
tm_time->tm_min,
tm_time->tm_sec);
// C形式的字符串
return buf;
}
// #include <iostream>
// int main()
// {
// std::cout << Timestamp::now().toString() << std::endl;
// return 0;
// } |
package com.madao.auth.config;
import com.madao.auth.handler.CustomTokenEnhancer;
import com.madao.auth.handler.CustomWebResponseExceptionTranslator;
import com.madao.auth.provider.CaptchaAuthenticationProvider;
import com.madao.auth.provider.GithubAuthenticationProvider;
import com.madao.auth.provider.SmsCodeAuthenticationProvider;
import com.madao.constant.CommonConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.bootstrap.encrypt.KeyProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.builders.ClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.builders.InMemoryClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import java.security.KeyPair;
import java.util.Arrays;
import java.util.List;
/**
* Oauth2认证配置
*
* @author GuoGuang
* @公众号 码道人生
* @gitHub https://github.com/GuoGuang
* @website https://madaoo.com
* @created 2019-09-29 7:37
*/
@Configuration
public class OauthAuthorizationServerConfig {
@Autowired
CustomUserAuthenticationConverter customUserAuthenticationConverter;
//读取密钥的配置
@Bean("keyProp")
public KeyProperties keyProperties() {
return new KeyProperties();
}
@Autowired
@Qualifier("userDetailsServiceImpl")
UserDetailsService userDetailsService;
// jwt令牌转换器
// 登录错误时执行
@Autowired
private CustomWebResponseExceptionTranslator customWebResponseExceptionTranslator;
@Autowired
private SmsCodeAuthenticationProvider smsCodeAuthenticationProvider;
@Autowired
private CaptchaAuthenticationProvider captchaAuthenticationProvider;
@Autowired
private GithubAuthenticationProvider githubAuthenticationProvider;
/**
* 配置客户端应用
* 如果要实现类似GitHub、Google那种支持开发者申请APP或者有多个不同系统的可以将此处改为从数据库动态取数据加载。
*/
@Bean
public ClientDetailsService clientDetailsService() throws Exception {
ClientDetailsServiceBuilder<InMemoryClientDetailsServiceBuilder> clients = new InMemoryClientDetailsServiceBuilder();
return clients.inMemory()
.withClient("XcWebApp")//客户端id
.secret("XcWebApp")//密码,要保密
.accessTokenValiditySeconds(CommonConst.TIME_OUT_DAY)//访问令牌有效期
.refreshTokenValiditySeconds(CommonConst.TIME_OUT_DAY)//刷新令牌有效期
//授权客户端请求认证服务的类型authorization_code:根据授权码生成令牌,
// client_credentials:客户端认证,refresh_token:刷新令牌,password:密码方式认证
.authorizedGrantTypes("authorization_code", "client_credentials", "refresh_token", "password")
.scopes("app")//客户端范围,名称自定义,必填
.and().build();
}
/**
* 构建AuthorizationServerConfig.configure(AuthorizationServerEndpointsConfigurer endpoints)
* 所需的authenticationManager
* 目前支持验证码和手机验证码登录
*/
@Bean
public AuthenticationManager authenticationManager() {
List<AuthenticationProvider> providers = List.of(smsCodeAuthenticationProvider,captchaAuthenticationProvider,githubAuthenticationProvider);
return new ProviderManager(providers);
}
/**
* 配置AccessToken加密方式
*/
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
KeyPair keyPair = new KeyStoreKeyFactory(keyProperties().getKeyStore().getLocation(),
keyProperties().getKeyStore().getSecret().toCharArray())
.getKeyPair(keyProperties().getKeyStore().getAlias(),
keyProperties().getKeyStore().getPassword().toCharArray());
converter.setKeyPair(keyPair);
//配置自定义的CustomUserAuthenticationConverter
DefaultAccessTokenConverter accessTokenConverter = (DefaultAccessTokenConverter) converter.getAccessTokenConverter();
accessTokenConverter.setUserTokenConverter(customUserAuthenticationConverter);
return converter;
}
/**
* 自定义token
*/
@Bean
public TokenEnhancerChain tokenEnhancerChain() {
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(Arrays.asList(new CustomTokenEnhancer(), jwtAccessTokenConverter()));
return tokenEnhancerChain;
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(jwtAccessTokenConverter());
}
/**
* 端点配置
* 配置用户认证
* 所有的用户认证逻辑,由authenticationManager统一管理
*/
@Bean
public AuthorizationServerTokenServices authorizationServerTokenServices() throws Exception {
AuthorizationServerEndpointsConfigurer endpoints = new AuthorizationServerEndpointsConfigurer();
endpoints.setClientDetailsService(clientDetailsService());
return endpoints.accessTokenConverter(jwtAccessTokenConverter())
.authenticationManager(authenticationManager())//认证管理器
.tokenStore(tokenStore())//令牌存储
.tokenEnhancer(tokenEnhancerChain())
.exceptionTranslator(customWebResponseExceptionTranslator)
.userDetailsService(userDetailsService).getTokenServices();//用户信息service
}
} |
{% extends "base.html" %}
{% load staticfiles %}
{% block extrastyle %}
<link href="{% static 'statistics/css/custom.css' %}" rel="stylesheet" />
<link href="{% static 'datepicker/bootstrap-datepicker.min.css' %}" rel="stylesheet" />
{% endblock %}
{% block content %}
<div class="row">
{% block main %}
<div class="col-xs-12 col-sm-9 col-md-8" >
<h1 class="text-center">Some queries</h1>
{% include 'statistics/queries.html' %}
</div>
<div class="col-xs-12 col-sm-3 col-md-4 chart-container" >
<!-- Modal panels -->
<div class="panel-group" >
<div class="panel panel-info">
<div class="panel-heading text-center" data-toggle="collapse" href="#collapse-one" >
<h4>
<span class="glyphicon glyphicon-stats" ></span>
Unique listeners - last 30 days
</h4>
</div>
<div id="collapse-one" class="panel-collapse collapse in" >
<div class="panel-body" >
<canvas id="last-30-days" ></canvas>
</div>
</div>
</div>
</div>
<div class="panel-group" >
<div class="panel panel-info">
<div class="panel-heading text-center" data-toggle="collapse" href="#collapse-two" >
<h4>
<span class="glyphicon glyphicon-stats" ></span>
Unique listeners - last year
</h4>
</div>
<div id="collapse-two" class="panel-collapse collapse in" >
<div class="panel-body" >
<canvas id="last-months" ></canvas>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
<!-- Chart.js -->
<script src="{% static 'chartjs/Chart.min.js' %}" ></script>
<script>
//Chart.defaults.global.responsive = true;
jQuery.get('{% url "listeners-per-day" %}', function(data) {
var ctx = $("#last-30-days").get(0).getContext("2d");
new Chart(ctx).Line(data, {'responsive': true});
});
jQuery.get('{% url "listeners-per-month" %}', function(data) {
var ctx = $("#last-months").get(0).getContext("2d");
new Chart(ctx).Line(data, {'responsive': true});
});
</script>
</div>
<div class="container" >
<div class="row" style="background-color:white;">
<div class="col-lg-12 text-center" >
<h1>Podcasts' stats</h1>
<form class="form-inline text-left" role="form" >
<div class="form-group ">
<label for="podcast-name">Podcast name:</label>
{% csrf_token %}
<input type="text"
class="form-control"
id="podcast-name"
placeholder="Podcast name to consult"
name="podcast-name" />
</div>
</form>
<div class="table-responsive" >
<table class="table table-condensed table-hover" >
<thead>
<tr>
<th colspan="2" >Podcast</th>
<th>Unique listeners count</th>
<th>Total times played</th>
<th>Average - listeners / times played </th>
</tr>
</thead>
<tbody id="podcast-stats-content" >
<tr class="tmp-loading">
<td colspan="5" class="text-center" >
<img src="{% static 'images/loading.gif' %}" alt="loading" title="loading ... "/>
Loading stats ... please wait
</td>
</tr>
</tbody>
</table>
</div>
<script>
var PODCAST_STATS = "{% url 'listeners-per-podcast' %}";
var podcast_ids = [];
var COVERS_DIR = "{% static 'images/covers/' %}";
jQuery(document).ready(function(){
loadPodcastStats();
// Form-filtering
jQuery('#podcast-name').keyup(function( event ) {
var podcastName = jQuery(this).val();
if ( podcastName.length > 0 ) {
var request = jQuery.ajax({
type: 'POST',
url: PODCAST_STATS,
dataType: 'json',
data: {
'csrfmiddlewaretoken': jQuery('[name=csrfmiddlewaretoken]').val(),
'podcast_name': podcastName,
}
});
request.done(function(json, httpStatusCode){
fillChart(json, httpStatusCode);
});
request.fail(function(jqXHR, httpStatusCode){
jQuery('#podcast-stats-content > *').fadeOut('slow', function(){
jQuery('#podcast-stats-content > *').remove();
jQuery('#podcast-stats-content').append('<tr><td colspan="5">Unable to retrive stats</td></tr>');
});
});
} else {
loadPodcastStats();
}
}).keydown(function( event ) {
if ( event.which == 13 ) {
event.preventDefault();
}
});
// End form-filtering
});
function fillChart(json, httpStatusCode){
jQuery('#podcast-stats-content > *').fadeOut('slow', function(){
jQuery('#podcast-stats-content > *').remove();
jQuery.each(json, function(k, v){
$row = '<tr>';
$row += '<td id="cell-{0}" ></td>'.format(v[0]);
$row += '<td class="text-left" >{0}</td>'.format('<span>'+v[1]+'</span>');
$row += '<td>{0}</td>'.format(v[2]);
$row += '<td>{0}</td>'.format(v[3]);
$row += '<td>{0}</td>'.format(v[4]);
$row += '</tr>';
podcast_ids.push(v[0]);
jQuery('#podcast-stats-content').append($row);
});
if (podcast_ids.length > 0) {
// Search for images
for (var i in podcast_ids){
var podcast_id = podcast_ids[i];
var request = jQuery.ajax({
type: 'GET',
url: '/stats/podcast_thumbnail/{0}/'.format(podcast_id), // Hardcoded S:
dataType: 'json'
});
request.done(function(json){
$img = '<img class="img-responsive img-thumbnail"';
$img += ' src="{0}" width="32" height="32" />'.format(COVERS_DIR + json.image);;
jQuery('#cell-' + json.id ).html($img);
});
} // End for
podcast_ids.length = 0; // empties the array
} else {
jQuery('#podcast-stats-content').append('<tr><td colspan="5">No podcasts with that name ... </td></tr>');
}
});
}
function loadPodcastStats(){
var request = jQuery.ajax({
type: 'GET',
url: PODCAST_STATS,
dataType: 'json'
});
request.done(function(json, httpStatusCode){
// Fills the chart
fillChart(json, httpStatusCode);
});
request.fail(function(jqXHR, textStatus){
jQuery('#podcast-stats-content > *').fadeOut('slow', function(){
jQuery('#podcast-stats-content > *').remove();
jQuery('#podcast-stats-content').append('<tr><td colspan="5">Unable to retrive stats</td></tr>');
});
});
}//End loadPodcastStats function
</script>
</div>
</div>
</div>
{% endblock %}
{% block footer %}
{% endblock %} |
import './globals.css'
import {getServerSession} from "next-auth";
import SideBar from "@/components/SideBar";
import React from "react";
import Login from "@/components/Login";
import {authOptions} from "@/lib/auth";
import {NextProvider} from "@/components/SessionProvider";
import ClientProvider from "@/components/ClientProvider";
export default async function RootLayout({
children,
}: {
children: React.ReactNode
}) {
const session = await getServerSession(authOptions);
return (
<html lang="en">
<head/>
<body>
<NextProvider session={session}>
{!session ? (
<Login/>
) : (
<div className="flex bg-[#343541]">
<div
className="bg-[#202123] text-white max-w-xs h-screen overflow-auto md:min-w-[20rem]">
<SideBar/>
</div>
<ClientProvider/>
<div className="bg-[#343541] flex-1">
{children}
</div>
</div>
)}
</NextProvider>
</body>
</html>
)
} |
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
public function login(){
return view('login/login');
}
public function register(){
return view('login/register');
}
public function store_user(Request $request){
$validatedData = $request->validate([
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8',
're_password' => 'required|string|min:8|same:password',
'clave' => 'required|string|min:4',
're_clave' => 'required|string|min:4|same:clave',
'dni' => 'required|string|regex:/^[0-9]{8}$/|unique:users',
]);
$user = new User();
$user->name = $request->input('name');
$user->last_name = $request->input('last_name');
$user->dni = $validatedData['dni'];
$user->email = $validatedData['email'];
$user->password = Hash::make($validatedData['password']);
$user->clave = Hash::make($validatedData['clave']);
$user->save();
return redirect()->route('login')->with('success', 'Usuario registrado exitosamente');
}
public function recovery_before(){
return view('login/recovery_before');
}
public function verify(Request $request){
$validatedData = $request->validate([
'email' => 'required|email',
'clave' => 'required|string|min:4',
]);
$user = User::where('email', $validatedData['email'])->first();
if (!$user || !Hash::check($validatedData['clave'], $user->clave)) {
return redirect()->back()->with('error', 'Credenciales incorrectas');
}
return redirect()->route('recovery', ['id' => $user->id]);
}
public function recovery($id)
{
$user = User::find($id);
return view('login/recovery', compact('user'));
}
public function recovery_user(Request $request,$id)
{
$validatedData = $request->validate([
'password' => 'required|string|min:8',
're_password' => 'required|string|min:8|same:password',
]);
$user = User::find($id);
$user->password = Hash::make($validatedData['password']);
$user->save();
return redirect()->route('login')->with('success', 'Contraseña actualizada exitosamente');
}
public function autenticacion(Request $request) {
$credentials = $request->validate([
'email' => 'required|string|email|max:255',
'password' => 'required|string',
]);
$user = User::where('email', $credentials['email'])->first();
if ($user && $user->estado != 1) {
return back()->withErrors(['error' => 'Tu cuenta está inactiva. Contacta al administrador.']);
}
if (Auth::attempt($credentials)) {
return redirect()->route('start')->with('success', 'Conexión exitosa');
} else {
return back()->withErrors(['error' => 'Credenciales inválidas'])->withInput($request->only('email'));
}
}
public function logout(Request $request){
$user = Auth::user();
Auth::logout();
return view('login/login');
}
} |
import { ICell } from "../types/board";
interface ITurnInfo {
from: ICell;
to: ICell;
}
class GameHelper {
private lastThreePlayerTurns: ITurnInfo[] = [];
private lastThreeAITurns: ITurnInfo[] = [];
calculatePossibleMoves = (
row: number,
col: number,
board: number[][]
): ICell[] => {
const result: ICell[] = [];
//TOP
for (let i = row; i > 0; i--) {
if (board[i - 1][col] !== 0) {
result.push({ row: i, col });
break;
} else if (i - 1 === 0) {
result.push({ row: i - 1, col });
break;
}
}
//BOT
for (let i = row; i < 4; i++) {
if (board[i + 1][col] !== 0) {
result.push({ row: i, col });
break;
} else if (i + 1 === 4) {
result.push({ row: i + 1, col });
break;
}
}
//LEFT
for (let i = col; i > 0; i--) {
if (board[row][i - 1] !== 0) {
result.push({ row, col: i });
break;
} else if (i - 1 === 0) {
result.push({ row, col: i - 1 });
break;
}
}
//RIGHT
for (let i = col; i < 4; i++) {
if (board[row][i + 1] !== 0) {
result.push({ row, col: i });
break;
} else if (i + 1 === 4) {
result.push({ row, col: i + 1 });
break;
}
}
//TOP RIGHT DIAGONAL
for (let i = row, j = col; i > 0 && j < 4; i--, j++) {
if (board[i - 1][j + 1] !== 0) {
if (i !== row || j !== col) result.push({ row: i, col: j });
break;
} else if (i - 1 === 0 || j + 1 === 4) {
result.push({ row: i - 1, col: j + 1 });
break;
}
}
//TOP LEFT DIAGONAL
for (let i = row, j = col; i > 0 && j > 0; i--, j--) {
if (board[i - 1][j - 1] !== 0) {
if (i !== row || j !== col) result.push({ row: i, col: j });
break;
} else if (i - 1 === 0 || j - 1 === 0) {
result.push({ row: i - 1, col: j - 1 });
break;
}
}
//BOT RIGHT DIAGONAL
for (let i = row, j = col; i < 4 && j < 4; i++, j++) {
if (board[i + 1][j + 1] !== 0) {
if (i !== row || j !== col) result.push({ row: i, col: j });
break;
} else if (i + 1 === 4 || j + 1 === 4) {
result.push({ row: i + 1, col: j + 1 });
break;
}
}
//BOT LEFT DIAGONAL
for (let i = row, j = col; i < 4 && j > 0; i++, j--) {
if (board[i + 1][j - 1] !== 0) {
if (i !== row || j !== col) result.push({ row: i, col: j });
break;
} else if (i + 1 === 4 || j - 1 === 0) {
result.push({ row: i + 1, col: j - 1 });
break;
}
}
return result.filter((cell) => {
if (!(cell.row === row && cell.col === col)) return cell;
});
};
checkForWin = (board: number[][], side: number): boolean => {
//left -> right
for (let i = 0; i < 5; i++) {
let sum = 0;
for (let j = 0; j < 5; j++) {
if (board[i][j] === side) {
sum += board[i][j];
}
}
if (sum === side * 3) {
const resultCollumn = [];
for (let k = 0; k < 5; k++) resultCollumn.push(board[i][k]);
// console.log(resultCollumn.join(""));
let count = 0;
for (let m = 0; m < resultCollumn.length - 1; m++) {
if (resultCollumn[m] === side && resultCollumn[m + 1] === side)
count++;
}
if (count === 2) {
return true;
}
}
}
//top -> bot
for (let i = 0; i < 5; i++) {
let sum = 0;
for (let j = 0; j < 5; j++) {
if (board[j][i] === side) {
sum += board[j][i];
}
}
if (sum === side * 3) {
const resultCollumn = [];
for (let k = 0; k < 5; k++) resultCollumn.push(board[k][i]);
// console.log(resultCollumn.join(""));
let count = 0;
for (let m = 0; m < resultCollumn.length - 1; m++) {
if (resultCollumn[m] === side && resultCollumn[m + 1] === side)
count++;
}
if (count === 2) {
return true;
}
}
}
// right top diagonal
for (let i = 2; i < 5; i++) {
let sum = 0;
for (let j = 0; j < i + 1; j++) {
if (board[i - j][j] === side) {
sum += board[i - j][j];
}
}
if (sum === side * 3) {
const resultDiagonal = [];
for (let k = 0; k < i + 1; k++) {
resultDiagonal.push(board[i - k][k]);
// console.log(resultDiagonal.join(""));
let count = 0;
for (let m = 0; m < resultDiagonal.length - 1; m++) {
if (resultDiagonal[m] === side && resultDiagonal[m + 1] === side)
count++;
}
if (count === 2) {
return true;
}
}
}
}
// right bot diagonal
for (let j = 2; j >= 0; j--) {
let sum = 0;
for (let i = 0; i < 5 - j; i++) {
if (board[i][j + i] === side) {
sum += board[i][j + i];
}
}
if (sum === side * 3) {
const resultDiagonal = [];
for (let k = 0; k < 5 - j; k++) {
resultDiagonal.push(board[k][j + k]);
// console.log(resultDiagonal.join(""));
let count = 0;
for (let m = 0; m < resultDiagonal.length - 1; m++) {
if (resultDiagonal[m] === side && resultDiagonal[m + 1] === side)
count++;
}
if (count === 2) {
return true;
}
}
}
}
return false;
};
addPlayerTurn = (from: ICell, to: ICell) => {
if (this.lastThreePlayerTurns.length === 3) {
this.lastThreePlayerTurns.shift();
}
this.lastThreePlayerTurns.push({ from, to });
};
addAITurn = (from: ICell, to: ICell) => {
if (this.lastThreeAITurns.length === 3) {
this.lastThreeAITurns.shift();
}
this.lastThreeAITurns.push({ from, to });
};
checkForDraw = (): boolean => {
console.log("Last 3 turns human", this.lastThreePlayerTurns);
console.log("Last 3 turns AI", this.lastThreeAITurns);
if (
this.lastThreeAITurns.length < 3 ||
this.lastThreePlayerTurns.length < 3
)
return false;
const aiFirst = this.lastThreeAITurns[0];
const sameAITurns = this.lastThreeAITurns.filter(
(info) =>
info.from.row === aiFirst.from.row &&
info.from.col === aiFirst.from.col &&
info.to.row === aiFirst.to.row &&
info.to.col === aiFirst.to.col
);
if (sameAITurns.length !== 2) return false;
if (
this.lastThreeAITurns[0].from.col !== this.lastThreeAITurns[1].to.col ||
this.lastThreeAITurns[0].from.row !== this.lastThreeAITurns[1].to.row
)
return false;
const playerFirst = this.lastThreePlayerTurns[0];
const samePlayerTurns = this.lastThreePlayerTurns.filter(
(info) =>
info.from.row === playerFirst.from.row &&
info.from.col === playerFirst.from.col &&
info.to.row === playerFirst.to.row &&
info.to.col === playerFirst.to.col
);
if (samePlayerTurns.length !== 2) return false;
if (
this.lastThreePlayerTurns[0].from.col !==
this.lastThreePlayerTurns[1].to.col ||
this.lastThreePlayerTurns[0].from.row !==
this.lastThreePlayerTurns[1].to.row
)
return false;
return true;
};
estimateNow = (board: number[][]): number => {
const side = 1;
let result = 0;
//left -> right
for (let i = 0; i < 5; i++) {
let sum = 0;
for (let j = 0; j < 5; j++) {
if (board[i][j] === side) {
sum += board[i][j];
}
}
if (sum === 2) result += 0.2;
else if (sum === 3) result += 0.3;
}
//top -> bot
for (let i = 0; i < 5; i++) {
let sum = 0;
for (let j = 0; j < 5; j++) {
if (board[j][i] === 1) {
sum += board[j][i];
}
}
if (sum === 2) result += 0.2;
else if (sum === 3) result += 0.3;
}
// right top diagonal
for (let i = 2; i < 5; i++) {
let sum = 0;
for (let j = 0; j < i + 1; j++) {
if (board[i - j][j] === side) {
sum += board[i - j][j];
}
}
if (sum === 2) result += 0.2;
else if (sum === 3) result += 0.3;
}
// right bot diagonal
for (let j = 2; j >= 0; j--) {
let sum = 0;
for (let i = 0; i < 5 - j; i++) {
if (board[i][j + i] === side) {
sum += board[i][j + i];
}
}
if (sum === 2) result += 0.2;
else if (sum === 3) result += 0.3;
}
return result;
};
}
export default new GameHelper(); |
<?php
use App\Models\User;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('payments', function (Blueprint $table) {
$table->id();
$table->foreignId('order_id')->references('id')->on('orders');
$table->decimal('amount'/*, 8, 2*/);
$table->string('status'/*, 255 */);
$table->string('type'/*, 255 */);
$table->foreignIdFor(User::class, 'created_by')->nullable();
$table->foreignIdFor(User::class, 'updated_by')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('payments');
}
}; |
import { freeThreadCount, getServersCanRun, growThreadMaths, HomeRamReservation, remoteExec, rootServers, ThreadCounts, weakenThreadMaths } from './main-loop-support'
import { NS, Player, Server } from './bitburner'
import {getProcesses, getServers, getServersWithPath} from './utils/get-servers'
const hackThreadMaths = (ns: NS, homeServer: Server, serverToHack: Server, maxThreads: number): ThreadCounts => {
if (maxThreads < 22) return { weaken: 0, grow: 0, hack: maxThreads }
const hackPercent = ns.hackAnalyze(serverToHack.hostname)
const wantedHackThreads = Math.ceil(0.2 / hackPercent)
const totalHacks = wantedHackThreads * 3
// const wantedGrowThreads = ns.growthAnalyze(serverToHack.hostname, 1, homeServer.cpuCores)
const wantedGrowThreads = ns.growthAnalyze(serverToHack.hostname, 2.1, 1)
const secUp = totalHacks * 0.002 + wantedGrowThreads * 0.004
const wantedWeakenThreads = weakenThreadMaths(ns, homeServer, secUp).weaken
const totalWantedThreads = wantedHackThreads + wantedGrowThreads + wantedWeakenThreads
if (totalWantedThreads <= maxThreads) {
return {
weaken: wantedWeakenThreads,
grow: wantedGrowThreads,
hack: wantedHackThreads,
}
}
// Just have to do maths based off maxThreads and just use the above ratios to figure out numbers
return {
weaken: Math.ceil(maxThreads * (totalWantedThreads / wantedWeakenThreads)),
grow: Math.floor(maxThreads * (totalWantedThreads / wantedGrowThreads)),
hack: Math.floor(maxThreads * (totalWantedThreads / wantedHackThreads)),
}
}
const hackGrowWeaken = async (ns: NS, servers: Server[], player: Player) => {
const hackLvl = player.hacking
const homeServer = servers.find((x) => x.hostname == 'home')!
// Can run scripts
const ramCost = Math.max(ns.getScriptRam('hack.js'), ns.getScriptRam('grow.js'), ns.getScriptRam('weaken.js'))
const serversCanRun = getServersCanRun(ns, servers, ramCost)
const processes = getProcesses(ns)
// Only work on servers that aren't being worked on currently
const sortedServers = servers.sort((x, y) => x.moneyMax - y.moneyMax)
// Can weaken and grow
const serversToWeakenAndGrow = sortedServers.filter((x) => x.hasAdminRights && x.moneyMax)
// Can also hack
const serversToHack = serversToWeakenAndGrow.filter((x) => hackLvl >= x.requiredHackingSkill)
let serverToHackCount = Math.min(Math.ceil(freeThreadCount(ns, serversCanRun) / 500), serversToHack.length)
for (const serverToHack of serversToHack.slice(0, serverToHackCount)) {
// Update the max threads and decrease the serverToHackCount
const maxThreads = Math.floor(freeThreadCount(ns, serversCanRun) / serverToHackCount)
if (serverToHackCount > 1) serverToHackCount -= 1
// Don't do anything to this server if we're already working on it
if (processes.some(x => { x.args.some(y => y == serverToHack.hostname)})) continue
// Need to weaken?
const minDifficulty = serverToHack.minDifficulty
const currDifficulty = ns.getServerSecurityLevel(serverToHack.hostname)
if (currDifficulty != minDifficulty) {
const threadMaths = weakenThreadMaths(ns, homeServer, currDifficulty - minDifficulty, maxThreads)
remoteExec(ns, serversCanRun, 'weaken.js', threadMaths.weaken, serverToHack.hostname, 1)
continue
}
// Need to grow?
const maxMoney = serverToHack.moneyMax
const currMoney = ns.getServerMoneyAvailable(serverToHack.hostname)
if (currMoney != maxMoney) {
const threadMaths = growThreadMaths(ns, homeServer, serverToHack, maxMoney, currMoney, maxThreads)
remoteExec(ns, serversCanRun, 'grow.js', threadMaths.grow, serverToHack.hostname, 1)
remoteExec(ns, serversCanRun, 'weaken.js', threadMaths.weaken, serverToHack.hostname, 1)
continue
}
// Should hack
const threadMaths = hackThreadMaths(ns, homeServer, serverToHack, maxThreads)
remoteExec(ns, serversCanRun, 'hack.js', threadMaths.hack, serverToHack.hostname, 3)
remoteExec(ns, serversCanRun, 'grow.js', threadMaths.grow, serverToHack.hostname, 1)
remoteExec(ns, serversCanRun, 'weaken.js', threadMaths.weaken, serverToHack.hostname, 1)
}
}
const mainLoopWork = async (ns: NS) => {
// Set
const player = ns.getPlayer()
const serversWithPath = getServersWithPath(ns)
const servers = serversWithPath.map(x => x.Server)
// Root servers and update them with the hacking script
await rootServers(ns, serversWithPath)
// Hack / Grow / Weaken
await hackGrowWeaken(ns, servers, player)
// Buy new servers
// await buyServer(ns, servers)
}
export async function main(ns: NS) {
while (true) {
try {
await mainLoopWork(ns)
} catch (ex) {
ns.tprint(`Error in main loop - ${ex}`)
}
await ns.sleep(500)
}
} |
import { HttpEventType, HttpResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { ProjectService } from '../project/project.service';
import Swal from 'sweetalert2';
import { AuthService } from 'src/app/services/auth/auth.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-projects',
templateUrl: './projects.component.html',
styleUrls: ['./projects.component.scss']
})
export class ProjectsComponent implements OnInit{
projectForm!:FormGroup
checkListForm!:FormGroup
// conceptFiles?: FileList;
// torFiles?: FileList;
selectedFiles?: FileList;
currentFile1?: File;
currentFile2?: File;
progress1 = 0;
progress2 = 0;
message = '';
documentTitle= '';
projectId!: number;
hide = true;
isLinear = false;
fileName1 = 'Upload Concept Note';
fileName2 = 'Upload TOR';
isProjectAdded = false;
isDocumentUploaded = false;
isCompleted = false;
constructor(private _formBuilder: FormBuilder, private projectService: ProjectService ,private authService: AuthService, private router: Router) {}
userId = this.authService.getUserId();
ngOnInit(): void {
this.projectForm = this._formBuilder.group({
projectName:new FormControl('',[Validators.required]),
projectManager:new FormControl('',[Validators.required]),
projectVendor:new FormControl('',[Validators.required]),
institutionName:new FormControl('',[Validators.required]),
projectSponsor:new FormControl('',[Validators.required]),
createdAt:new FormControl(''),
status:new FormControl('',[Validators.required])
})
this.checkListForm = this._formBuilder.group({
budgetIncluded: new FormControl('', Validators.required),
sponsorIncluded: new FormControl('', Validators.required),
outcomes: new FormControl('', Validators.required),
activities: new FormControl('', Validators.required),
vision: new FormControl('', Validators.required),
approved: new FormControl('', Validators.required),
qualifications: new FormControl('', Validators.required),
software: new FormControl('', Validators.required),
role: new FormControl('', Validators.required),
contact: new FormControl('', Validators.required),
gantt: new FormControl('', Validators.required),
policies: new FormControl('', Validators.required)
})
}
onClick(){
if(this.projectId != null && this.checkListForm.valid){
let marks = 0
if (this.checkListForm.get('budgetIncluded')?.value === 'Yes') {
marks = marks + 5;
}else if(this.checkListForm.get('sponsorIncluded')?.value === 'Yes'){
marks = marks + 5;
}else if(this.checkListForm.get('outcomes')?.value === 'Yes'){
marks = marks + 5;
}else if(this.checkListForm.get('vision')?.value === 'Yes'){
marks = marks + 5;
}else if(this.checkListForm.get('activities')?.value === 'Yes'){
marks = marks + 5;
}else if(this.checkListForm.get('approved')?.value === 'Yes'){
marks = marks + 5;
}else if(this.checkListForm.get('qualifications')?.value === 'Yes'){
marks = marks + 5;
}else if(this.checkListForm.get('policies')?.value === 'Yes'){
marks = marks + 5;
}else if(this.checkListForm.get('gantt')?.value === 'Yes'){
marks = marks + 5;
}else if(this.checkListForm.get('software')?.value === 'Yes'){
marks = marks + 5;
}else if(this.checkListForm.get('contact')?.value === 'Yes'){
marks = marks + 5;
}else if(this.checkListForm.get('role')?.value === 'Yes'){
marks = marks + 5;
}
if(marks >= 40){
Swal.fire('Success', 'You passed the checklist!', 'success');
this.isDocumentUploaded = true;
}else if(marks < 40){
Swal.fire('Error', 'You did not pass the checklist, Please correct your documents!', 'error');
this.isDocumentUploaded = false;
}
}
}
submitForm() {
if (this.checkListForm.valid) {
// console.log(this.userId);
const projectData = {
...this.checkListForm.value,
userId: this.userId // Add userId to the project data
};
this.projectService.add(projectData).subscribe({
next: (response: any) => {
// console.log(response);
Swal.fire('Success', 'Project added successfully!', 'success');
this.isProjectAdded = true; // Set isProjectAdded to true
this.projectId = response.id;
this.projectService.assign(this.userId, this.projectId).subscribe({
next: (response: any)=> {
console.log(response)
},
error: (error: any) => {
console.error(error);
}
})
},
error: (error) => {
console.error(error);
if (error.status === 409) {
Swal.fire('Error', 'A project with the same name already exists in the institution!', 'error');
} else {
Swal.fire('Error', 'Error occurred!', 'error');
}
}
});
}
}
selectFile1(event1: any): void {
if (event1.target.files && event1.target.files[0]) {
const file1: File = event1.target.files[0];
this.currentFile1 = file1;
this.fileName1 = this.currentFile1.name;
this.documentTitle = "CONCEPT NOTE"
} else {
this.fileName1 = 'Select File';
}
}
upload1(): void {
this.progress1 = 0;
if (this.currentFile1 && this.projectId != null) {
this.projectService.upload(this.currentFile1, this.projectId, this.documentTitle).subscribe({
next: (event: any) => {
this.isCompleted = true;
if (event.type === HttpEventType.UploadProgress) {
this.progress1 = Math.round(100 * event.loaded / event.total);
} else if (event instanceof HttpResponse) {
this.message = event.body.message;
// this.fileInfos = this.uploadService.getFiles();
Swal.fire('Success', 'Concept Note uploaded!', 'success');
}
},
error: (err: any) => {
console.log(err);
this.progress1 = 0;
Swal.fire('Error', 'Unexpected Error!', 'error');
// if (err.error && err.error.message) {
// this.message = err.error.message;
// } else {
// this.message = 'Could not upload the file!';
// }
this.currentFile1 = undefined;
}
});
}
}
selectFile2(event2: any): void {
if (event2.target.files && event2.target.files[0]) {
const file2: File = event2.target.files[0];
this.currentFile2 = file2;
this.fileName2 = this.currentFile2.name;
this.documentTitle = "TOR"
} else {
this.fileName2 = 'Select File';
}
}
upload2(): void {
this.progress2 = 0;
if (this.currentFile2 && this.projectId != null) {
this.projectService.upload(this.currentFile2, this.projectId, this.documentTitle).subscribe({
next: (event2: any) => {
this.isCompleted = true;
if (event2.type === HttpEventType.UploadProgress) {
this.progress2 = Math.round(100 * event2.loaded / event2.total);
} else if (event2 instanceof HttpResponse) {
this.message = event2.body.message;
// this.fileInfos = this.uploadService.getFiles();
Swal.fire('Success', 'TOR uploaded!', 'success');
}
},
error: (err: any) => {
console.log(err);
this.progress2 = 0;
this.isCompleted = false;
Swal.fire('Error', 'Unexpected Error!', 'error');
// if (err.error && err.error.message) {
// this.message = err.error.message;
// } else {
// this.message = 'Could not upload the file!';
// }
this.currentFile2 = undefined;
}
});
}
}
onConfirm(){
if(this.isDocumentUploaded && this.isProjectAdded && this.isCompleted){
Swal.fire('Success', 'Your project successfully registered, Wait for further notice.', 'success')
this.router.navigate(['/admin/projects']);
}else{
Swal.fire('Error', 'Project is not completed!', 'error')
}
}
} |
//ДЗ 23
const alert = document.querySelector('.alert');
//1. Знайти на сторінці кнопку з класом btn-primary. Призначте знайденому елементу подію onclick. Написати функцію обробки події onclick, що додає CSS-клас alert-primary до елемента з id = alert та змінює значення властивості textContent цього елемента на "A simple primary alert—check it out!".
const button = document.querySelector('.btn-primary');
button.onclick = function () {
alert.classList.add('alert-primary');
alert.textContent = 'A simple primary alert—check it out!';
};
//2. Знайти на сторінці кнопку з класом btn-secondary. Додати до кнопки прослуховувач події "click". Написати функцію обробки події click, що додає CSS-клас alert-primary до елемента з id = alert та змінює значення властивості textContent цього елемента на "A simple secondary alert—check it out!"
const button2 = document.querySelector('.btn-secondary');
button2.addEventListener('click', function () {
alert.classList.add('alert-primary');
alert.textContent = 'A simple secondary alert—check it out!';
});
//3.Знайти на сторінці кнопку з класом btn-success. Додати до кнопки прослуховувач події "mouseover". Написати функцію обробки події mouseover, що додає CSS-клас alert-success до елемента з id = alert та змінює значення властивості textContent цього елемента на "A simple success alert—check it out!"
const button3 = document.querySelector('.btn-success');
button3.addEventListener('mouseover', function () {
alert.classList.add('alert-success');
alert.textContent = 'A simple success alert—check it out!';
});
//Додати до кнопки прослуховувач події "mouseout". Написати функцію обробки події mouseout, що видаляє CSS-клас alert-success з елемента alert та змінює значення властивості textContent цього елемента на пустий рядок.
button3.addEventListener('mouseout', function () {
alert.classList.remove('alert-success');
alert.textContent = '';
});
//4. Знайти на сторінці кнопку з класом btn-danger. Додати до кнопки прослуховувач події "focus". Написати функцію обробки події focus, що додає CSS-клас alert-danger до елемента з id = alert та змінює значення властивості textContent цього елемента на "A simple danger alert—check it out!" Додати до кнопки прослуховувач події "focusout". Написати функцію обробки події focusout, що видаляє CSS-клас alert-danger з елемента alert та змінює значення властивості textContent цього елемента на пустий рядок.
const button4 = document.querySelector('.btn-danger');
button4.addEventListener('focus', function () {
alert.classList.add('alert-danger');
alert.textContent = 'A simple danger alert—check it out!';
});
//Додати до кнопки прослуховувач події "focusout". Написати функцію обробки події focusout, що видаляє CSS-клас alert-danger з елемента alert та змінює значення властивості textContent цього елемента на пустий рядок.
button4.addEventListener('focusout', function () {
alert.classList.remove('alert-danger');
alert.textContent = '';
});
//5.Знайти на сторінці кнопки з класом btn-dark та btn-light. Написати функцію toggleMode, що перемикає клас «dark-mode» елемента document.body за допомогою методу classList.toggle(). Одночасно при перемиканні класу dark-mode потрібно приховувати або показувати відповідну кнопку. Якщо ввімкнено режим dark-mode, показати кнопку btn-light та сховати кнопку dark-mode, і навпаки, якщо вимкнено режим dark-mode, показати кнопку btn-dark та сховати кнопку btn-light
const darkButton = document.querySelector('.btn-dark');
const lightButton = document.querySelector('.btn-light');
function toggleMode() {
const body = document.body;
body.classList.toggle('dark-mode');
if (body.classList.contains('dark-mode')) {
darkButton.style.display = 'none';
lightButton.style.display = 'block';
} else {
darkButton.style.display = 'block';
lightButton.style.display = 'none';
}
};
darkButton.addEventListener('click', toggleMode);
lightButton.addEventListener('click', toggleMode);
//6. Знайти на сторінці кнопку з класом btn-info. Додати до кнопки прослуховувач події "keypress". Написати функцію обробки події keypress, що перевіряє, чи є натиснута клавіша, клавішею "Enter". Якщо це так, типову дію події потрібно скасовувати за допомогою методу event.preventDefault(). Після скасування дії за замовчуванням, додати CSS-клас alert-info до елемента з id = alert та змінити значення властивості textContent цього елемента на "A simple info alert—check it out!";
const button5 = document.querySelector('.btn-info');
button5.addEventListener('keypress', function (event) {
if (event.key === "Enter") {
event.preventDefault();
alert.classList.add('alert-info');
alert.textContent = 'A simple info alert—check it out!';
}
});
//7.Знайти на сторінці всі селектори .card. Використовуючи цмкл for, вивести на консоль вміст кожного елемента з класом .card-title
const elementCards = document.querySelectorAll('.card');
for (i = 0; i < elementCards.length; i++) {
const titleCards = document.querySelectorAll('.card-title');
console.log(titleCards[i].textContent);
};
//8.Знайти на сторінці всі селектори .card. Використовуючи цикл for, знайти для кожного елемента .card кнопку з класом .add-to-cart, додати для кожної кнопки обробник події click, що викликає функцію, яка виводить на консоль вміст кожного елемента з класом .card-title
const cards = document.querySelectorAll('.card');
for (const card of cards) {
const addToCartButton = card.querySelector('.add-to-cart');
addToCartButton.addEventListener('click', () => {
const cardTitle = card.querySelector('.card-title');
console.log(cardTitle.textContent);
});
} |
import Foundation
import Utility
import Networking
class AddFolderInteractor {
// MARK: Properties
private weak var viewController: AddFolderViewController?
private let apiService = NetworkManager.shared.apiService
private let formatterService = UtilityManager.shared.formatterService
// MARK: - Constructor
init(viewController: AddFolderViewController?) {
self.viewController = viewController
}
// MARK: - Validations
func validateFolderName(text: String?) {
guard let text = text, !text.trimmingCharacters(in: .whitespaces).isEmpty else {
viewController?.darkLineView.backgroundColor = k_redColor
setAddButton(enable: false)
return
}
let nameValid = formatterService.validateFolderNameFormat(enteredName: text)
viewController?.darkLineView.backgroundColor = nameValid ? k_sideMenuColor : k_redColor
setAddButton(enable: nameValid && self.viewController?.selectedHexColor.isEmpty == false)
}
func validFolderName(text: String?) -> Bool {
return formatterService.validateFolderNameFormat(enteredName: text ?? "")
}
func setAddButton(enable: Bool) {
viewController?.addButton.isEnabled = enable
}
// MARK: - API Call
func createCustomFolder(name: String, colorHex: String) {
apiService.createCustomFolder(name: name, color: colorHex) { [weak self] (result) in
DispatchQueue.main.async {
switch(result) {
case .success(let value):
DPrint("value:", value)
if let folder = value as? Folder {
self?.viewController?.delegate?.didAddFolder(folder)
}
self?.viewController?.dismiss(animated: true, completion: nil)
case .failure(let error):
DPrint("error:", error)
self?.viewController?.showAlert(with: Strings.AppError.foldersError.localized,
message: error.localizedDescription,
buttonTitle: Strings.Button.closeButton.localized
)
}
}
}
}
} |
import React from "react";
import FormErrors from "./FormErrors";
function QuestionForm(props) {
const { errors = [], onSubmit = () => {} } = props;
const handleSubmit = event => {
event.preventDefault();
const formData = new FormData(event.currentTarget);
onSubmit({
title: formData.get("title"),
body: formData.get("body")
});
};
return (
<form onSubmit={handleSubmit} className="QuestionForm">
<div>
<label htmlFor="title">Title</label> <br />
<input name="title" id="title" />
<FormErrors forField="title" errors={errors} />
</div>
<div>
<label htmlFor="body">Body</label> <br />
<textarea name="body" id="body" cols="60" rows="4" />
<FormErrors forField="body" errors={errors} />
</div>
<div>
<input type="submit" value="Submit" />
</div>
</form>
);
}
export default QuestionForm; |
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:doclink/patient/common/top_bar_area.dart';
import 'package:doclink/patient/generated/l10n.dart';
import 'package:doclink/patient/model/custom/categories.dart';
import 'package:doclink/patient/screen/medical_prescription_screen/medical_prescription_screen_controller.dart';
import 'package:doclink/utils/color_res.dart';
import 'package:doclink/utils/my_text_style.dart';
class MedicalPrescriptionScreen extends StatelessWidget {
const MedicalPrescriptionScreen({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
final controller = Get.put(MedicalPrescriptionScreenController());
return Scaffold(
backgroundColor: ColorRes.white,
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TopBarArea(title: PS.current.medicalPrescription),
const SizedBox(
height: 8,
),
Expanded(
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ListView.builder(
itemCount:
controller.medicalPrescription?.addMedicine?.length ??
0,
primary: false,
shrinkWrap: true,
padding: EdgeInsets.zero,
itemBuilder: (context, index) {
AddMedicine? data =
controller.medicalPrescription?.addMedicine?[index];
return Container(
color: index % 2 != 0
? ColorRes.snowDrift
: ColorRes.whiteSmoke,
padding: const EdgeInsets.all(15),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Text(
data?.title ?? '',
style: MyTextStyle.montserratSemiBold(
size: 15,
color: ColorRes.charcoalGrey),
),
const SizedBox(
height: 3,
),
Text(
data?.mealTime == 0
? PS.current.afterMeal
: PS.current.beforeMeal,
style: MyTextStyle.montserratSemiBold(
size: 13,
color: ColorRes.battleshipGrey),
),
const SizedBox(
height: 3,
),
Text(
data?.dosage ?? '',
style: MyTextStyle.montserratRegular(
size: 13,
color: ColorRes.battleshipGrey),
),
],
),
),
Row(
children: [
Text(
'${data?.quantity ?? 0}',
style: MyTextStyle.montserratBold(
size: 24,
color: ColorRes.charcoalGrey),
),
],
),
],
),
Visibility(
visible:
(data?.notes == null || data!.notes!.isEmpty)
? false
: true,
child: Container(
margin: const EdgeInsets.only(top: 8),
child: Text(
data?.notes == null
? ''
: '${PS.current.notes} :- ${data?.notes}',
style: MyTextStyle.montserratRegular(
size: 13, color: ColorRes.tuftsBlue),
),
),
)
],
),
);
},
),
Visibility(
visible: (controller.medicalPrescription?.notes == null ||
controller.medicalPrescription!.notes!.isEmpty)
? false
: true,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.all(15),
child: Text(
PS.current.notes,
style: MyTextStyle.montserratSemiBold(
size: 15, color: ColorRes.charcoalGrey),
),
),
Container(
color: ColorRes.snowDrift,
width: double.infinity,
padding: const EdgeInsets.all(10),
child: Text(
controller.medicalPrescription?.notes ?? '',
style: MyTextStyle.montserratMedium(
color: ColorRes.nobel,
),
),
),
],
),
)
],
),
),
),
GetBuilder(
init: controller,
builder: (context) {
return InkWell(
onTap: controller.createPdf,
child: Container(
padding: const EdgeInsets.symmetric(
vertical: 15, horizontal: 10),
decoration: const BoxDecoration(
gradient: MyTextStyle.linearTopGradient),
alignment: Alignment.center,
child: SafeArea(
top: false,
child: Text(
PS.current.downloadPrescription,
style: MyTextStyle.montserratSemiBold(
size: 17, color: ColorRes.white),
),
),
),
);
})
],
),
);
}
} |
package rocketseat.com.passin.services;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import rocketseat.com.passin.domain.attendee.Attendee;
import rocketseat.com.passin.domain.events.exceptions.EventFullException;
import rocketseat.com.passin.domain.events.exceptions.EventNotFoundException;
import rocketseat.com.passin.dto.attendee.AttendeeIdDTO;
import rocketseat.com.passin.dto.attendee.AttendeeRequestDTO;
import rocketseat.com.passin.dto.event.*;
import rocketseat.com.passin.repositories.EventRepository;
import rocketseat.com.passin.domain.events.Event;
import java.text.Normalizer;
import java.time.LocalDateTime;
import java.util.List;
@Service
@RequiredArgsConstructor
public class EventService {
private final EventRepository eventRepository;
private final AttendeeService attendeeService;
public EventListAttendees getEventsAttendee(String eventId){
List<EventAttendees> eventAttendees = this.eventRepository.findAttendeesFromEvent(eventId).orElseThrow(() -> new EventNotFoundException("Event not found with ID: " + eventId));
return new EventListAttendees(eventAttendees);
}
public EventDetailDTO getEventDetail(String eventId) {
EventResponseDTO event = this.eventRepository.getEventDetails(eventId).orElseThrow(() -> new EventNotFoundException("Event not found with ID: " + eventId));
return new EventDetailDTO(event.getId(), event.getTitle(), event.getDetails(), event.getSlug(), event.getMaximumAttendees(), event.getAttendeesAmount());
}
public EventIdDTO createEvent(EventRequestDTO eventDto){
Event newEvent = new Event();
newEvent.setTitle(eventDto.title());
newEvent.setDetails(eventDto.details());
newEvent.setMaximumAttendees(eventDto.maximumAttendees());
newEvent.setSlug(this.createSlug(eventDto.title()));
this.eventRepository.save(newEvent);
return new EventIdDTO(newEvent.getId());
}
private Event getEventById(String eventId){
return this.eventRepository.findById(eventId).orElseThrow(() -> new EventNotFoundException("Event not found with ID: " + eventId));
}
public AttendeeIdDTO registerAttendeeOnEvent(String eventId, AttendeeRequestDTO attendeeRequestDTO) {
this.attendeeService.verifyAttendeeSubscription(attendeeRequestDTO.email(), eventId);
Event event = this.getEventById(eventId);
EventCountAttendees attendeeList = this.eventRepository.findAttendeesAmountFromEvent(eventId);
if(event.getMaximumAttendees() <= attendeeList.getAttendeesAmount()) throw new EventFullException("Event is full");
System.out.println(attendeeList.getAttendeesAmount());
Attendee newAttendee = new Attendee();
newAttendee.setName(attendeeRequestDTO.name());
newAttendee.setEmail(attendeeRequestDTO.email());
newAttendee.setEvent(event);
newAttendee.setCreatedAt(LocalDateTime.now());
this.attendeeService.registerAttendee(newAttendee);
return new AttendeeIdDTO(newAttendee.getId());
}
private String createSlug(String text) {
String normalizer = Normalizer.normalize(text, Normalizer.Form.NFD);
return normalizer.replaceAll("[\\p{InCOMBINING_DIACRITICAL_MARKS}]", "")
.replaceAll("[^\\w\\s]", "")
.replaceAll("\\s+", "-")
.toLowerCase();
}
} |
import { IPatientRepository } from "../../../patient/repositories/IPatientRepository";
import { inject, injectable } from "tsyringe";
import { ITokensRepository } from "../../repositories/ITokensRepository";
import { IDateProvider } from "../../../../shared/infra/container/providers/DateProvider/IDateProvider";
import auth from "../../../../config/auth";
import { AppError } from "../../../../shared/infra/errors/appError";
import { compare } from "bcrypt";
import { sign } from "jsonwebtoken";
interface IRequest{
email: string;
password: string;
}
interface IResponse {
patient: {
name: string;
email: string;
}
token: string;
refresh_token: string;
}
@injectable()
class AuthenticateUseCase {
constructor(
@inject("PatientRepository")
private patientRepository: IPatientRepository,
@inject("TokensRepository")
private tokensRepository: ITokensRepository,
@inject("DayJsDateProvider")
private dateProvider: IDateProvider
){}
async execute({email, password}: IRequest): Promise<IResponse>{
const patient = await this.patientRepository.findByEmail(email)
const {
expires_in_token,
secret_token,
secret_refresh_token,
expires_in_refresh_token,
expires_refresh_token_days
} = auth
if(!patient){
throw new AppError("Email or password incorrect.", )
}
const passwordMatch = await compare(password, patient.password)
if(!passwordMatch){
throw new AppError("Email or password incorrect.");
}
const token = sign({}, secret_token, {
subject: patient.id,
expiresIn: expires_in_token
})
const refresh_token = sign({ email }, secret_refresh_token, {
subject: patient.id,
expiresIn: expires_in_refresh_token
})
const refresh_token_expires_date = this.dateProvider.addDays(expires_refresh_token_days)
await this.tokensRepository.create({
expires_date:refresh_token_expires_date ,
refresh_token: refresh_token,
patient_id: patient.id
})
const tokenReturn: IResponse = {
token,
patient:{
name: patient.name,
email: patient.email
},
refresh_token
}
return tokenReturn
}
}
export { AuthenticateUseCase} |
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:shop/components/auth_form.dart';
class AuthPage extends StatelessWidget {
const AuthPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
double heightAvaliable = height -
MediaQuery.of(context).padding.top -
MediaQuery.of(context).padding.bottom;
return Scaffold(
body: Stack(
children: [
Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [
Color.fromRGBO(215, 117, 255, 0.5),
Color.fromRGBO(255, 188, 117, 0.5),
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
),
),
SingleChildScrollView(
child: SizedBox(
width: double.infinity,
height: heightAvaliable,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
margin: const EdgeInsets.only(bottom: 20),
padding: const EdgeInsets.symmetric(
vertical: 10,
horizontal: 70,
),
transform: Matrix4.rotationZ(-8 * pi / 180)
..translate(-10.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: Colors.deepOrange.shade900,
boxShadow: const [
BoxShadow(
blurRadius: 8,
color: Colors.black26,
offset: Offset(0, 2),
)
]),
child: Text(
'Minha Loja',
style: TextStyle(
fontSize: 45,
fontFamily: 'Anton',
color:
Theme.of(context).accentTextTheme.headline6?.color,
),
),
),
const AuthForm(),
],
),
),
)
],
),
);
}
} |
describe('App initialization', () => {
context('Verify that the app does appropriate routing' , () => {
it('Routes to the login screen if the token does not exist in the local storage', () => {
cy.clearAllLocalStorage();
cy.visit('/')
cy.url().should('include', '/login')
})
it('Routes to the login screen if the token exists but the user is not authenticated', () => {
localStorage.setItem('auth_token', 'some-token');
cy.visit('/')
cy.wait(2000)
.url()
.should('include', '/login')
})
it('Routes to the dashboard if the user is authenticated', () => {
let authUrls = {}
const apiBaseUrl = Cypress.env('REACT_APP_API_BASE_URL') ?? 'http://18.188.14.183/bingo_api/public/api'
cy.fixture('auth/auth-urls')
.then((urls) => {
authUrls = urls;
})
cy.fixture('auth/valid-user')
.then((data) => {
cy.request('POST', `${apiBaseUrl}/login`, data).then((response) => {
localStorage.setItem('auth_token', response.body.data.token);
})
});
cy.visit('/')
cy.url()
.should('include', '/dashboard')
cy.get('.dashboard')
.should('exist')
})
})
}); |
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './entity/user.entity';
import { UserController } from './user.controller';
import { UserService } from './user.service';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt';
import { JwtStrategy } from './jwt.strategy';
import { AuthService } from './auth.service';
@Module({
imports: [
TypeOrmModule.forFeature([User]),
ConfigModule,
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => ({
secret: configService.get('JWT_SECRET'),
signOptions: {
expiresIn: 3600,
},
}),
}),
],
controllers: [UserController],
providers: [UserService, AuthService, JwtStrategy],
exports: [UserService, JwtStrategy, PassportModule],
})
export class UserModule {} |
import { apiUrl } from '../../../../lib/api-url'
import { Yacht } from '../../../../types/yacht.type'
import YachtScoreCard from '../../yacht-score-card'
import Link from 'next/link'
import { Suspense } from 'react'
import DetailPlaceHolder from '../../../../components/detail-place-holder'
export async function generateStaticParams() {
const results = await fetch(`${apiUrl}/api/yacht?Limit=100`)
if (!results.ok) return []
const { Items }: { Items: Yacht[] } = await results.json()
return Items.map((item) => ({ id: item.id }))
}
async function getYacht(id: string) {
const result = await fetch(`${apiUrl}/api/yacht/${id}`)
if (!result.ok) return {}
const yacht: Yacht = await result.json()
return yacht
}
export default async function YachtScoreDetail({
params,
}: {
params: { id: string }
}) {
const yacht: Yacht = await getYacht(params.id)
return (
<div id="yacht-detail" className="m-2">
<h1>Yacht Score</h1>
<Suspense fallback={<DetailPlaceHolder />}>
<YachtScoreCard
total={yacht.Total || 0}
turns={yacht.turns && yacht.turns.length > 0 ? yacht.turns : []}
/>
</Suspense>
<Link href="/yacht/scores">Back To Scores</Link>
</div>
)
} |
import { Path, UseFormRegister } from "react-hook-form";
import { IFormValues } from "../../../interfaces/IFormValues";
interface Props {
label: string;
register: UseFormRegister<IFormValues>;
name: Path<IFormValues>;
type: "text" | "number";
error: any;
}
export const InputText = ({ label, register, name, type, error }: Props) => {
return (
<div>
<label className="block mb-2 text-xs font-medium text-gray-100 dark:text-gray-400 line-clamp-1 truncate">
{label}
</label>
<input
className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
type={type}
{...register(name, { required: true })}
/>
{error && (
<p role="alert" className="text-red-400 text-xs">
*{error}
</p>
)}
</div>
);
}; |
// state
export const state = () => ({
// series
series: [],
// posts
posts: [],
// page
page: 1,
// post
postseri: {},
// post
post: {}
})
export const getters = {
getPosts(state) {
return state.posts
}
}
// mutations
export const mutations = {
// mutation "setPostsData"
setSeriesData(state, payload) {
// set value state "posts"
state.series = payload
},
// mutation "setCategoriesData"
setPostseriData(state, payload) {
// set value state "posts"
state.postseri = payload
},
// mutation "setCategoriesData"
setPostsData(state, payload) {
// set value state "posts"
state.posts = payload
},
// mutation "setPage"
setPage(state, payload) {
// set value state "page"
state.page = payload
}
}
// actions
export const actions = {
// get Posts data
getSeriesData({ commit, state }, payload) {
// search
let search = payload ? payload : ''
// set promise
return new Promise((resolve, reject) => {
// fetching Rest API "/api/v1/admin/posts" with method "GET"
this.$axios.get(`/api/v1/admin/postseries?q=${search}&page=${state.page}`)
// success
.then((response) => {
// commit to mutation "SetPostsData"
commit('setSeriesData', response.data.data)
// resolve promise
resolve()
})
})
},
// get Posts data
getPostsData({ commit, state }, payload) {
// search
let search = payload ? payload : ''
// set promise
return new Promise((resolve, reject) => {
// fetching Rest API "/api/v1/admin/posts" with method "GET"
this.$axios.get(`/api/v1/admin/postseri/posts?q=${search}&page=${state.page}`)
// success
.then((response) => {
// commit to mutation "SetPostsData"
commit('setPostsData', response.data.data)
// resolve promise
resolve()
})
})
},
// get detail Post
getDetailSeries({ commit }, payload) {
// set promise
return new Promise((resolve) => {
// get to Rest API "/api/v1/admin/posts/:id" with method "GET"
this.$axios.get(`/api/v1/admin/postseries/${payload}`)
// success
.then(response => {
// commit to mutation "setPostData"
commit('setPostseriData', response.data.data)
// resolve promise
resolve()
})
})
},
// store post
storeSeries({ dispatch, commit }, payload) {
// set Promise
return new Promise((resolve, reject) => {
// store to Rest API "/api/v1/admin/posts" with method "POST"
this.$axios.post('/api/v1/admin/postseries', payload)
// success
.then(() => {
// dispatch action "getPostsData"
dispatch('getSeriesData')
// resolve promise
resolve()
})
.catch(error => reject(error))
})
},
// update Post
updateSeries({ dispatch, commit }, { postId, payload }) {
// set promise
return new Promise((resolve, reject) => {
// store to Rest API "/api/v1/admin/posts/:id" with method POST
this.$axios.post(`/api/v1/admin/postseries/${postId}`, payload)
// success
.then(() => {
// dispatch action "getPostsData"
dispatch('getSeriesData')
// resolve promise
resolve()
})
// error
.catch(error => reject(error))
})
},
// destroy Post
destroySeries({ dispatch, commit }, payload) {
// set promise
return new Promise((resolve, reject) => {
// delete to Rest API "/api/v1/admin/posts/:id" with method "DELETE"
this.$axios.delete(`/api/v1/admin/postseries/${payload}`)
// success
.then(() => {
// dispatch action "getPostsData"
dispatch('getSeriesData')
// resolve promise
resolve()
})
})
}
} |
/*
* Test the gradients of a model.
*
* - m: Model.
* - N: Number of samples.
* - backward: Test joint distributions in backward mode? (Otherwise forward
* mode.)
*/
function test_grad(m:TestModel, N:Integer, backward:Boolean) {
let failed <- vector(0.0, N); // failure rate in each test
let Δ <- 1.0e3; // maximum width for finite difference estimate
let ntrials <- 50; // number of trials
// ^ the interval width adapts by starting at h, dividing by 2 until either
// success or ntrials trials, after which the test is considered failed
let γ <- 1.0e-3; // acceptable failure rate
let ε <- 1.0e-2; // relative error threshold for fail
// ^ the pass criterion is that 100*(1 - γ) percent of gradients computed
// are within 100.0*ε percent of the finite difference approximation; e.g.
// with γ = 1.0e-3 and ε = 1.0e-2, that "99.9% of gradients computed are
// within 1% of the finite difference approximation"
parallel for n in 1..N {
let h <- construct<Handler>(backward, true, true);
let m' <- copy(m);
with h {
m'.initialize();
m'.simulate();
if backward {
m'.backward();
} else {
m'.forward();
}
}
/* compute gradient */
let π <- h.hoist()!;
let p <- π.eval();
π.grad(1.0);
let (x, g) <- π.args();
/* compare with finite difference estimates */
for i in 1..rows(x) {
let Δ' <- Δ; // initial interval size for finite difference
let min_fd <- inf; // closest finite difference estimate...
let min_δ <- inf; // ...and associated distance
let t <- 1;
while t <= ntrials && Δ' > 0.0 { // may == 0.0 in single precision
let y <- x;
let z <- x;
y[i] <- y[i] - 0.5*Δ';
z[i] <- z[i] + 0.5*Δ';
let q <- π.move(y)!;
let r <- π.move(z)!;
let fd <- (r - q)/Δ';
let δ <- abs(g[i] - fd);
let pass <- δ <= ε*min(abs(g[i]), abs(fd));
if δ < min_δ {
min_δ <- δ;
min_fd <- fd;
}
if pass {
/* success */
t <- ntrials + 1;
} else if t < ntrials {
/* shrink interval for finite difference and try again */
t <- t + 1;
Δ' <- 0.5*Δ';
} else {
/* fail */
t <- ntrials + 1;
warn("on component " + i + ", " + g[i] + " vs " + min_fd);
failed[n] <- failed[n] + 1.0/rows(x);
}
}
}
/* smoke test for constant */
π.constant();
}
/* check that failure rate within bounds */
let nfailed <- sum(failed)!;
let rfail <- nfailed/N;
if N > 10 && !(rfail <= γ) { // if N <= 10, smoke test only
error("***failed*** in aggregate, " + nfailed + " of " + N + " failed");
}
} |
# 6. Puerocentrismo, statualizzazione, privatizzazione
<!--
vim: spell:spelllang=it
-->
## 6.1. Novecento come secolo del bambino, e dello Stato-padre di famiglia (135)
Le democrazie liberali e le esperienze totalitarie mantengono la struttura dei codici ottocenteschi.
I cambiamenti principali sono:
* La **maggiore repressione degli abusi domestici**.
* La **definitiva abrogazione dei poteri di coazione matrimoniale e di internamento del figlio**.
Nel Novecento, lo **Stato si interessa sempre di più ai figli e alla loro educazione, per creare il cittadino ideale**, e si inserisce sempre di più all'interno della famiglia.
Ellen Key chiama il Novecento il "secolo del bambino", e si stabilisce un **puerocentrismo di Stato** nelle democrazie liberali.
A livello internazionale, si dichiarano i **diritti dell'infanzia** e si creano **società per la prevenzione delle violenze sui bambini**.
Gli Stati europei creano politiche a sostegno della "fanciullezza martoriata o abbandonata", anche per prevenire la delinquenza giovanile.
Tuttavia, **già nell'Ottocento** il bambino era il centro della famiglia:
* Se la famiglia era povera o incapace, si inserivano dei terzi per proteggere, allevare e disciplinare il figlio. Ad es., filantropi, medici, uomini di Stato.
* L'educazione pubblica obbligatoria ed i programmi per la **formazione del buon cittadino** sottraggono ai genitori il diritto di educare i propri figli.
* Nell'area tedesca il maestro era chiamato "padre di scuola".
* Altre figure pubbliche (assistenti sociali, medici, magistrati, etc.) intervengono nella vita domestica.
Il codice civile spagnolo del 1889 distingueva fra vari diritti provinciali.
* L'appendice al **diritto provinciale aragonese** del 1925 **non menzionava la patria potestà**, ma usava espressioni come **autorità paterna** o **relazioni giuridiche** fra ascendenti e discendenti.
* Il diritto nella Navarra e Vizcaya considerava **entrambi i genitori alla pari**, e **tutori e amministratori legali** dei figli.
Riguardo la disciplina dei poteri paterni si discuteva della tutela dell'infanzia, di aumentare il ruolo della madre, e di definire in maniera puntuale i casi di abuso e trascuratezza.
Durante il **Franchismo** vengono introdotte riforme ispirate al **tradizionalismo cattolico**.
## 6.2. Istituto di diritto pubblico, l'opinione di Antonio Cicu (138)
La patria potestà prevede diritti irrinunciabili ed immodificabili, con prevalenti finalità pubbliche, ed è assoggettata a controllo statale.
Secondo **Pisanelli**, l'idea fondamentale del codice civile è la **proprietà**.
Il primo libro del codice sui **diritti di famiglia** è una serie di **leggi speciali ed intermedie** fra il **codice civile e lo Statuto**.
Durante l'ottocento e novecento lo Stato allarga sempre di più la sua sfera di intervento, e accentua la **natura pubblica** del **diritto di famiglia**.
La **collocazione del diritto di famiglia** tra diritto pubblico e privato comporta delle **implicazioni politiche e culturali**, ed è un problema risalente:
* Nel **diritto medievale comune e di antico regime**, dove la distinzione era poco rilevante, la patria potestà era largamente considerata una materia di **diritto pubblico**.
* La questione assume maggiore importanza nel tardo ottocento, e nel **codice napoleonico**, si attua una **privatizzazione** del diritto di famiglia.
Le **ragioni della privatizzazione** si distinguevano fra:
* **Ragioni di praticità**, perché il codice civile comprende tutte le regole relativi ai rapporti fra pubblico e privato.
* **Ragioni di politica**.
**Antonio Cicu** era **cattolico e nazionalista**.
Propone una **concezione della famiglia** come **terzo genere fra diritto pubblico e privato**.
Riprende la divisione aristotelica fra economia, politica, ed etica.
Si unirà al fascismo, ma aveva già espresso la sua concezione della famiglia prima di quel momento.
La **volontà del padre** esprime la **volontà della famiglia** in quanto **istituzione organica**.
La **patria potestà** rappresenta un **potere teso ad un fine**, è **irrinunciabile ed imprescrittibile**, ed è considerata un **dovere**.
In caso di **inadempimento del dovere** si lede il **diritto soggettivo familiare**.
Si può **esercitare un'apposita azione giuridica** per imporre l'adempimento del dovere, **nell'interesse della famiglia**.
La **patria potestà** secondo Cicu è legittimata dalla **famiglia come unità organica**, che è diversa dalla somma degli interessi individuali dei componenti.
La **famiglia assomiglia** allo Stato, ma **non fa parte dello Stato**.
Cercare di **conciliare** la tradizionale autonomia della famiglia con lo statualismo novecentesco sarà un problema che riguarderà la destra europea.
## 6.3. Padri fascisti, per un figlio soldato e produttore (139)
I **totalitarismi novecenteschi non incidono sull'assetto** della famiglia.
Piuttosto, **aumentano l'invasività dello Stato** sia nella società che nella famiglia.
In Germania non viene prodotto un nuovo codice civile, ma si usano leggi speciali.
In Italia, anche se viene prodotto un nuovo codice civile si utilizzano comunque le leggi speciali.
I regimi di destra in Italia, Germania e Spagna proposero un modello di famiglia patriarcale, ed erano opposti al kolchoz sovietico.
Tutti erano fortemente incentrati su **politiche nataliste**.
In Italia, il dibattito sulla famiglia si intensifica intorno alla **prima guerra mondiale**:
* Marinetti ed i **futuristi** sono favorevoli alla sua dissoluzione ed al figlio di Stato.
* Gli **ideologi di destra** criticavano la diminuzione del potere paterno sui figli.
All'interno del **fascismo**:
* Secondo Mussolini, nulla poteva esistere al di fuori dello Stato.
* Secondo Pellizzi, la famiglia doveva essere considerata sia parte del diritto privato, che parte fondamentale del diritto pubblico.
* **Pompei** scrive un saggio in cui evidenziava la **contraddizione** fra la **famiglia patriarcale** di antico regime, e lo **Stato totalitario** novecentesco.
Il familismo fascista incontrava resistenze interne al movimento.
In Germania, la **fedeltà al Führer** ledeva i rapporti fra la società domestica e gli stessi poteri paterni.
I figli dovevano denunciare le idee sovversive dei genitori, il loro corpo apparteneva allo Stato.
La pedagogia tedesca sosteneva la necessità di sottrarre l'educazione dei figli ai genitori, e rimetterla ad istituti nazionali di educazione.
Il **modello di famiglia fascista** più condiviso fu la **famiglia patriarcale e maschilista**.
* Secondo **Urbani**, la famiglia tradizionale era il presupposto di uno Stato senza partiti.
* Secondo **Fanelli**, il padre indebolito dal "morbo democratico" doveva essere ricollocato in una posizione di potere, e controllato rigidamente dallo Stato.
Il **pensiero di minoranza** proponeva una **potestà condivisa fra moglie e marito**.
La madre è responsabile della gestione familiare, il padre conserva solo un diritto di controllo.
L'uomo ed i figli prendono anche il **cognome della moglie o madre**.
Il **pensiero maggioritario** proponeva il **ritorno alla gerarchia**.
Secondo **Loffredo**:
* La **famiglia** deve essere riformata in una **gerarchia**, così come lo è la società.
* La **donna** deve essere assolutamente **sottomessa all'uomo**, e si devono attuare riforme per garantirlo.
* La **famiglia** e la **identità razziale** sono strettamente legate.
**Baccigalupi** sviluppa una **concezione razzista della famiglia**.
La famiglia è fonte della razza, e la razza della famiglia va mantenuta pura.
**Maroi**:
* Afferma il **nesso** fra la **potenza dello Stato** e **la coesione della famiglia**.
* **Critica il codice del 1865** perché troppo **individualista** e di ispirazione napoleonica.
## 6.4. Ragioni della politica e del diritto, il regime fascista alla prova dei codici (143)
L'impatto del fascismo sulla famiglia non è dato dal codice, ma dalla **politica di intervento statale** sulla società.
La politica fascista della famiglia si ritrova nel codice penale del 1930.
I **reati contro la famiglia**:
* Sono reintrodotti, erano assenti nel codice penale francese del 1810, ma erano tipici della **Restaurazione italiana**.
* Includono i **maltrattamenti ai familiari**, che **non** sono più considerati **reati contro la persona**.
La **violazione degli obblighi di assistenza familiare** (art. 570) comprendono anche quelli della **patria potestà**.
È una **novità assoluta**, mentre gli articoli successivi erano già presenti nei codici ottocenteschi.
**L'abuso dei mezzi di correzione** ed i **maltrattamenti** verso **membri della famiglia** o **persone affidate** per ragioni di educazione, istruzione, cura, vigilanza e custodia sono regolati dagli artt. 571 e 572.
**La sottrazione del minore** con il suo consenso, e la **sottrazione del minore di 14 anni o infermo di mente** sono sanzionate agli art. 573 e 574.
**L'autorità di polizia** può invitare le parti a comparire per conciliare i dissidi privati.
Il **codice civile fascista** del 1942 **non sovverte l'assetto liberale** del codice del 1865.
Le proposte di rafforzare il codice non vengono accolte, ed la versione definitiva è moderata.
Per consolidare l'unità domestica si introduce il **patrimonio familiare** (art. 167).
Consiste in **beni immobili e titoli di credito inalienabili** ed i cui **frutti** sono destinati a vantaggio della famiglia.
La **condizione della madre** non peggiora, e migliore in alcuni casi.
Ad es., ottiene automaticamente il pieno esercizio della potestà quando decade il padre (art. 331).
**L'art. 147** era la **norma più importante** per il nuovo assetto statale **fascista**.
Prevede **l'obbligo dei genitori di educare i figli secondo la morale ed il sentimento fascista**.
**Considerato insieme agli artt. 330 e 333** una **educazione contraria all'ideologia di regime** poteva determinare:
* La **decadenza della patria potestà** (art. 330 c.c.)
* L'adozione dei **provvedimenti giudiziali** più adeguati al caso particolare nei **casi meno gravi** (art. 333 c.c.).
* Secondo **Foderaro**, la violazione dell'art. 147 c.c. costituiva anche una **violazione dell'art. 570 c.p.** ("condotta contraria all'ordine o alla morale delle famiglie").
**L'art. 342** dava rilevanza alla **razza dei genitori**.
Se il genitore di razza non ariana che ha figli ariani passa a nuove nozze con una persona non-ariana, perde la patria potestà sui figli, che viene trasferita ad uno degli avi di razza ariana.
Secondo **Sermonti**, lo **Stato** considera la **protezione dell'infanzia e giovinezza come una funzione pubblica**.
Pertanto, il **padre è un delegato dello Stato nell'educazione dei figli come produttori-soldati**.
Il padre non è interamente libero nello scegliere come educare i figli.
Il legislatore fascista ha imposto il dovere di educare i figli in maniera **conforme alla morale e sentimento nazionale fascista**.
L'art. 147 non ha una portata solo morale, ma la sua violazione ha effetti giuridici.
L'art. 330 prevede la decadenza della patria potestà per violazioni dei doveri che portano grave pregiudizio al figlio.
La violazione dell'art. 147 deve essere inteso come un **pregiudizio spirituale**, che legittima **l'intervento del tribunale**.
La **caduta del regime** porterà alla riscrittura dell'art. 147 e l'abrogazione dell'art. 342.
## 6.5. Francia di Vichy ed eterno femminino (146)
La Francia viene occupata nel 1940.
Il nuovo regime attua riforme che introducono i valori familisti e ruralisti di destra, adattati alla tradizione francese.
Il **Le Play** è un **precursore** della nuova ideologia.
Rigetta la disciplina del codice, perché antipatriarcale.
Prevede tre modelli di famiglia:
La **famiglia patriarcale**:
* È il modello più stabile, dove tutti i figli si sposano e rimangono presso i genitori, ed imparano le tradizioni.
* Nelle buone epoche, quando le consuetudini si conservano, il regime si adatta ai cambiamenti delle circostanze.
* Nelle epoche di corruzione, quando le consuetudini si alterano, degenera in routine.
La **famiglia instabile**:
* È il modello più instabile, dove tutti i figli si allontanano appena sono autosufficienti.
* Il padre non ha una tradizione da trasmettere ai figli, che cedono agli impulsi fortuiti dell'ambiente sociale.
* Degenera nell'individualismo e nel bisogno di novità.
La **famiglia-ceppo**:
* Prevede che un figlio si sposi e rimanga presso i genitori, mentre gli altri figli sono liberi di rimanere o allontanarsi.
* Permette al padre di scegliere l'erede, e quindi chi dirigerà la famiglia.
* Bilancia la ricchezza degli individui con il potere dei governanti.
**Taudière** scrive un saggio nel 1913.
Critica le "**leggi francesi contro la famiglia**", che includono:
* Il divorzio.
* L'assimilazione delle diverse categorie di figli.
* La limitazione dei poteri paterni e maritali.
**Pétain**:
* Sostiene che la Francia si è sconfitta da sola, con i "morbi" moderni dell'individualismo, femminismo, e crisi dei valori familiari tradizionali.
* Sostiene la necessità di ritornare alle **comunità naturali** e della **famiglia patriarcale come istituzione** alla base dello Stato.
La **riforma del lavoro** nella **Repubblica di Vichy** è fondata su **principi natalisti**:
* La madre al focolare domestico.
* La remunerazione del padre dipende dal numero di figli.
* I padri di famiglia devono essere preferiti per gli impieghi pubblici e privati.
Il **Codice della Famiglia** era stato promulgato nel 1939 dalla III Repubblica, ed era un esempio della **legislazione natalista** del tempo.
* Il primo titolo (**aiuti alla famiglia**) prevede premi per le nascite, allocazioni familiari, e sostegni per le famiglie rurali.
* Il secondo titolo (**protezione della famiglia**) protegge ed incoraggia la maternità, crea "case materne", protegge l'infanzia e sanzionano i reati contro i buoni costumi.
* Il terzo titolo (**disposizioni fiscali**) introduce benefici fiscali in campo successorio e per le famiglie agricole.
Nel 1940 era stato creato uno specifico "Ministero della Famiglia".
Nel 1941 viene pubblicato un rapporto sui risultati che il ministero aveva ottenuto in un anno.
Si sottolinea l'importanza del **ritorno all'ordine e tradizione**, il **lavoro nei campi**.
**Beauchamp** sostiene l'importanza della **padre di famiglia**:
* I **figli** imparano la **gerarchia** nel rapporto domestico.
* La **scuola** deve **confermare** questo insegnamento, ed i padri hanno diritto di chiedere il licenziamento di educatori che insegnano diversamente.
* In politica, i padri con più figli possono esercitare **voti plurimi**.
**Rouast** insegna diritto civile durante l'occupazione tedesca.
La sua **critica al codice**:
* **Non** è la debolezza delle **relazioni familiari**, ma la **mancanza di norme sulla famiglia-istituzione**.
* **L'approccio contrattualistico** non poteva assicurare il ruolo della famiglia e la sua durata nel tempo.
* La **disciplina delle successioni** divideva la famiglia con la morte del primo dei genitori.
* Le **parti deboli** (moglie e figli) dovevano essere **tutelate**, dando al **padre** una mera **autorità di protezione**.
**Rouast giudica con favore**:
* I **movimenti politici e sociali** favorevoli al neofamilismo.
* La creazione delle **associazioni di famiglia**, che davano **rilevanza giuridica all'interesse di famiglia**, ed erano rappresentate dai padri.
Anche se riteneva che il **diritto di famiglia facesse parte del diritto privato, gli dava rilevanza pubblica**.
In materia di **matrimonio del figlio**:
* **L'arbitrio del padre** è giustificato dalla **protezione** del **figlio inesperto** da una passione irrazionale, e degli **interessi della famiglia** riguardo una cattiva alleanza.
* Critica il codice perché le **opposizioni dei genitori non possono più** essere usate come **misura dilatoria**.
In materia di **potestà maritale**, aveva partecipato personalmente alla riforma:
* La **potestà maritale viene abrogata** e **sostituita dalla funzione di capo di famiglia**, che durerà fino al 1970.
* Il padre conserva **forti poteri**, ma devono essere esercitati **nell'interesse della famiglia**, e **non discrezionalmente**.
* La **moglie** subentra al marito in caso di **morte o altre situazioni eccezionali**, ma altrimenti aveva **poteri limitati**.
* La **residenza separata** poteva essere richiesta solo in caso di pericoli fisici o morali.
**L'interesse oggettivo della famiglia** è il fondamento della disciplina dei **diritti paterni** secondo Rouast.
I **doveri essenziali** includono il **mantenimento e l'educazione** (fondato **sull'obbligo scolastico**), e per il loro adempimento sono previste le **prerogative accessorie** (diritto di consenso al matrimonio, amministrazione legale dei beni del figlio, emancipazione del figlio, designazione di un tutore testamentario).
Le **prerogative essenziali** includono:
* La **garde**, ossia la **educazione, cura materiale e sorveglianza** delle relazioni e della corrispondenza del figlio, era **sanzionata civilmente e penalmente**, e poteva terminare per **abbandono del figlio alla pubblica assistenza** o per **delega a terzi**.
* Il **diritto di correzione**, che includeva anche il **potere di internamento**, sottoposto a **vaglio giudiziario generalizzato**.
* **L'usufrutto legale** sui redditi del figlio.
I **maltrattamenti** secondo Rouast:
* Oltre ai **maltrattamenti per commissione**, sono previsti gli **abusi per omissione**.
* I **controlli pubblici** valutano i maltrattamenti, e possono ordinare la **decadenza totale o parziale** dalla potestà.
La **supplenza all'autorità paterna**:
* I genitori e le ragazze madri potevano **abbandonare i figli alla pubblica assistenza**, in maniera **volontaria e non definitiva**.
* Sulla base delle idee nataliste e ruraliste, i figli venivano collocati presso una famiglia rurale, per garantire la sua salute ed evitare lo spopolamento delle campagne.
* Completano la **scuola dell'obbligo**, un **apprendistato per un mestiere legato all'agricoltura**, e diventavano **domestici a pagamento** presso la famiglia, fino alla maggiore età o loro adozione.
* Gli **assistenti sociali** sorvegliavano ogni passo della procedura.
**Nonostante le tendenze arcaizzanti**, non ci fu mai una sovversione della famiglia.
Lo **Stato si era definitivamente affermato come supplente** delle carenze dei genitori.
## 6.6. Padri comunisti, da Marx all'Unione Sovietica (154)
La **rivoluzione comunista** in Russia si era proposta di **sovvertire l'istituzione familiare** sulla base del **modello marxista**.
Il **socialismo prima di Marx** criticava, ma non voleva demolire la famiglia.
Il **pensiero di Marx** porta alla concezione della **famiglia come incidente storico**, e **sovrastruttura per la formazione e controllo della proprietà**.
Il **Manifesto del partito comunista**:
* Prevedeva la **promiscuità sessuale** e la necessità di una **educazione sociale**.
* Sosteneva che il modello di famiglia borghese sarebbe caduto naturalmente con la caduta del capitale.
La **scuola di Francoforte** considera negativamente la famiglia come un **luogo di autoritarismo** e di **trasmissione dei valori tradizionali**.
Il pensiero marxista **non vuole superare la famiglia in quanto tale**, ma **solo la famiglia borghese**.
Il **diritto imperiale zarista** prevedeva:
* Una **famiglia patriaracale**, con **potestà perpetua**.
* Un **diritto correzionale ampio**, le cui **uniche limitazioni** erano quelle imposte dalle comunità di villaggio.
* La **proprietà** dei beni alla **comunità familiare allargata**.
* Un sistema con **poche norme** e regolato dalla **prassi giudiziaria**.
Nei **primi anni della Rivoluzione** si tende verso un **forte radicalismo**.
**Subito dopo** si arriva ad uno **statualismo estremamente pervasivo**, con grandi **poteri discrezionali per la magistratura**, e dove i **genitori** erano visti come **funzionari statali**.
Lo **scorporo del diritto di famiglia dal diritto privato**:
* Sarà mantenuto anche dopo la seconda guerra mondiale, e nei paesi d'area sovietica.
* Aveva il **valore ideologico** di superamento della famiglia borghese.
* Era anche una conseguenza della **giuspubblicizzazione** di tutto il diritto privato.
Il **codice sovietico della famiglia**:
* **Esclude** il termine **patria potestà**.
* Introduce un **controllo giudiziario pervasivo** nelle relazioni domestiche.
* Prevede la **bititolarità dei poteri genitoriali**, ed in **caso di dissenso**, la questione viene risolta dagli organi statali.
**Con Stalin**, negli anni '30 e '40 si **rivaluta la famiglia** come **luogo di produzione del buon cittadino**.
Si dà un **ruolo centrale alle madri**, sempre sotto il controllo statale.
Rimane una certa **diffidenza verso il patriarcato** e la sua **incompatibilità con la società sovietica**.
Secondo **Matteucci**:
* I genitori hanno solo in ruolo di curare i figli, e lo Stato può **avocare** i diritti dei genitori con un provvedimento amministrativo.
* Lo **Stato ha dovuto reintrodurre il vincolo matrimoniale per contrastare gli aborti ed i figli abbandonati**.
* Il **rapporto fra genitori e figli non viene riformato**, per evitare che si creino di nuovo gerarchie.
I **figli devono ubbidire allo Stato, prima che alla famiglia**.
Ad es., **Pavlik Morozov** denuncia il padre perché voleva prendere parte a dei moti, viene ucciso dai genitori, e viene nominato "eroe dell'Unione Sovietica".
Nell'Unione Sovietica e negli altri paesi socialisti, il **puerocentrismo** si sono affermati per **motivi principalmente politici**.
Il **valore del figlio** deriva dal fatto che nel futuro dovrà **costruire il sistema socialista**.
## 6.7. Zadruga slava e kanun albanese (157)
Nel processo novecentesco di omologazione delle relazioni domestiche le peculiarità locali vengono eliminate.
Tuttavia, nell'Europa che tende al puerocentrismo sopravvivono dei **microcosmi patriarcali**.
La **zadruga slava** viene considerata da **Engels** come lo stadio intermedio fra la famiglia matriarcale fondata sul matrimonio di gruppo e quella monogamica moderna.
È un **istituto consuetudinario**, che viene **regolato normativamente** nell'ottocento.
È tipica degli **slavi del sud**, ed è stata conservata durante la dominazione turca.
Rappresentava lo **spirito nazionale croato, serbo e montenegrino**.
Dopo che la **Serbia** ottiene l'indipendenza e si dà un codice civile, **disciplina la zadruga** per prima.
La zadruga sarà anche prevista dal codice montenegrino del 1855 e dalle leggi croate del 1889 e 1902.
La **zadruga** era un modello di **famiglia complessa**, che poteva comprendere anche più di cento componenti.
Anche a **metà ottocento non era ancora obsoleta**, dato il contesto sociale marcatamente arcaico in cui si trovava.
Inizia a **decadere** solo nei **decenni successivi**, sotto l'influenza dei nuovi codici civili liberali.
Il **codice serbo** richiedeva la **parentela, comunione dei beni, vita e attività lavorativa in comune**.
I **maschi maggiorenni e capaci** hanno **uguaglianza di diritti e doveri**.
Le **donne** sono in condizione di **inferiorità**, specialmente dal punto di vista dei **diritti successori**.
I **codici ottocenteschi** e la **zadruga croata** prevedevano condizioni più favorevoli per la donna.
Il **governo** era esercitato da un **Consiglio**.
È competente per **atti di particolare rilievo** ed è composto dai **membri maschi e maggiorenni**.
Il **capo** (staréchitza):
* Viene eletto dal Consiglio stesso, ed era **solitamente, ma non necessariamente, il maschio più anziano**.
* Veniva **aiutato di solito dalla moglie** (staréchina), a cui **delegava poteri** riguardanti **l'organizzazione interna** della zadruga e i **compiti delle donne**.
* **Rappresenta** la zadruga all'esterno.
* È il **tutore di tutti i minorenni ed incapaci** all'interno della zadruga.
Con il **regime comunista**:
* Si **parificano i diritti e doveri dei genitori** verso i figli.
* Si prevede che **l'esercizio dei poteri** sia diretto alla **formazione di cittadini utili e devoti**, e la **consolidazione della famiglia**.
**L'organizzazione familiare albanese** era fondata sulla coabitazione di più coppie imparentate.
Il **capo di casa** è il maschio più anziano.
**Poteva essere sostituto per gravi manchevolezze dal consiglio di famiglia, composto dai maschi maggiorenni**.
Può erogare **pene corporali**, e gli è dovuta **obbedienza assoluta**.
Il **kanun** è una **raccolta di consuetudini locali** in Albania, che dimostrano un **assetto sociale arcaico**.
La **padrona di casa** è **priva di diritti patrimoniali**, compresi i diritti ereditari.
Ha una **potestà subalterna**, limitata alla **direzione e vigilanza** di cosa si fa in casa, e può **comandare le donne di casa**.
Gli **altri membri** della famiglia hanno **un'autonomia limitata**:
* Possono **gestire liberamente** il patrimonio derivante dalle loro **armi**.
* Possono **destituire il padrone o la padrona di casa** se non lavorano per la famiglia, o sottraggono beni.
* **Non hanno autonomia patrimoniale**.
Il **padre**:
* Può **legare e bastonare moglie e figli**, e può **uccidere i figli**.
* È titolare dei guadagni del figlio, e può allontanarlo di casa.
* **Deve adoperarsi per il bene dei figli**, **non può preferire un figlio**, e **deve lasciare l'eredità indivisa o divisa in parti uguali**.
* Deve dare il **consenso** affinché i **figli** possano **lavorare o spostarsi**.
Il **figlio**:
* Se **uccide il padre** viene ucciso o esiliato dai parenti.
* Può **allontanarsi da casa**, ma **perde il diritto all'eredità**.
* Il **figlio primogenito eredita il governo della casa**.
* Diventa **maggiorenne** quando può **portare le armi**.
* Se è **adulto e capo di casa, è libero nella scelta matrimoniale**.
* Le **figlie** devono **sempre rimettersi** alla decisione del **padre**, congiunto maschio prossimo, madre, o sorelle.
* Può essere **promesso in matrimonio anche se nascituro**.
## 6.8. Responsabilità genitoriale nel tardo Novecento (161)
La **seconda guerra mondiale** accelera l'abbandono dei tradizionali elementi del patriarcato.
Si afferma:
* Il **puerocentrismo**.
* **L'uguaglianza dei genitori**, la **scomparsa del "capo famiglia" e della divisione dei ruoli**.
* **L'intervento giudiziale nell'interesse del minore** e la **partecipazione del figlio alle decisioni che lo interessano**.
* **L'annichilimento dello ius corrigendi**.
* La **deistituzionalizzazione, privatizzazione, individualizzazione del matrimonio e relazioni familiari**.
La **scelta del cognome** è un elemento emblematico dei cambiamenti sociali.
Nel dopoguerra, **l'affidamento dei figli in caso di separazione**:
* **Non** veniva più **automaticamente** fatto a favore del padre, solo perché titolare della patria potestà.
* Piuttosto, si valutava **solo l'interesse del figlio** nella scelta del genitore affidatario.
La **decadenza dalla patria potestà**:
* **Non** è più considerata una **sanzione civile accessoria** per la condotta del genitore.
* Piuttosto, serve a **tutelare l'interesse del figlio**.
Negli **anni settanta** c'è il **crollo definitivo** della **patria potestà ottocentesca**.
Nella **riforma del diritto di famiglia italiano del 1975**:
* La **potestà diventa pienamente bititolare** ed **orientata all'interesse del figlio**.
* Viene abrogato il **dovere di onorare** i genitori, ed è sostituito dal **rispetto**, che implicava un **rapporto paritario**.
* **L'educazione** dei figli **non** deve più tenere conto dei **principi della morale**, ma solo delle **capacità, inclinazioni e aspirazioni** dei **figli**.
Nella nuova prospettiva puerocentrica:
* I **genitori non** sono più titolari di un **diritto**, ma di un **dovere**.
* I **confini dei poteri dei genitori** sono dati dal **principi fondamentali dell'ordinamento**, che includono anche la **Costituzione**.
* Lo **Stato** è il **garante dei diritti del minorenne**, considerato "parte debole".
Il **potere correzionale** è limitato alla **educazione**, e **non può consistere in forme di violenza**. |
% function R = Xmatrixr3(wx,wy,wz)
%
% Toolbox Xvis: 3D rotation matrix.
%
% It returns the 3D rotation matrix given by a rotation arround z, y and x
% axes where the rotation angles are wz, wy, and wx respectively. The
% angles are given in radians.
%
% R = Xmatrixr3(wx,wy,wz) is equal to Rx*Ry*Rz where
%
% Rz = [ cos(wz) sin(wz) 0
% -sin(wz) cos(wz) 0
% 0 0 1];
%
% Ry = [ cos(wy) 0 -sin(wy)
% 0 1 0
% sin(wy) 0 cos(wy)];
%
% Rx = [ 1 0 0
% 0 cos(wx) sin(wx)
% 0 -sin(wx) cos(wx)];
%
% Example:
%
% R = Xmatrixr3(pi/2,-pi,0); % Rotation matrix for theta = pi/3
% X = 1; Y = 0; Z = 1; % 3D point given in original coordinate system
% M = [X Y Z]'; % 3D point as vector
% Mt = R*M; % Transformed 2D point as vector
% Xt = Mt(1), Yt = Mt(2), Zt = Mt(3) % 2D point given in new coordinate system
%
% See also Xmatrixr2, Xmatrixp.
function R = Xmatrixr3(wx,wy,wz)
R = [
cos(wy)*cos(wz) cos(wy)*sin(wz) -sin(wy)
sin(wx)*sin(wy)*cos(wz)-cos(wx)*sin(wz) sin(wx)*sin(wy)*sin(wz)+cos(wx)*cos(wz) sin(wx)*cos(wy)
cos(wx)*sin(wy)*cos(wz)+sin(wx)*sin(wz) cos(wx)*sin(wy)*sin(wz)-sin(wx)*cos(wz) cos(wx)*cos(wy)]; |
// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
crate::resolved_driver::ResolvedDriver,
bind::compiler::Symbol,
bind::ddk_bind_constants::{BIND_AUTOBIND, BIND_PROTOCOL},
bind::interpreter::decode_bind_rules::DecodedCompositeBindRules,
bind::interpreter::match_bind::{DeviceProperties, PropertyKey},
fidl_fuchsia_driver_framework as fdf,
fuchsia_zircon::{zx_status_t, Status},
};
const BIND_PROTOCOL_KEY: PropertyKey = PropertyKey::NumberKey(BIND_PROTOCOL as u64);
const BIND_AUTOBIND_KEY: PropertyKey = PropertyKey::NumberKey(BIND_AUTOBIND as u64);
pub fn node_to_device_property(
node_properties: &Vec<fdf::NodeProperty>,
) -> Result<DeviceProperties, zx_status_t> {
let mut device_properties = DeviceProperties::new();
for property in node_properties {
let key = match &property.key {
fdf::NodePropertyKey::IntValue(i) => PropertyKey::NumberKey(i.clone().into()),
fdf::NodePropertyKey::StringValue(s) => PropertyKey::StringKey(s.clone()),
};
let value = match &property.value {
fdf::NodePropertyValue::IntValue(i) => Symbol::NumberValue(i.clone().into()),
fdf::NodePropertyValue::StringValue(s) => Symbol::StringValue(s.clone()),
fdf::NodePropertyValue::EnumValue(s) => Symbol::EnumValue(s.clone()),
fdf::NodePropertyValue::BoolValue(b) => Symbol::BoolValue(b.clone()),
_ => {
return Err(Status::INVALID_ARGS.into_raw());
}
};
// TODO(https://fxbug.dev/42175777): Platform bus devices may contain two different BIND_PROTOCOL values.
// The duplicate key needs to be fixed since this is incorrect and is working by luck.
if key != BIND_PROTOCOL_KEY {
if device_properties.contains_key(&key) && device_properties.get(&key) != Some(&value) {
tracing::error!(
"Node property key {:?} contains multiple values: {:?} and {:?}",
key,
device_properties.get(&key),
value
);
return Err(Status::INVALID_ARGS.into_raw());
}
}
device_properties.insert(key, value);
}
// Due to a bug, if device properties already contain a "fuchsia.BIND_PROTOCOL" string key
// and BIND_PROTOCOL = 28, we should remove the latter.
// TODO(https://fxbug.dev/42175777): Fix the duplicate BIND_PROTOCOL values and remove this hack.
if device_properties.contains_key(&PropertyKey::StringKey("fuchsia.BIND_PROTOCOL".to_string()))
&& device_properties.get(&BIND_PROTOCOL_KEY) == Some(&Symbol::NumberValue(28))
{
device_properties.remove(&BIND_PROTOCOL_KEY);
}
Ok(device_properties)
}
pub fn node_to_device_property_no_autobind(
node_properties: &Vec<fdf::NodeProperty>,
) -> Result<DeviceProperties, zx_status_t> {
let mut properties = node_to_device_property(node_properties)?;
if properties.contains_key(&BIND_AUTOBIND_KEY) {
properties.remove(&BIND_AUTOBIND_KEY);
}
properties.insert(BIND_AUTOBIND_KEY, Symbol::NumberValue(0));
Ok(properties)
}
pub fn get_composite_rules_from_composite_driver<'a>(
composite_driver: &'a ResolvedDriver,
) -> Result<&'a DecodedCompositeBindRules, i32> {
match &composite_driver.bind_rules {
bind::interpreter::decode_bind_rules::DecodedRules::Normal(_) => {
tracing::error!("Cannot extract composite bind rules from a non-composite driver.");
Err(Status::INTERNAL.into_raw())
}
bind::interpreter::decode_bind_rules::DecodedRules::Composite(rules) => Ok(rules),
}
}
#[cfg(test)]
mod tests {
use super::*;
use fuchsia_async as fasync;
#[fasync::run_singlethreaded(test)]
async fn test_duplicate_properties() {
let node_properties = vec![
fdf::NodeProperty {
key: fdf::NodePropertyKey::IntValue(10),
value: fdf::NodePropertyValue::IntValue(200),
},
fdf::NodeProperty {
key: fdf::NodePropertyKey::IntValue(10),
value: fdf::NodePropertyValue::IntValue(200),
},
];
let mut expected_properties = DeviceProperties::new();
expected_properties.insert(PropertyKey::NumberKey(10), Symbol::NumberValue(200));
let result = node_to_device_property(&node_properties).unwrap();
assert_eq!(expected_properties, result);
}
#[fasync::run_singlethreaded(test)]
async fn test_property_collision() {
let node_properties = vec![
fdf::NodeProperty {
key: fdf::NodePropertyKey::IntValue(10),
value: fdf::NodePropertyValue::IntValue(200),
},
fdf::NodeProperty {
key: fdf::NodePropertyKey::IntValue(10),
value: fdf::NodePropertyValue::IntValue(10),
},
];
assert_eq!(Err(Status::INVALID_ARGS.into_raw()), node_to_device_property(&node_properties));
}
// TODO(https://fxbug.dev/42175777): Remove this case once the issue with multiple BIND_PROTOCOL properties
// is resolved.
#[fasync::run_singlethreaded(test)]
async fn test_multiple_bind_protocol() {
let node_properties = vec![
fdf::NodeProperty {
key: fdf::NodePropertyKey::IntValue(BIND_PROTOCOL.into()),
value: fdf::NodePropertyValue::IntValue(200),
},
fdf::NodeProperty {
key: fdf::NodePropertyKey::IntValue(BIND_PROTOCOL.into()),
value: fdf::NodePropertyValue::IntValue(10),
},
];
let mut expected_properties = DeviceProperties::new();
expected_properties.insert(BIND_PROTOCOL_KEY, Symbol::NumberValue(10));
assert_eq!(Ok(expected_properties), node_to_device_property(&node_properties));
}
// TODO(https://fxbug.dev/42175777): Remove this case once the issue with multiple BIND_PROTOCOL properties
// is resolved.
#[fasync::run_singlethreaded(test)]
async fn test_multiple_bind_protocol_w_deprecated_str_key() {
let node_properties = vec![
fdf::NodeProperty {
key: fdf::NodePropertyKey::IntValue(BIND_PROTOCOL.into()),
value: fdf::NodePropertyValue::IntValue(28),
},
fdf::NodeProperty {
key: fdf::NodePropertyKey::StringValue("fuchsia.BIND_PROTOCOL".to_string()),
value: fdf::NodePropertyValue::IntValue(10),
},
];
let mut expected_properties = DeviceProperties::new();
expected_properties.insert(
PropertyKey::StringKey("fuchsia.BIND_PROTOCOL".to_string()),
Symbol::NumberValue(10),
);
assert_eq!(Ok(expected_properties), node_to_device_property(&node_properties));
}
#[fasync::run_singlethreaded(test)]
async fn test_no_autobind() {
let node_properties = vec![fdf::NodeProperty {
key: fdf::NodePropertyKey::IntValue(BIND_PROTOCOL.into()),
value: fdf::NodePropertyValue::IntValue(200),
}];
let mut expected_properties = DeviceProperties::new();
expected_properties.insert(BIND_PROTOCOL_KEY, Symbol::NumberValue(200));
expected_properties.insert(BIND_AUTOBIND_KEY, Symbol::NumberValue(0));
assert_eq!(Ok(expected_properties), node_to_device_property_no_autobind(&node_properties));
}
#[fasync::run_singlethreaded(test)]
async fn test_no_autobind_override() {
let node_properties = vec![fdf::NodeProperty {
key: fdf::NodePropertyKey::IntValue(BIND_AUTOBIND.into()),
value: fdf::NodePropertyValue::IntValue(1),
}];
let mut expected_properties = DeviceProperties::new();
expected_properties.insert(BIND_AUTOBIND_KEY, Symbol::NumberValue(0));
assert_eq!(Ok(expected_properties), node_to_device_property_no_autobind(&node_properties));
}
} |
<!DOCTYPE html>
<html lang="en" xmlns:th="https://thymeleaf.org"
xmlns:layout="http://www.nz.ultraq.nz/thymeleaf/layout"
layout:decorate="~{layout}">
<head>
<title>Hotel List</title>
<style>
.star {
color: gold;
font-size: 24px;
}
body {
font-family: Arial, sans-serif;
margin: 20px;
}
.review-container {
max-width: 800px;
margin: auto;
}
.review {
border-radius: 8px;
margin-bottom: 20px;
padding: 15px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); /* Optional shadow for better separation */
}
.star {
color: gold;
font-size: 20px;
}
.review-text {
margin-top: 10px;
}
.user {
margin-left: auto;
}
</style>
</head>
<body class="d-flex flex-column h-100">
<main class="flex-shrink-0">
<!-- Page Content-->
<section layout:fragment="body" class="py-5">
<div class="review-container">
<h1>My Reviews</h1>
<div th:each="review : ${reviews}">
<div class="review">
<h2 th:text="${review.reservation.hotel.name}"></h2>
<p th:text="${review.review_text}"></p>
<p>
<span th:switch="${review.stars}">
<span th:case="1" class="star">★</span>
<span th:case="2" class="star">★★</span>
<span th:case="3" class="star">★★★</span>
<span th:case="4" class="star">★★★★</span>
<span th:case="5" class="star">★★★★★</span>
<span th:case="*" th:text="${'Invalid stars: ' + review.stars}"></span>
</span>
</p>
</div>
</div>
</div>
</section>
</main>
</body>
</html> |
//logger.h
/*******************************************************************************
* Includes
******************************************************************************/
#include <iostream>
#include <fstream>
/*******************************************************************************
* Class Definitions
******************************************************************************/
/**
* @brief Logger is used to track information about the simulation and store it in a csv
*/
class Logger
{
public:
/**
* @brief Instance instantiates a new logger to be used without it having to be defined elsewhere
*
* @return an instance of the logger
*/
static Logger& Instance()
{
static Logger instance;
return instance;
}
/**
* @brief Log writes the data into the csv file
*
* @return void (data saved to csv)
*/
void Log(const double distance)
{
std::ofstream dataFile;
dataFile.open ("build/dataLog.csv", std::ofstream::app);
dataFile << "Total Distance:,";
dataFile << distance << ",\n";
dataFile.close();
}
private:
/**
* @brief Consturtor of the Logger
*
* @return none
*/
Logger() {}
}; |
package summary;
public class Summary {
//面试笔记
//-------------------------------------------------------------------基础
// Integer a = new Integer(2);
// Integer b = new Integer(2);
// System.out.println(a==b);// false
// 只要是new 都是两个对象 都是false
// 如果没有new 在缓存范围里的true 在范围外是false
//包装类的缓存:-128到127
//只要有一个new就是两个对象
//(只有在都没使用new并且数值在缓存范围内才是一个对象)
//方法也可以加final 加了就不能修改了
// static 静态方法可以访问静态变量 静态方法不能访问非静态变量和调用非静态方法
// 实例方法可以调用静态方法 静态方法不能调用实例方法
// 类与类之间是单继承 接口与接口之间是多继承
// stringbuffer(安全) 和 stringbuilder(不安全)
// arrayList怎么扩容
// Hashcode的返回值(int)
//vector和map的区别
// vector扩容的原理
// 接口和抽象类 接口里都是方法申明 不能有方法实现 抽象里类是有实现 接口只能使用public 抽象类里除了private都行
// springbean是不是线程安全的 是不是线程安全和作用域没关系,查看bean这个对象是不是线程安全还得看本身是不是有状态 有则不安全
//hashmap怎么扩容 1.7的头插法是扩容的时候出现的死循环 所以要提到扩容 这块还得根据代码再看看
//string为什么不是基础数据类型(因为String对象是System.Char对象的有序集合,基本类型是简单的字符或者数字,引用类型是复杂的数据结构)
//-------------------------------------------------------------------JVM
//类加载器有哪些
//年轻代和老年代的比例(1:2)
// 可达性分析 根节点是哪些
//New一个对象 生命周期
//Jvm常用参数
// 引用计数法的缺陷
// 为什么要常量池
//---------------------------------------------------------------------springboot
// 循环依赖
// @Transaction原理
//Bean的生命周期
//
//-----------------------------------------------------------------------设计模式
// 单例模式 一次创建多次使用
// 什么时候用单例
//spring里面的设计模式
// --------------------------------------------------------------------多线程
//reentrantlock使用
//volatile使用
//线程池销毁线程和使用
//拒绝策略
//线程池的状态
//为什么不用Executors创建线程池
//多线程和异步的区别
// 线程池 的工作流程
// Sleep wait
// Thread的sleep会进入什么状态
//如何查看线程死锁
// Threadlocal里的entry
//threadlocal内存泄漏
// 线程之间如何通信
//线程是进程的实体
// 线程依赖进程哪些资源:线程共享进程的堆和数据区(进程是CPU调度的基本单位)
//--------------------------------------------------------------------mysql+数据库
//事务隔离级别怎么解决事务的问题
//怎么加行锁
//了解一下为什么es倒排索引那么快
//怎么实现可重复读
// 跳跃表
// mybatis的分页
// 普通索引
//可为null的字段适合加索引吗 (is null走索引 is not null 不走索引)
// 数据变化频繁怎么加索引(频繁修改对字段不建议🏠索引,如果数据量大可以考虑分库分表)
// B+树怎么平衡的
// Redis指令
// 慢sql的优化思路
// char和varchar
//mysql死锁
// aof重写的过程
//聚簇
//布隆过滤器
// 分布式ID
//rdb和aof怎么配合使用
// 怎么解决幻读 mvcc+间隙锁
//redis分布式锁
//left join和right join的区别 (left是左边整体 right是右边整体)
// 间隙锁就是范围查询的时候加上排他锁
//redis集群 mysql主从复制
//延时双删要统计数据库写的时间
// 最左前缀 a b c d 四个字段 只用了 a c是可以的 c a 也是可以的 b c就不行了
// a是要在的 并且a是不能范围查的 范围查了 后面都没效了
//------------------------------------------------------------------------网络
// session怎么失效的(设置最大存活时间)
//whois信息
//什么是报文:网络中传输的数据单元
// udp报文结构:原端口,目的端口,校验和,UDP长度
//单点登陆(直接复制session、redis+cookie(用户信息存redis key放cookie里 后端解析cookie去redis里查询)、token)
//nginx怎么负载均衡
// 分布式session、
// Tcp限流 滑动窗口
// 拥塞控制
// ping的过程
// 什么是syn攻击
// 为什么是2msl
//---------------------------------------------------------------------springcloud
// fign的原理
//
//------------------------------------------------------------------------消息队列
//topic和group
//消息队列
//————————————————————————————————————————————————————————————————————————————
//—————————————————————————————————————————————————————————————————————————————
//redis批量处理 批量读写和删除
//AOP、AQS、KMP
//为什么用Reactor、Webflux
//二叉树的题目有时间整理一下
//堆排序
//红黑树
// 拦截器和过滤器谁先执行、过滤器和拦截器的区别、
// 拥塞控制算法
//第三次握手没收到怎么办(重发?还有呢)
// Tcp客户端没有找到服务端 他的状态机是什么
// Tcp可靠性保障
//myisam的索引结构 b+
// 最左前缀法则索引树是什么样
// Mysql的日志 redo.log undo.log
//分库分表
// mysql里的count准确吗
// 线程池里的线程工厂怎么使用
//线程池里多余的线程是怎么回收的: 线程池会整理线程设置活跃的线程数
// Countdownlatch任务失败怎么办
// 阻塞队列
// lock为什么是乐观锁:因为他是volatile+cas实现的
// syn为什么是非公平锁
//自动装配怎么实现的 :@EnableAutoConfiguration注解会读取spring.factories文件 自动加载里面配置类的对象到spring组件里
// springboot加载顺序
// spring事务 @Transaction AOP
// @Todo 后期有时间把编译原理看了(考研也需要)
// @Todo 每天都要保证力扣 后期这个git也要维护
// @Todo 没事时候去B站上找一些八股文面试视频 看看这些视频就能发现还是有很多技术细节不了解
//链表反转、回文、公共、相加、
// dfs、bfs
// es查询优化
//再多了解根节点、镜像节点 路由路径
//计算机网络
// es加分词
//NIO使用
//堆排
//mysql主从复制
//单调栈 dfs 动态规划
//什么时候用fullGC
// mysql里join的效率
// chmod
// 第三次握手服务器没收到会怎样
// 半连接队列 全连接队列
// 哪些握手能带数据:只有第三次
// 数字证书
// 粘包 :字节流没有分隔符 不知道每个字节流的大小
//具体说一下怎么保证tcp传输安全
//来未来
//模版模式
// treemap (是树的中序遍历) 是根据key元素的comparator to实现的(默认是根据key来排序的,那就可以把count放在key的位置就行,但是count可能重复 作为key的话数据会丢)
// 分布式会用哪些 redis分布式 springcloud
// 分布式原理
// mybatis里的扩展组件
// mysql线程 怎么执行的
// redis缓存击穿
//数据库怎么做分布式锁
// ioc的bean加载过程
// ioc和aop
//threadlocal使用场景
// G1
//今晚看下CMS
// string args[]
// 力扣上面的线程题
// 最长公共题
//又被问到网络IO了
// FileInputStream FileOutputStream FileReader FileWriter
/**
* Exception有两种
* 运行时异常和编译时异常
* 编译时异常要显示的抛出或者try-catch(类似读取文件时会提醒文件可能不存在)
* 运行时异常就是运行了代码才知道的异常
*
* 编译异常:filenotfoundException classnotfoundexception
* 运行时异常:nullpointerexception classcastexception 越界
*
*
* 反射获取到类的信息后怎么创建对象
* 直接反射来的类的对象newInstance
* 或者先获取到构造器再newInstance
*
*/
//接口幂等性
/**
* 唯一索引
* 加悲观锁、乐观锁
* 加分布式锁
* token机制:请求前先申请一个token(唯一的) 然后token作为key 用户信息作为value存储到redis里
* 发请求时候带着token 去redis里查找 请求结束 删除token 重复请求的化 redis的key已经被
* 删除了 就直接返回重复请求的错误信息
*
*/
//双亲委派:类加载的过程中 将加载请求委派给父类执行 避免类被重复加载 防止核心类被篡改 扩展-》引用--》启动
// 怎么打破双亲委派呢 为什么需要打破
//spring动态代理 不是AOP
//消息被重复消费:记录消息的记录、唯一性约束、
//websocket实现弹幕 写的有问题 代码看不懂不会改 先把netty看了
//有时间看下那个测试开发工具实现的逻辑
//为什么left join 慢
// feign的原理
//ribbon的工作原理
//es查询快
//抓一次https:
//(为什么可以触发GC呢)
//租房APP
//ruoyi其他接口
//力扣上多线程的题
//lua
//什么时候使用netty 为什么使用netty NIO的弊端
//
//消息队列消息丢失
//b+树:子节点更多 树更矮 叶子节点也方便范围查询
//lua脚本保证加锁及超期的原子性
//状态模式
//布隆过滤器
//怎么熔断
//服务之间怎么调用:通过feign远程调用,ribbon的负载均衡决定使用哪个服务器,feign的原理是动态代理,检测到feign的注解,创建代理类,创建网络连接,发请求
//spring事务的原理:动态代理,监测事务注解,创建代理类 实现事务
//方法区:存放的常量、静态变量、类信息
//jdk1.8是G1
} |
import 'dart:ffi';
import 'dart:math';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart' as latLng;
import 'package:get/get.dart';
import 'package:geolocator/geolocator.dart';
import 'package:tugas/app/modules/report/controllers/report_controller.dart';
Future<Position?> getLastKnownPosition() async {
try {
Position? position = await Geolocator.getLastKnownPosition();
return position;
} catch (e) {
print('Error: $e');
return null;
}
}
class ReportView extends GetView<ReportController> {
ReportView({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Report'),
centerTitle: true,
),
body: FutureBuilder<Position?>(
future: getLastKnownPosition(),
builder: (context, positionSnapshot) {
if (positionSnapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
}
if (positionSnapshot.hasError) {
return Center(child: Text('Error: ${positionSnapshot.error}'));
}
Position? lastKnownPosition = positionSnapshot.data;
if (lastKnownPosition == null) {
return Center(child: Text('No last known position available.'));
}
return FutureBuilder<QuerySnapshot>(
future: FirebaseFirestore.instance.collection('masjid').get(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
}
if (!snapshot.hasData || snapshot.data!.docs.isEmpty) {
return Center(child: Text('No masjid found'));
}
Map<String, String> map = {};
List<Marker> markers = [];
List<CircleMarker> circles = [];
int i = 0;
snapshot.data!.docs.forEach((doc) {
int random = Random().nextInt(0xFFFFFF);
Color randomColor = Color(random);
double latitude = doc['latitude'];
double longitude = doc['longtitude'];
String namamasjid = doc['namamasjid'];
String lokasi = doc['lokasi'];
String key = '$latitude-$longitude';
i++;
Marker marker = Marker(
point: latLng.LatLng(latitude, longitude),
child: Icon(
Icons.circle,
size: 12,
color: randomColor.withOpacity(1.0),
),
);
circles.add(
CircleMarker(
point: latLng.LatLng(latitude, longitude),
color: randomColor.withOpacity(0.2),
borderStrokeWidth: 0.2,
borderColor: randomColor,
radius: i * 10.0, // Radius in meters
),
);
markers.add(
Marker(
point: latLng.LatLng(
lastKnownPosition.latitude,
lastKnownPosition.longitude,
),
child: const Icon(
Icons.gps_fixed, // Gunakan ikon GPS
size: 32,
color: Colors.red, // Warna biru
),
),
);
map[key] = '$namamasjid, $lokasi, $random';
markers.add(marker);
});
return ListView(
children: [
Container(
height: 300,
width: double.infinity,
child: FlutterMap(
options: MapOptions(
initialCenter:
// latLng.LatLng(-7.945581609707316, 112.56841751221398),
latLng.LatLng(
lastKnownPosition.latitude,
lastKnownPosition.longitude,
),
initialZoom: 10.9,
),
children: [
TileLayer(
urlTemplate:
'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
),
CircleLayer(circles: circles),
MarkerLayer(markers: markers),
],
),
),
// Displaying the table of masjid and lokasi
Padding(
padding: const EdgeInsets.all(16.0),
child: Table(
border: TableBorder.all(), // Adding borders to the table
columnWidths: {
0: FlexColumnWidth(1), // Adjust column width as needed
1: FlexColumnWidth(1),
2: FlexColumnWidth(1),
},
children: map.entries.map((entry) {
var values = entry.value.split(
','); // Splitting the value into "masjid", "lokasi", and "warna"
return TableRow(
children: [
Padding(
padding: const EdgeInsets.symmetric(
vertical: 4.0, horizontal: 8.0),
child: Text(
'${values[0]}',
style: TextStyle(
fontSize: 16,
color: Colors.black87,
),
),
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 4.0, horizontal: 8.0),
child: Text(
'${values[1]}',
style: TextStyle(
fontSize: 16,
color: Colors.black,
),
),
),
Padding(
padding:
const EdgeInsets.symmetric(vertical: 4.0),
child: Icon(
Icons.circle,
size: 12,
color: Color(int.parse(values[2]))
.withOpacity(1.0),
),
),
],
);
}).toList(),
),
),
],
);
},
);
},
),
);
}
} |
<script lang="ts" setup>
import { computed } from 'vue'
import { useFilterStore } from '../../store/Filter'
import { getItemIcon } from '../../utils/ImageLoader'
import { getItemNameById } from '../../utils/getItemNameById'
import { getWowheadItemLinkById } from '../../utils/getWowheadItemLinkById'
import { TIER_CONFIGS } from '@/common/TierConfig'
const filterStore = useFilterStore()
const boeCategories = computed(() => TIER_CONFIGS[filterStore.tier].boes)
const selectedBoes = computed<Array<number>>({
get() {
return [...filterStore.boes]
},
set(boes) {
filterStore.boes = new Set(boes)
},
})
const toggleAll = (idsToAdd: ReadonlyArray<number>) => {
const currentSelected = new Set(filterStore.boes)
for (const id of idsToAdd) {
currentSelected.add(id)
}
filterStore.boes = currentSelected
}
const toggleNone = (idsToRemove: ReadonlyArray<number>) => {
const currentSelected = new Set(filterStore.boes)
for (const id of idsToRemove) {
currentSelected.delete(id)
}
filterStore.boes = currentSelected
}
const isAllActive = (idsToCheck: ReadonlyArray<number>): boolean => {
for (const id of idsToCheck) {
if (!selectedBoes.value.includes(id)) {
return false
}
}
return true
}
const isNoneActive = (idsToCheck: ReadonlyArray<number>): boolean => {
for (const id of idsToCheck) {
if (selectedBoes.value.includes(id)) {
return false
}
}
return true
}
const region = computed(() => filterStore.region)
const getWowheadLink = (itemId: number) => {
if (region.value === null) {
return ''
}
return getWowheadItemLinkById(itemId, region.value)
}
const getItemName = (itemId: number) => {
if (region.value === null) {
return ''
}
return getItemNameById(itemId, region.value)
}
const tierName = computed(() => TIER_CONFIGS[filterStore.tier].name)
</script>
<template>
<q-banner
v-if="boeCategories.length === 0"
>
No BoEs available for {{ tierName }}
</q-banner>
<div
v-else
class="group"
>
<div
v-for="category of boeCategories"
:key="category.label"
>
<h2>
{{ category.label }}
<div
v-if="category.ids.length > 1"
class="toggles"
>
<a
:class="{ 'active': isNoneActive(category.ids) }"
@click="toggleNone(category.ids)"
>
none
</a>
<a
:class="{ 'active': isAllActive(category.ids) }"
@click="toggleAll(category.ids)"
>
all
</a>
</div>
</h2>
<q-list dense>
<a
v-for="id of category.ids"
:key="id"
:href="getWowheadLink(id)"
:data-wowhead="`item=${id}`"
class="boe"
rel="noopener"
target="_blank"
@click="(event) => event.stopPropagation()"
>
<q-item
v-ripple
clickable
tag="label"
:active="selectedBoes.includes(id)"
>
<q-checkbox
v-model="selectedBoes"
:val="id"
hidden
/>
<q-item-section avatar>
<q-avatar
rounded
size="40px"
>
<img
v-if="getItemIcon(id)"
:src="getItemIcon(id)"
:alt="getItemName(id)"
width="40"
height="40"
>
<q-icon
v-else
name="error_outline"
size="40px"
/>
</q-avatar>
</q-item-section>
<q-item-section>
{{ getItemName(id) }}
</q-item-section>
</q-item>
</a>
</q-list>
</div>
</div>
</template>
<style lang="scss" scoped>
.group{
display: flex;
flex-direction: column;
gap: $side-padding;
padding: $side-padding 0;
}
h2 {
display: flex;
align-items: center;
.toggles{
flex: 1;
a{
background: $dark;
border-radius: 15px;
color: white;
cursor: pointer;
display: block;
float: right;
margin-left: math.div($padding, 2);
padding: 5px 10px;
font-size: 0.75rem;
line-height: 20px;
text-transform: uppercase;
text-decoration: none;
&.active{
background: $primary;
}
&:hover{
background: $secondary;
}
}
}
}
.q-list{
a.boe{
display: block;
text-decoration: none;
.q-checkbox{
display: none;
}
.q-item{
&.q-item--active{
background: $primary
}
.q-item__section--avatar{
padding-right: $padding;
}
.q-item__label--caption{
color: #aaa;
line-height: $line-height !important;
margin-top: math.div($padding, 2);
}
}
}
}
</style> |
import React, { useState } from 'react'
import axios from "axios"
import "./searchFilm.css"
const SearchFilm = () => {
const [filmsId, setFilmsId] = useState("");
const [idChosen, setIdChosen] = useState(false);
const [film, setID] = useState({
id: "",
title: "",
original_title: "",
url: "",
description: "",
director: "",
producer: "",
release_date: "",
running_time: "",
});
const searchId = () => {
axios.get(`https://ghibliapi.herokuapp.com/films/?title=${filmsId}`).then(
(res) => {
setID({
id: res.data[0].id,
title: filmsId,
original_title: res.data[0].original_title,
url: res.data[0].image,
description: res.data[0].description,
director: res.data[0].director,
producer: res.data[0].producer,
release_date: res.data[0].release_date,
running_time: res.data[0].running_time,
});
console.log(res.data)
setIdChosen(true);
}
);
};
return (
<div className="App">
<div className="TitleSection">
<h1></h1>
<input
type="text"
onChange={(event) => {
setFilmsId(event.target.value);
}}
/>
<button onClick={searchId}>Busca Pelicula</button>
</div>
<div className="DisplaySection">
{!idChosen ? (
<h1> Escoge una Pelicula </h1>
) : (
<div className="Card">
<h1>{film.title}</h1>
<img className="image" src={film.url} alt={film.name} />
<h3>Titulo Original: #{film.original_title}</h3>
<h3 className="description">description: {film.description}</h3>
<h3>director: {film.director}</h3>
<h3>productor: {film.producer}</h3>
<h3>fecha de lanzamiento: {film.release_date}</h3>
<h3>tiempo de Duracion: {film.running_time}</h3>
</div>
)}
</div>
</div>
)
}
export default SearchFilm |
<?php
/**
* Shopware Premium Plugins
* Copyright (c) shopware AG
*
* According to our dual licensing model, this plugin can be used under
* a proprietary license as set forth in our Terms and Conditions,
* section 2.1.2.2 (Conditions of Usage).
*
* The text of our proprietary license additionally can be found at and
* in the LICENSE file you have received along with this plugin.
*
* This plugin is distributed in the hope that it will be useful,
* with LIMITED WARRANTY AND LIABILITY as set forth in our
* Terms and Conditions, sections 9 (Warranty) and 10 (Liability).
*
* "Shopware" is a registered trademark of shopware AG.
* The licensing of the plugin does not imply a trademark license.
* Therefore any rights, title and interest in our trademarks
* remain entirely with us.
*/
namespace SwagAdvancedCart;
use Shopware\Components\Plugin;
use Shopware\Components\Plugin\Context\ActivateContext;
use Shopware\Components\Plugin\Context\DeactivateContext;
use Shopware\Components\Plugin\Context\InstallContext;
use Shopware\Components\Plugin\Context\UninstallContext;
use Shopware\Components\Plugin\Context\UpdateContext;
use SwagAdvancedCart\Bootstrap\Setup;
use SwagAdvancedCart\Bootstrap\Uninstaller;
class SwagAdvancedCart extends Plugin
{
/**
* {@inheritdoc}
*/
public function install(InstallContext $context)
{
$setup = $this->getSetup();
$setup->install();
}
/**
* {@inheritdoc}
*/
public function update(UpdateContext $context)
{
$setup = $this->getSetup();
$setup->update($context->getCurrentVersion());
$context->scheduleClearCache(UpdateContext::CACHE_LIST_ALL);
}
/**
* {@inheritdoc}
*/
public function uninstall(UninstallContext $context)
{
if (!$context->keepUserData()) {
$uninstaller = $this->getUninstaller();
$uninstaller->uninstall();
}
$context->scheduleClearCache(UninstallContext::CACHE_LIST_ALL);
}
/**
* {@inheritdoc}
*/
public function activate(ActivateContext $context)
{
$context->scheduleClearCache(ActivateContext::CACHE_LIST_ALL);
}
/**
* {@inheritdoc}
*/
public function deactivate(DeactivateContext $context)
{
$context->scheduleClearCache(DeactivateContext::CACHE_LIST_ALL);
}
/**
* @return Uninstaller
*/
private function getUninstaller()
{
return new Uninstaller(
$this->container->get('dbal_connection'),
$this->container->get('shopware_attribute.crud_service'),
$this->container->get('models')
);
}
/**
* @return Setup
*/
private function getSetup()
{
return new Setup(
$this->getPath(),
$this->container->get('shopware_attribute.crud_service'),
$this->container->get('dbal_connection'),
$this->container->get('models'),
$this->container->get('shopware.model_config')
);
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>auth</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f5f5f5;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
form {
background-color: #ffffff;
border-radius: 10px;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
padding: 30px;
width: 400px;
}
form label {
font-weight: bold;
display: block;
margin-bottom: 10px;
color: #555555;
}
form input[type="text"],
form input[type="email"],
form input[type="password"],
form textarea {
width: 100%;
padding: 12px;
border: 1px solid #cccccc;
border-radius: 5px;
margin-bottom: 20px;
font-size: 16px;
color: #333333;
}
form input[type="submit"] {
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
padding: 12px 20px;
font-size: 16px;
cursor: pointer;
}
form input[type="submit"]:hover {
background-color: #0056b3;
}
form textarea {
resize: vertical;
}
.errorlist {
color: #dc3545;
list-style: none;
padding-left: 0;
font-size: 14px;
margin-top: 5px;
}
.errorlist li {
margin-bottom: 5px;
}
</style>
</head>
<body>
<form action="" method="POST" novalidate>
{% csrf_token %}
{% for fo in form %}
<label>{{fo.label_tag}}</label>
{{fo}}
<ul class="errorlist">
{% for error in fo.errors %}
<li>{{ error|striptags }}</li>
{% endfor %}
</ul>
{% endfor %}
<input type="submit" value="Submit">
</form>
</body>
</html> |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.*;
/**
* MuseumRoom is the room where all the action takes place. It is utter chaos in this newly opened museum
* and thus highly suspectible to robbery despite the museums dreams to become one of the biggst.
*
* @author Edwin, Jean, Jerry
* @version May 2 2024
*/
public class MuseumRoom extends Room
{
private static GreenfootSound roomBGM = new GreenfootSound("SneakySnitch.mp3");
// Obstacle Bounding Boxes
private GreenfootImage worldImage = new GreenfootImage("room2.png");
private Obstacle displayTable1 = new Obstacle(84, 49); // (285, 723), (369, 674)
private Obstacle displayTable2 = new Obstacle(73, 64); // (144, 544), (217, 480)
private Obstacle brokenGlassBox = new Obstacle(85, 118); // (283, 272), (368, 154) //broken glass
private Obstacle littleGlassBox = new Obstacle(31, 43); // (76, 140), (107, 97) // little top right box
private Obstacle largeWoodBox = new Obstacle(106, 62); // (274, 402), (380, 346) // saturated brown box
private Obstacle mediumGlassBox = new Obstacle(71, 61); // (424, 544), (495, 483)
private Obstacle statue1 = new Obstacle(44, 68); // (89, 414), (133, 346)
private Obstacle statue2 = new Obstacle(44, 68); // (513, 414), (556, 346)
private Obstacle pillar1 = new Obstacle(39, 100); // (69, 665), (108, 566)
private Obstacle pillar2 = new Obstacle(39, 100); // (536, 665), (574, 566)
// Wall bounds
private Obstacle leftWall = new Obstacle(62, 548);
private Obstacle rightWall = new Obstacle(62, 548);
private Obstacle topWall = new Obstacle(635, 92);
private Obstacle wallSegLeft = new Obstacle(125, 64);
private Obstacle wallSegRight = new Obstacle(125, 64);
private Obstacle leftBound = new Obstacle(40, 223);
private Obstacle rightBound = new Obstacle(4, 223);
private Obstacle lowerBound = new Obstacle(663, 7);
// Where robbers and guards can spawn
private List<Pair> robberSpawns;
private List<Pair> guardSpawns;
// instance variables
private int robbers, guards, robberSpawnRate, visitorSpawnRate, dayLimit;
private int actCount;
// To count the days, and to display some text
private static DayCounter dayCounter;
private static Text museumText;
//Variables
private int money = 0;
private int valuablesStolenNumber = 0;
private int robbersCatchedNumber = 0;
private int income = 0;
private int maxIncome = 0;
//Images
private GreenfootImage moneyImage = new GreenfootImage("money.png");
private GreenfootImage valuableImage = new GreenfootImage("valuable.png");
private GreenfootImage robberImage = new GreenfootImage("robber.png");
private GreenfootImage potImage = new GreenfootImage("PinkPot.png");
private GreenfootImage silverPotImage = new GreenfootImage("SilverPot.png");
private GreenfootImage goldPotImage = new GreenfootImage("GoldPot.png");
private GreenfootImage tallPotImage = new GreenfootImage("valuableArtPot.png");
private GreenfootImage shortPotImage = new GreenfootImage("valuableArtPot2.png");
private GreenfootImage teaPotImage = new GreenfootImage("valuableTeaPot.png");
private GreenfootImage monaLisaImage = new GreenfootImage("paintingArt2.png");
private GreenfootImage paintingManImage = new GreenfootImage("paintingArt.png");
//Statistics
private Statistic moneyEarned = new Statistic(moneyImage, money, "$");
private Statistic valuablesStolen = new Statistic(valuableImage, valuablesStolenNumber);
private Statistic robbersCatched = new Statistic(robberImage, robbersCatchedNumber);
private Statistic museumIncome = new Statistic(moneyImage, income, "$");
//Price List
private ValueList potPriceLabel = new ValueList(potImage, "$"+Pot.price);
private ValueList silverPotPriceLabel = new ValueList(silverPotImage, "$"+SilverPot.price);
private ValueList goldPotPriceLabel = new ValueList(goldPotImage, "$"+GoldPot.price);
private ValueList tallPotPriceLabel = new ValueList(tallPotImage, "$"+AntiquePotTall.price);
private ValueList shortPotPriceLabel = new ValueList(shortPotImage, "$"+AntiquePotShort.price);
private ValueList teaPotPriceLabel = new ValueList(teaPotImage, "$"+AntiqueTeaPot.price);
private ValueList monaLisaPriceLabel = new ValueList(monaLisaImage, "$"+MonaLisa.price);
private ValueList paintingManPriceLabel = new ValueList(paintingManImage, "$"+PaintingMan.price);
private boolean isNight = false;
// For robber location
private boolean robberLoc[] = new boolean[3];
private static final int valuableCount = 6;
//Stores the possible locations of valuables
private static int[][] valuableLocation = new int[valuableCount][2];
//Stores the boolean for each valuable
private boolean[] valuableInWorld = {false, false, false, false, false, false}; //{Pot, SilverPot, GoldPot, AntiquePotTall, AntiquePotShort, AntiqueTeaPot}
//Array of valuables that are in the world
private Valuable[] roomValuables = new Valuable[valuableCount];
private static final int artCount = 2;
//Stores the possible locations of arts
private static int[][] artLocation = new int[artCount][2];
//Stores the boolean for each art
private boolean[] artInWorld = {false, false}; //{Mona Lisa, Painting Man}
//Array of valuables that are in the world
private Art[] roomArts = new Art[artCount];
// Utility Pair class -- See Class "Human" for more info
public class Pair {
int x, y;
public Pair(int x, int y) {
this.x = x; this.y = y;
}
}
/**
* Constructor for objects of class MuseumRoom.
*
* @param robbers The maximum number of robbers in the museum room
* @param guards The maximum number of guards in the museum room
* @param valuables The number of valuables in the museum room
* @param robberSpawnRate The spawn rate of robbers
* @param visitorSpawnRate The spawn rate of visitors
* @param dayLimit The limit of the amount of days that the museum is active
*/
public MuseumRoom(int robbers, int guards, int robberSpawnRate, int visitorSpawnRate, int dayLimit)
{
super(1000,816,0, 0);
setBackground(worldImage);
addObject(displayTable1, 327, 699);
//Add the location to the 2D array
valuableLocation[0][0] = 331;
valuableLocation[0][1] = 670;
addObject(displayTable2, 181, 512);
//Add the location to the 2D array
valuableLocation[1][0] = 184;
valuableLocation[1][1] = 483;
addObject(brokenGlassBox, 327, 213);
//Add the location to the 2D array
valuableLocation[2][0] = 331;
valuableLocation[2][1] = 162;
addObject(littleGlassBox, 92, 119);
//Add the location to the 2D array
valuableLocation[3][0] = 94;
valuableLocation[3][1] = 86;
addObject(largeWoodBox, 329, 374);
//Add the location to the 2D array
valuableLocation[4][0] = 331;
valuableLocation[4][1] = 346;
addObject(mediumGlassBox, 464, 514);
//Add the location to the 2D array
valuableLocation[5][0] = 466;
valuableLocation[5][1] = 486;
addObject(statue1, 115, 380);
addObject(statue2, 539, 380);
addObject(pillar1, 93, 590);
addObject(pillar2, 559, 590);
addObject(leftWall, 32, 366);
addObject(rightWall, 626, 366);
addObject(topWall, 326, 46);
//Add the location to the 2D array
artLocation[0][0] = 168;
artLocation[0][1] = 64;
artLocation[1][0] = 510;
artLocation[1][1] = 64;
addObject(wallSegLeft, 125, 218);
addObject(wallSegRight, 530, 218);
addObject(leftBound, 680, 720);
addObject(rightBound, 0, 720);
addObject(lowerBound, 330, 850);
// set instance variables
this.robbers = robbers; this.guards = guards; this.robberSpawnRate = robberSpawnRate; this.visitorSpawnRate = visitorSpawnRate; this.dayLimit = dayLimit;
// initialize robber and guard spawns
robberSpawns = new ArrayList<Pair>(3);
guardSpawns = new ArrayList<Pair>(3);
// add the locations of the spawn
robberSpawns.add(new Pair(330, 500));
robberSpawns.add(new Pair(200, 350));
robberSpawns.add(new Pair(450, 350));
// randomize the order of the spawns
Collections.shuffle(robberSpawns);
// based on how many robbers chosen, spawn in random locations
for (int i = 0;i<robbers;i++) {
Pair p = robberSpawns.remove(0);
if (p.x == 330 && p.y == 500) {
addObject(new Robber(3, 600, 4, 0), p.x, p.y);
robberLoc[0] = true;
}
else if (p.x == 200 && p.y == 350) {
addObject(new Robber(3, 600, 4, 1), p.x, p.y);
robberLoc[1] = true;
} else {
addObject(new Robber(3, 600, 4, 2), p.x, p.y);
robberLoc[2] = true;
}
}
// add the spawn locations for the guard
guardSpawns.add(new Pair(330, 770));
guardSpawns.add(new Pair(420, 200));
guardSpawns.add(new Pair(240, 200));
// randomize the order
Collections.shuffle(guardSpawns);
// randomly spawn guards
for (int i = 0;i<guards;i++) {
Pair p = guardSpawns.remove(0);
addObject(new Guard(1), p.x, p.y);
}
actCount = 1;
//Add the statistics at the top right of the world
int xPos = 780;
addObject(moneyEarned, xPos, 100);
addObject(valuablesStolen, xPos, 175);
addObject(robbersCatched, xPos, 250);
addObject(museumIncome, xPos, 350);
//Add the price list at the bottom right of the world
int xPos1 = 703, xPos2 = 865;
getBackground().drawImage(new GreenfootImage("Current Price", 24, Color.BLACK, Color.WHITE), xPos-7, 450);
addObject(potPriceLabel, xPos1, 510);
addObject(silverPotPriceLabel, xPos2, 510);
addObject(goldPotPriceLabel, xPos1, 590);
addObject(tallPotPriceLabel, xPos2, 590);
addObject(shortPotPriceLabel, xPos1, 670);
addObject(teaPotPriceLabel, xPos2, 670);
addObject(monaLisaPriceLabel, xPos1, 750);
addObject(paintingManPriceLabel, xPos2, 750);
// add a day counter
dayCounter = new DayCounter();
addObject(dayCounter, 830, 50);
// add some text
museumText = new Text("Museum Stats");
addObject(museumText, 830, 300);
//Spawn all valuables randomly
spawnValuables();
//Spawn all arts randomly
spawnArts();
// Set the paint order (for Nighttime class)
setPaintOrder(Statistic.class, Text.class, DayCounter.class, ValueList.class, SuperTextBox.class, Nighttime.class, Robber.class);
Robber.init();
}
/**
* Start music
*/
public void started() {
roomBGM.playLoop();
if(isNight) Nighttime.resumeAmbience();
}
/**
* Stop music
*/
public void stopped(){
roomBGM.stop();
if(isNight) Nighttime.pauseAmbience();
}
/**
* Setter for if the world is night or not
*/
public void setTime(boolean isNight){
this.isNight = isNight;
}
/**
* If a valuable is stolen by the robber and put to the deposit position, it is considered "gone".
* If this is the case, clear out the position to spawn the next valuable.
*
* @param index The index indicated which specific Valuable needs to clear out.
*/
public void clearValuablePosition(int index){
valuableInWorld[index] = false;
}
//Over all profit Income grow
public void gainIncome(int newIncome){
this.income += newIncome;
}
public void act() {
// play music
if(actCount == 1){
roomBGM.playLoop();
}
actCount++;
if(dayCounter.getDayCount() > dayLimit) {
calculateEnding();
}
maxIncome = Math.max(income, maxIncome);
// get if it is night or not (every 1600 acts, night will activate, and the night duration is 600)
isNight = (actCount % 1600) < 600;
if(actCount % 1600 == 0) { // spawn new night effect every 1600 acts
Nighttime night = new Nighttime();
addObject(night, 500, 408);
}
if (actCount % (600/visitorSpawnRate) == 0 && !isNight) { // every now and then based on visitor spawn rate, and also not night, spawn some visitors
addObject(new Visitor(1000, 1), 20, 670);
}
// Randomly spawn robber if 2 stations are vacant, spawn robber at specific location if only 1 station is vacant
// set robberLoc of that station to true to prevent others from coming
if (actCount % (1200/robberSpawnRate) == 0 && getObjects(Robber.class).size() < 3) {
if (robberLoc[0] == true) {
if (robberLoc[1] == true) {
addObject(new Robber(3, 600, 4, 2), 450, 350);
robberLoc[2] = true;
} else if (robberLoc[2] == true) {
addObject(new Robber(3, 600, 4, 1), 200, 350);
robberLoc[1] = true;
} else {
int rand = Greenfoot.getRandomNumber(2)+1;
if (rand == 1) {
addObject(new Robber(3, 600, 4, rand), 200, 350);
} else {
addObject(new Robber(3, 600, 4, rand), 450, 350);
}
robberLoc[rand] = true;
}
} else if (robberLoc[1] == true) {
if (robberLoc[0] == true) {
addObject(new Robber(3, 600, 4, 2), 450, 350);
robberLoc[2] = true;
} else if (robberLoc[2] == true) {
addObject(new Robber(3, 600, 4, 0), 330, 500);
robberLoc[0] = true;
} else {
int rand = Greenfoot.getRandomNumber(2);
if (rand == 1) {
addObject(new Robber(3, 600, 4, 2), 450, 350);
robberLoc[2] = true;
} else {
addObject(new Robber(3, 600, 4, 0), 330, 500);
robberLoc[0] = true;
}
}
} else if (robberLoc[2] == true) {
if (robberLoc[0] == true) {
addObject(new Robber(3, 600, 4, 1), 200, 350);
robberLoc[1] = true;
} else if (robberLoc[1] == true) {
addObject(new Robber(3, 600, 4, 0), 330, 500);
robberLoc[0] = true;
} else {
int rand = Greenfoot.getRandomNumber(2);
if (rand == 1) {
addObject(new Robber(3, 600, 4, rand), 200, 350);
} else {
addObject(new Robber(3, 600, 4, rand), 330, 500);
}
robberLoc[rand] = true;
}
} else {
int rand = Greenfoot.getRandomNumber(3);
if (rand == 0) {
addObject(new Robber(3, 600, 4, rand), 330, 500);
} else if (rand == 1) {
addObject(new Robber(3, 600, 4, rand), 200, 350);
} else {
addObject(new Robber(3, 600, 4, rand), 400, 350);
}
robberLoc[rand] = true;
}
}
//Prepare to spawn each Valuable
for(int i=0; i<roomValuables.length; i++){
if(roomValuables[i].getWaiting()){
roomValuables[i].prepareToSpawn();
}
}
if (income == 0 && actCount > 1200) {
Greenfoot.setWorld(new BadEnd(this));
}
boolean hasLoc = false;
for(int i=0; i<valuableInWorld.length; i++){
if (valuableInWorld[i] == true) {
hasLoc = true;
break;
}
}
if (!hasLoc) {
Greenfoot.setWorld(new BadEnd(this));
}
//Prepare to spawn each Art
for(int i=0; i<roomArts.length; i++){
if(roomArts[i].getWaiting()){
roomArts[i].prepareToSpawn();
}
}
}
/**
* Randomly spawn different valuables at different locations.
*/
public void spawnValuables(){
for(int i=0; i<valuableLocation.length; i++){
int x = valuableLocation[i][0];
int y = valuableLocation[i][1];
//If something is there, do not spawn any
if(getObjectsAt(x, y, Valuable.class).size()!=0){
continue;
}
//For this location, find a valuable to be spawned
boolean hasFalse = false;
for(boolean value : valuableInWorld) {
if(!value) {
hasFalse = true;
break;
}
}
//If this object at this index 'random' is not currently in world, then get the valuable coresponding to this index
while(hasFalse){
//If something is false in the array, still ramdomly get number
int random = Greenfoot.getRandomNumber(valuableInWorld.length);
if(valuableInWorld[random]==true){
continue;
}
//If this object at this index 'random' is not currently in world, then get the valuable coresponding to this index
Valuable valuable;
switch(random){
case 0: {
valuable = new Pot(x,y);
roomValuables[0] = valuable;
break;
}
case 1: {
valuable = new SilverPot(x,y);
roomValuables[1] = valuable;
break;
}
case 2: {
valuable = new GoldPot(x,y);
roomValuables[2] = valuable;
break;
}
case 3: {
valuable = new AntiquePotTall(x,y);
roomValuables[3] = valuable;
break;
}
case 4: {
valuable = new AntiquePotShort(x,y);
roomValuables[4] = valuable;
break;
}
default: {
valuable = new AntiqueTeaPot(x,y);
roomValuables[5] = valuable;
break;
}
}
//Spawn the valuable at x & y
addObject(valuable, x, y);
valuableInWorld[random] = true;
//Go to the next location
break;
}
}
// if (i < 6) {
// }
// else {
// Valuable valuable = new Art(520, 60);
// addObject(valuable, 520, 60);
// artInWorld = true;
// }
}
/**
* Randomly spawn different arts at different locations.
*/
public void spawnArts(){
for(int i=0; i<artLocation.length; i++){
int x = artLocation[i][0];
int y = artLocation[i][1];
//If something is there, do not spawn any
if(getObjectsAt(x, y, Art.class).size()!=0){
continue;
}
//For this location, find a valuable to be spawned
boolean hasFalse = false;
for(boolean value : artInWorld) {
if(!value) {
hasFalse = true;
break;
}
}
while(hasFalse){
//If something is false in the array, still ramdomly get number
int random = Greenfoot.getRandomNumber(artInWorld.length);
if(artInWorld[random]==true){
continue;
}
//If this object at this index 'random' is not currently in world, then get the art coresponding to this index
Art art;
switch(random){
case 0: {
art = new MonaLisa(x,y);
roomArts[0] = art;
break;
}
default: {
art = new PaintingMan(x,y);
roomArts[1] = art;
break;
}
}
//Spawn the valuable at x & y
addObject(art, x, y);
artInWorld[random] = true;
//Go to the next location
break;
}
}
}
/**
* Set the new value of money stolen.
*
* @param change The change in the amount of money stolen by Robber.
*/
public void setMoney(int change){
money += change;
moneyEarned.updateValue(money);
}
public void setIncome(int change){
income += change;
museumIncome.updateValue(income);
}
/**
* Set the new number of valuables stolen.
*
* @param change The change in the amount of valuables stolen from room.
*/
public void setValuables(int change){
valuablesStolenNumber += change;
valuablesStolen.updateValue(valuablesStolenNumber);
}
/**
* Set the new value of robbers catched.
*
* @param change The change in the amount of robbers catched in room.
*/
public void setRobbers(int change){
robbersCatchedNumber += change;
robbersCatched.updateValue(robbersCatchedNumber);
}
/*
* Add the Valuable to the Array.
*
* @param v The Valuable that needs to be added.
*/
/*public void addValuables(Valuable v, int index){
roomValuables[index] = v;
}*/
/*
* Remove the Valuable from the ArrayList.
*
* @param v The Valuable that needs to be removed.
*/
/*public void removeValuables(Valuable v){
roomValuables.remove(v);
}*/
/**
* Get the current value of money stolen.
*/
public int getMoney(){
return money;
}
/**
* Get the current income.
*/
public int getIncome(){
return income;
}
/**
* Get the current number of valuables stolen.
*/
public int getValuables(){
return valuablesStolenNumber;
}
/**
* Get the new value of robbers catched.
*/
public int getRobbers(){
return robbersCatchedNumber;
}
public void setStation(int stationNumber, boolean b) {
robberLoc[stationNumber] = b;
}
public int getMaxIncome() {
return maxIncome;
}
public int getStation() {
if (robberLoc[0] == false) {
return 0;
} else if (robberLoc[1] == false) {
return 1;
} else {
return 2;
}
}
/**
* Increases the day count
*/
public static void increaseDayCount() {
dayCounter.incrementDayCount();
}
/**
* Returns whether it is currently night time.
*/
public boolean isNighttime(){
return isNight;
}
public void calculateEnding() {
roomBGM.stop();
Nighttime.pauseAmbience();
if(maxIncome < 800) {
Greenfoot.setWorld(new BadEnd(this));
}
else if(maxIncome > 800 && maxIncome < 2000) {
Greenfoot.setWorld(new MidEnd(this));
}
else if (maxIncome > 2000) {
Greenfoot.setWorld(new GoodEnd(this));
}
}
} |
/**
* @license Copyright (c) 2003-2021, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
/* globals ClassicEditor, console, window, document, ListStyle */
import { CS_CONFIG } from '@ckeditor/ckeditor5-cloud-services/tests/_utils/cloud-services-config';
ClassicEditor
.create( document.querySelector( '#snippet-paste-from-office' ), {
extraPlugins: [ ListStyle ],
toolbar: {
items: [
'heading',
'|',
'fontSize',
'fontFamily',
'fontColor',
'fontBackgroundColor',
'|',
'bold',
'italic',
'underline',
'strikethrough',
'-',
'alignment',
'|',
'numberedList',
'bulletedList',
'|',
'outdent',
'indent',
'|',
'link',
'uploadImage',
'insertTable',
'horizontalLine',
'|',
'undo',
'redo'
],
shouldNotGroupWhenFull: true
},
ui: {
viewportOffset: {
top: window.getViewportTopOffsetConfig()
}
},
image: {
toolbar: [
'imageStyle:inline',
'imageStyle:wrapText',
'imageStyle:breakText',
'|',
'toggleImageCaption',
'imageTextAlternative'
]
},
table: {
contentToolbar: [
'tableColumn',
'tableRow',
'mergeTableCells',
'tableProperties',
'tableCellProperties'
]
},
fontFamily: {
supportAllValues: true
},
fontSize: {
options: [ 10, 12, 14, 'default', 18, 20, 22 ],
supportAllValues: true
},
placeholder: 'Paste the content here to test the feature.',
cloudServices: CS_CONFIG
} )
.then( editor => {
window.editor = editor;
// Prevent showing a warning notification when user is pasting a content from MS Word or Google Docs.
window.preventPasteFromOfficeNotification = true;
} )
.catch( err => {
console.error( err.stack );
} ); |
'use strict'
import React from 'react'
import { connect } from 'react-redux'
import { Navbar as MDBNavbar, NavbarBrand, NavbarNav, NavbarToggler, Collapse, NavItem, NavLink } from 'mdbreact'
import userManager from '../Authentication/userManager'
import { ssoBaseURL } from '../../config/ssoBaseURL'
import { locale } from 'moment';
const mapStateToProps = (state, props) => {
let user = state.oidc.user
let { navigation: { locationHash }} = state
return { user, locationHash }
}
class Navbar extends React.Component {
constructor(props) {
super(props)
this.state = {
collapse: false,
isWideEnough: false,
dropdownOpen: false
}
this.onClick = this.onClick.bind(this)
this.toggle = this.toggle.bind(this)
this.LoginLogout = this.LoginLogout.bind(this)
this.GetUser = this.GetUser.bind(this)
this.Register = this.Register.bind(this)
}
onClick() {
this.setState({
collapse: !this.state.collapse,
});
}
toggle() {
this.setState({
dropdownOpen: !this.state.dropdownOpen
});
}
LoginLogout() {
let { user } = this.props
if (!user || user.expired) {
return <a className="nav-link" href="#/login">Login</a>
}
else {
return <a className="nav-link" href="#/logout">Logout</a>
}
}
Register() {
let { user } = this.props
if (!user || user.expired) {
return <a key="lnkRegister" className="nav-link" href={ssoBaseURL + "Account/Register"} target="_blank">Register</a>
}
}
GetUser() {
let { user } = this.props
if (!user || user.expired) {
return <span style={{ color: "#d0d6e2" }} className="nav-link"></span>
}
else {
return <span style={{ color: "#d0d6e2" }} className="nav-link">{"Hello, " + user.profile.email}</span>
}
}
makeNavLink(hash, text) {
let { locationHash } = this.props
return (
<NavItem active={locationHash === hash}>
<a className="nav-link" href={hash}>{text}</a>
</NavItem>
)
}
render() {
return (
<MDBNavbar size="sm" color="blue darken-2" expand="md" dark >
{!this.state.isWideEnough && <NavbarToggler onClick={this.onClick} />}
<Collapse isOpen={this.state.collapse} navbar>
<NavbarBrand tag="span">
<b>React Boilerplate & Templates</b>
</NavbarBrand>
<NavbarNav left>
{this.makeNavLink("#/", "Home")}
{this.makeNavLink("#/components", "Components")}
{this.makeNavLink("#/list", "List-View")}
</NavbarNav>
<NavbarNav right>
<NavItem>
{this.GetUser()}
</NavItem>
<NavItem>
{this.LoginLogout()}
</NavItem>
<NavItem>
{this.Register()}
</NavItem>
</NavbarNav>
</Collapse>
</MDBNavbar>
)
}
}
export default connect(mapStateToProps)(Navbar) |
package email
import (
"testing"
)
const email = `From: [email protected]
To: [email protected], [email protected]
Subject: Subject
Body`
func TestEmailMatch(t *testing.T) {
email, err := Parse([]byte(email))
if err != nil {
t.Fatalf("cannot create email: %v", err)
}
tests := []struct {
name string
option MatchOption
value string
expected bool
}{
{
name: "Exact match for subject",
option: MatchOption{Field: MatchSubjectField, Type: ExactMatch, CaseSensitive: true},
value: "Subject",
expected: true,
},
{
name: "Exact match for body",
option: MatchOption{Field: MatchBodyField, Type: ExactMatch, CaseSensitive: true},
value: "Body",
expected: true,
},
{
name: "Exact match for sender",
option: MatchOption{Field: MatchSenderField, Type: ExactMatch, CaseSensitive: true},
value: "[email protected]",
expected: true,
},
{
name: "Exact match for recipient",
option: MatchOption{Field: MatchRecipientField, Type: ExactMatch, CaseSensitive: true},
value: "[email protected]",
expected: true,
},
{
name: "Contains match for body",
option: MatchOption{Field: MatchBodyField, Type: ContainsMatch, CaseSensitive: true},
value: "dy",
expected: true,
},
{
name: "Exact match for subject (case-insensitive)",
option: MatchOption{Field: MatchSubjectField, Type: ExactMatch, CaseSensitive: false},
value: "subject",
expected: true,
},
{
name: "Exact match for recipient (case-insensitive)",
option: MatchOption{Field: MatchRecipientField, Type: ExactMatch, CaseSensitive: false},
value: "[email protected]",
expected: true,
},
{
name: "Exact match for recipient with incorrect case",
option: MatchOption{Field: MatchRecipientField, Type: ExactMatch, CaseSensitive: true},
value: "[email protected]",
expected: false,
},
{
name: "No match and no attachment",
option: MatchOption{Field: MatchNoField, Type: ExactMatch, CaseSensitive: true, HasAttachment: true},
value: "",
expected: false,
},
{
name: "Exact match for invalid field",
option: MatchOption{Field: MatchFieldEnum(999), Type: ExactMatch, CaseSensitive: true},
value: "Value",
expected: false,
},
{
name: "Match all",
option: MatchOption{Type: AllMatch},
value: "",
expected: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
result := email.Match(test.option, test.value)
if result != test.expected {
t.Errorf("Expected match result %v, but got %v (test=%q)", test.expected, result, test.name)
}
})
}
} |
using System;
using System.Collections.Generic;
using OOP.Model.Enums;
namespace OOP.Model.Orders
{
/// <summary>
/// Класс заказа.
/// </summary>
public class Order : IEquatable<Order>
{
/// <summary>
/// Свойство id заказа.
/// </summary>
public int Id { get; set; }
/// <summary>
/// Свойство даты создания заказа.
/// </summary>
public DateTime DateOfCreate { get; set; }
/// <summary>
/// Свойство для списка товаров заказа.
/// </summary>
public List<Item> Items { get; set; }
/// <summary>
/// Свойство для адреса доставки.
/// </summary>
public Address Address { get; set; }
/// <summary>
/// Размер примененной скидки.
/// </summary>
public decimal DiscountAmount { get; set; }
/// <summary>
/// Свойство для общей стоимости заказа.
/// </summary>
public decimal FullCost
{
get
{
var sum = 0.0m;
if (Items == null || Items.Count == 0)
{
return sum;
}
else
{
foreach (var item in Items)
{
sum += item.Cost;
}
return sum;
}
}
}
/// <summary>
/// Тип заказа.
/// </summary>
public OrderStatus OrderStatus { get; set; }
/// <summary>
/// Перегрузка метода Equals.
/// </summary>
/// <param name="other">Сравниваемый объект.</param>
/// <returns>True, если одинаковый адрес и статус заказа, иначе False.</returns>
public bool Equals(Order other)
{
return (this.Address == other.Address && this.OrderStatus == other.OrderStatus);
}
/// <summary>
/// Конструктор без параметров.
/// </summary>
public Order()
{
this.Id = Services.IdGenerator.GetNextOrderID();
this.Address = new Model.Address();
this.Items = new List<Model.Item>();
}
/// <summary>
/// Конструктор класса заказ.
/// </summary>
/// <param name="creatingDate">Дата создания заказа.</param>
/// <param name="address">Адрес доставки.</param>
/// <param name="orderStatus">Статус заказа.</param>
public Order(DateTime creatingDate, Address address, OrderStatus orderStatus)
{
this.Id = Services.IdGenerator.GetNextOrderID();
this.DateOfCreate = creatingDate;
this.Address = address;
this.OrderStatus = orderStatus;
this.Items = new List<Model.Item>();
}
}
} |
package org.wonderly.swing.tabs;
import javax.swing.plaf.basic.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
//import org.wonderly.awt.*;
import java.util.logging.*;
import java.util.*;
/**
* <pre>
Copyright (c) 1997-2006, Gregg Wonderly
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* The name of the author may not be used to endorse or promote
products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
* </pre>
*
* This class is a subclass of JTabbedPane which provides tab close buttons.
*/
public class CloseableTabbedPane extends JTabbedPane {
private Logger log = Logger.getLogger(getClass().getName());
private Vector<TabCloseListener> tlis = new Vector<TabCloseListener>();
private Vector<Integer> unclosable = new Vector<Integer>();
private volatile MyTabbedPaneUI ui;
/**
* Tyically, the last tab open is not closable. So, call this method with a
* tab number and that tab will not contain a close icon. If you monitor
* with a {@link TabCloseListener}, you can use {@link #getTabCount()} and
* when it is 1, you can call {@link #setUncloseableTab(int)}(0) to make the
* last tab unclosable.
*
* @see #setCloseableTab(int);
*/
public void setUnclosableTab(int val) {
if (unclosable.contains(val))
return;
unclosable.addElement(val);
}
/**
* Use this method to reverse the actions of {@link #setUnclosableTab(int)}
*/
public void setClosableTab(int val) {
unclosable.removeElement(val);
}
/**
* Add a tab close listener. On close events, the listener is responsible
* for deleting the tab or otherwise reacting to the event.
*/
public void addTabCloseListener(TabCloseListener lis) {
tlis.addElement(lis);
}
/** Remove a tab close listener */
public void removeTabCloseListener(TabCloseListener lis) {
tlis.removeElement(lis);
}
/** Create a new tabbed pane */
public CloseableTabbedPane() {
this(JTabbedPane.TOP);
}
/** Create a tabbed pane */
public CloseableTabbedPane(int placement) {
this(placement, JTabbedPane.WRAP_TAB_LAYOUT);
}
/** Create a tabbed pane */
public CloseableTabbedPane(int placement, int layout) {
super(placement, layout);
setUI(ui = new MyTabbedPaneUI(this));
// ImageIcon ic = new ImageIcon(
// getClass().getClassLoader().getResource("close.jpg") );
// ImageIcon dc = new ImageIcon(
// getClass().getClassLoader().getResource("down.jpg") );
// setCloseIcons(ic,dc);
}
public void setCloseIcons(ImageIcon ic, ImageIcon downIcon) {
ui.setCloseIcons(ic, downIcon);
}
private void closeTab(int tab) {
log.fine("Closing tab: " + tab + ", listeners: " + tlis);
if (tlis.size() == 0)
return;
TabCloseEvent ev = new TabCloseEvent(this, tab);
for (TabCloseListener l : tlis) {
try {
log.finer("Sending close to: " + l);
l.tabClosed(ev);
} catch (Exception ex) {
log.log(Level.SEVERE, ex.toString(), ex);
}
}
}
public void setCloseSize(int sz) {
ui.closeWidth = sz;
repaint();
}
private static class MyTabbedPaneUI extends BasicTabbedPaneUI {
Logger log = Logger.getLogger(getClass().getName());
CloseableTabbedPane mypane;
ImageIcon ci;
ImageIcon dci;
public MyTabbedPaneUI(CloseableTabbedPane ctp) {
mypane = ctp;
}
public void setCloseIcons(ImageIcon icon, ImageIcon downIcon) {
ci = icon;
dci = downIcon;
}
public class MouseLis extends MouseAdapter implements MouseMotionListener {
public void mouseReleased(MouseEvent e) {
closeIdx = -1;
tabPane.repaint();
}
public void mouseClicked(MouseEvent e) {
if (!tabPane.isEnabled()) {
log.finer("clicked, not enabled");
return;
}
if (e.getButton() != 1) {
log.finer("clicked, not button 1");
return;
}
int tabIndex = tabForCoordinate(tabPane, e.getX(), e.getY());
if (tabIndex == -1) {
log.finer("clicked no valid tab");
return;
}
if (mypane.unclosable.contains(tabIndex)) {
log.finer("clicked, not closable");
return;
}
Rectangle r = closeRectFor(tabIndex);
// Check for mouse being in close box
if (r.contains(new Point(e.getX(), e.getY()))) {
// Send tab closed message
mypane.closeTab(tabIndex);
}
}
public void mousePressed(MouseEvent e) {
if (!tabPane.isEnabled()) {
return;
}
if (e.getButton() != 1) {
log.finer("Not button 1");
return;
}
int tabIndex = tabForCoordinate(tabPane, e.getX(), e.getY());
if (tabIndex == -1) {
log.finer("No valid tab index");
return;
}
if (mypane.unclosable.contains(tabIndex)) {
log.finer("Non-closable tab");
return;
}
Rectangle r = closeRectFor(tabIndex);
if (r.contains(new Point(e.getX(), e.getY())))
closeIdx = tabIndex;
else
closeIdx = -1;
tabPane.repaint();
}
public void mouseDragged(MouseEvent e) {
mouseMoved(e);
mousePressed(e);
}
public void mouseMoved(MouseEvent e) {
if (tabPane == null || !tabPane.isEnabled()) {
log.finer("Tabpane disabled");
return;
}
int tabIndex = tabForCoordinate(tabPane, e.getX(), e.getY());
if (tabIndex == -1) {
log.finer("not on a tab");
return;
}
if (mypane.unclosable.contains(tabIndex)) {
log.finer("non-closable tab");
return;
}
Rectangle r = closeRectFor(tabIndex);
log.finer("rects[tabIndex].x = " + rects[tabIndex].x + ", " + "rects[tabIndex].y=" + rects[tabIndex].y
+ ", " + "rects[tabIndex].width=" + rects[tabIndex].width + ", " + "closeWidth=" + closeWidth
+ ", " + "closeWidth/2=" + (closeWidth / 2) + ", " + "m.x=" + e.getX() + ", m.y=" + e.getY()
+ ", r=" + r);
if (r.contains(new Point(e.getX(), e.getY())))
closeOverIdx = tabIndex;
else
closeOverIdx = -1;
tabPane.repaint();
}
}
private Rectangle closeRectFor(int tabIndex) {
int cw = closeWidth();
return new Rectangle(rects[tabIndex].x + rects[tabIndex].width - cw - cw / 2,
rects[tabIndex].y + (lastTabHeight - (ci == null ? cw : ci.getIconHeight())) / 2, cw, cw + 1);
}
/**
* Override this to provide extra space on right for close button
*/
protected int calculateTabWidth(int tabPlacement, int tabIndex, FontMetrics metrics) {
int w = super.calculateTabWidth(tabPlacement, tabIndex, metrics);
if (mypane.unclosable.contains(tabIndex) == false)
w += closeWidth() + closeWidth() / 2;
return w;
}
volatile int lastTabHeight = 0;
/**
* Override this to provide extra space on right for close button
*/
protected int calculateTabHeight(int tabPlacement, int tabIndex, int v) {
int h = super.calculateTabHeight(tabPlacement, tabIndex, v);
if (mypane.unclosable.contains(tabIndex) == false)
h = Math.max(h, (ci != null ? ci.getIconHeight() : closeWidth) + 6);
return lastTabHeight = h;
}
public int closeWidth() {
return ci != null ? ci.getIconWidth() : closeWidth;
}
volatile int closeIdx = -1;
volatile int closeWidth = 14;
volatile int closeOverIdx = -1;
int closeDownIdx() {
return closeIdx;
}
protected void paintText(Graphics g, int tabPlacement, Font font, FontMetrics metrics, int tabIndex,
String title, Rectangle textRect, boolean isSelected) {
Rectangle r = new Rectangle(textRect);
if (mypane.unclosable.contains(tabIndex) == false) {
r.x -= closeWidth - (closeWidth / 2);
}
super.paintText(g, tabPlacement, font, metrics, tabIndex, title, r, isSelected);
}
protected void paintIcon(Graphics g, int tabPlacement, int tabIndex, Icon icon, Rectangle iconRect,
boolean isSelected) {
Rectangle r = new Rectangle(iconRect);
if (mypane.unclosable.contains(tabIndex) == false) {
r.x -= closeWidth - (closeWidth / 2);
}
super.paintIcon(g, tabPlacement, tabIndex, icon, r, isSelected);
}
protected void paintTabBackground(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h,
boolean isSelected) {
super.paintTabBackground(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
if (mypane.unclosable.contains(tabIndex))
return;
final int ov = closeWidth();
if (ci != null) {
g.drawImage(closeDownIdx() != tabIndex ? ci.getImage() : dci.getImage(), x + w - ov - (ov / 2),
y + (h - ci.getIconHeight()) / 2, mypane);
} else {
// Get a constant, immutable value for painting.
g.setColor((closeOverIdx == tabIndex && closeDownIdx() == -1) ? new Color(220, 230, 255)
: Color.gray.brighter());
g.fill3DRect(x + w - ov - (ov / 2), y + (h - ov) / 2, ov, ov, closeDownIdx() != tabIndex);
g.draw3DRect(x + w - ov - (ov / 2) - 1, y + (h - ov) / 2, ov + 1, ov + 1, closeDownIdx() != tabIndex);
g.setColor(Color.black);
g.drawLine(x + w - (ov / 2) - 0, y + ((h - ov) / 2) + 0, x + w - ov - (ov / 2) + 2,
y + ((h - ov) / 2) + ov - 2);
g.drawLine(x + w - ov - (ov / 2) + 2, y + ((h - ov) / 2) + 2, x + w - (ov / 2) - 2,
y + ((h - ov) / 2) + ov - 2);
}
}
protected void installListeners() {
super.installListeners();
MouseLis mlis = new MouseLis();
tabPane.addMouseListener(mlis);
tabPane.addMouseMotionListener(mlis);
}
}
} |
import React from 'react';
const UpdateForm = ({
issueId,
priorityId,
priorities,
handleUpdate,
setIssueId,
setPriorityId,
}) => (
<div className="max-w-lg mx-auto mt-8 font-RedHatMedium max-[768px]:w-[95%] max-[768px]:mx-auto">
<form className="">
<div className="mb-6">
<label className="block text-gray-700 text-sm font-bold mb-2">ID de la Issue:</label>
<input
className="w-full border p-2 rounded-md focus:outline-none focus:ring focus:border-blue-500"
type="text"
placeholder="Ej. 426"
value={issueId}
onChange={(e) => setIssueId(e.target.value)}
/>
</div>
<div className="mb-6">
<label className="block text-gray-700 text-sm font-bold mb-2">Nueva Prioridad:</label>
<select
className="w-full border p-2 rounded-md focus:outline-none focus:ring focus:border-blue-500"
value={priorityId}
onChange={(e) => setPriorityId(e.target.value)}
>
<option value="">Seleccione una prioridad</option>
{priorities.map((priority) => (
<option key={priority.id} value={priority.id}>
{priority.type}
</option>
))}
</select>
</div>
<div className='flex justify-center'>
<button
className="bg-purpleBroobe text-white hover:bg-[#3b399c] transition-all px-2 py-2 rounded text-xl font-RedHatBold max-[768px]:text-xs"
type="button"
onClick={handleUpdate}
>
Actualizar Issue
</button>
</div>
</form>
</div>
);
export default UpdateForm; |
#
# @lc app=leetcode id=341 lang=python3
#
# [341] Flatten Nested List Iterator
#
from typing import *
class NestedInteger:
def isInteger(self) -> bool:
"""
@return True if this NestedInteger holds a single integer, rather than a nested list.
"""
pass
def getInteger(self) -> int:
"""
@return the single integer that this NestedInteger holds, if it holds a single integer
Return None if this NestedInteger holds a nested list
"""
pass
def getList(self) -> List[NestedInteger]:
"""
@return the nested list that this NestedInteger holds, if it holds a nested list
Return None if this NestedInteger holds a single integer
"""
pass
# @lc code=start
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger:
# def isInteger(self) -> bool:
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# """
#
# def getInteger(self) -> int:
# """
# @return the single integer that this NestedInteger holds, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# """
#
# def getList(self) -> [NestedInteger]:
# """
# @return the nested list that this NestedInteger holds, if it holds a nested list
# Return None if this NestedInteger holds a single integer
# """
class NestedIterator:
def __init__(self, nestedList: List[NestedInteger]):
self.stack: List[NestedInteger] = []
for i in range(len(nestedList) - 1, -1, -1):
self.stack.append(nestedList[i])
def next(self) -> int:
if self.hasNext():
return self.stack.pop().getInteger()
return None
def hasNext(self) -> bool:
while len(self.stack) and not self.stack[-1].isInteger():
lst = self.stack.pop().getList()
for i in range(len(lst) - 1, -1, -1):
self.stack.append(lst[i])
return bool(len(self.stack))
# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())
# @lc code=end |
<template>
<el-dialog
:title="'选择人员'"
width="600px"
top="10vh"
:modal="false"
:visible.sync="dialogVisible"
@close="handleClose"
>
<div class="title">选择人员</div>
<el-form :model="form" :rules="rules" ref="form" class="form" :inline="true">
<el-form-item prop="keyWord">
<el-input placeholder="请输入搜索关键字" v-model="form.keyWord"></el-input>
</el-form-item>
<el-button type="primary" @click="handleSearch">查询</el-button>
<el-button @click="resetForm">重置</el-button>
</el-form>
<div class="table" v-if="type === 'checkBox'">
<el-table
:data="tableData"
header-row-class-name="table-header"
size="medium"
ref="table"
highlight-current-row
style="width: 100%; height: 100%"
height="calc(100% - 40px)"
@selection-change="handleSelectionChange"
:row-key="getRowKey"
>
<el-table-column type="selection" width="55" :reserve-selection="true"> </el-table-column>
<el-table-column prop="nickName" label="姓名" width="120"></el-table-column>
<el-table-column prop="divsionName" label="行政区划" width=""></el-table-column>
</el-table>
</div>
<div class="table" v-else>
<el-table
:data="tableData"
header-row-class-name="table-header"
size="medium"
ref="table"
highlight-current-row
style="width: 100%; height: 100%"
height="calc(100% - 40px)"
@current-change="handleCurrentChange"
:row-key="getRowKey"
>
<el-table-column width="50">
<template slot-scope="scope">
<el-radio :value="radio" :label="scope.row.userId"><span> </span></el-radio>
</template>
</el-table-column>
<el-table-column prop="nickName" label="姓名" width="120"></el-table-column>
<el-table-column prop="divsionName" label="行政区划" width=""></el-table-column>
</el-table>
</div>
<div class="pagination">
<el-pagination
@current-change="handleCurrentPageChange"
:current-page="form.pageNum"
:page-size="form.pageSize"
layout="prev, pager, next"
:total="total"
>
</el-pagination>
</div>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="handleSave">下一步</el-button>
</span>
</el-dialog>
</template>
<script>
import { listUser } from '@/api/system/user';
export default {
props: ['code', 'type', 'url', 'divisionCode'],
components: {},
data() {
return {
dialogVisible: true,
showAddOut: false,
tableData: [],
form: {
pageNum: 1,
pageSize: 15,
whetherStock: 1,
// whetherSystemBuild: 2,
divisionCode: this.divisionCode,
},
total: 0,
radio: '',
currentRow: {},
rules: {},
selection: [],
};
},
computed: {
treeList() {
return this.$store.getters.divisionsTreeList;
},
},
watch: {
divisionCode: {
handler() {
this.form.divisionCode = this.divisionCode;
},
deep: true,
immediate: true,
},
},
mounted() {
console.log(this.divisionCode);
this.getList();
},
methods: {
getDivsionName(data, code, result = []) {
data.forEach((e) => {
if (e.weight === code) {
result.push(e.label);
return;
}
e.children && this.getDivsionName(e.children, code, result);
});
return result;
},
async getList() {
this.tableData = [];
listUser(this.form).then((res) => {
this.tableData = res.rows.map((item) => {
item.divsionName = this.getDivsionName(this.treeList, item.divisionCode)[0];
return item;
});
this.tableData = this.tableData.filter((item) => item.openId!==null);
this.total = res.total;
});
},
handleSave() {
console.log(this.currentRow);
if (this.type === 'radio') {
if (!this.currentRow.nickName) {
this.$message.warning('请选择人员');
return;
}
this.$emit('success', this.currentRow);
} else if (this.type === 'checkBox') {
if (!this.selection.length) {
this.$message.warning('请选择人员');
return;
}
console.log(this.selection);
this.$emit('success', this.selection);
}
},
handleSelectionChange(val) {
this.selection = val;
},
getRowKey(row) {
return row.userId;
},
handleCurrentChange(val) {
this.currentRow = val || {};
this.radio = val ? val.userId : '';
// this.$refs.singleTable.setCurrentRow(row)
},
handleCurrentPageChange(val) {
this.form.pageNum = val;
this.getList();
},
handleTabClick() {
this.radio = '';
this.form.pageNum = 1;
this.getList();
},
handleSearch() {
this.getList();
},
handleClose() {
this.$emit('close');
},
resetForm() {
this.$refs['form'].resetFields();
this.getList();
},
},
};
</script>
<style scoped lang="scss">
.title {
font-size: 16px;
font-weight: 500;
margin-bottom: 16px;
}
.main-tab {
margin-bottom: 16px;
}
.form {
width: 100%;
&::after {
content: '';
display: table;
clear: both;
}
}
.form .select,
.form .input {
width: 40%;
margin-right: 10px;
}
.subToolBar {
display: flex;
align-items: center;
button {
margin-left: 10px;
i {
font-size: 14px;
margin-right: 3px;
}
}
}
.table {
height: 45vh;
}
.pagination {
text-align: center;
}
.sex-item {
v-deep .el-input--small {
.el-input__inner {
width: 80px;
}
}
}
v-deep {
.el-tabs__header {
margin: 0;
}
}
</style> |
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>LAPORAN</title>
<!-- CSS -->
<link rel="stylesheet" href="{{ asset('css/util.css') }}">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" />
<!-- Bootstrap Font Icon CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css" />
</head>
<body>
<div class="col-md-6 container my-5">
<p class="text-center fw-bold fs-4">LIST PERIODE</p>
@if (session()->has('success'))
<div class="alert alert-success alert-dismissible fade show" role="alert">
{{ session('success') }}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
@endif
<div class="row mb-2">
<label for="bulan" class="col-form-label s-12 col-md-2 font-weight-bolder">Bulan</label>
<div class="col-sm-8">
<select id="bulan" onchange="getParams()" class="select2 form-control r-0 s-12">
<option value="1" {{ $bulan == 1 ? 'selected' : '-' }}>Januari</option>
<option value="2" {{ $bulan == 2 ? 'selected' : '-' }}>Februari</option>
<option value="3" {{ $bulan == 3 ? 'selected' : '-' }}>Maret</option>
<option value="4" {{ $bulan == 4 ? 'selected' : '-' }}>April</option>
<option value="5" {{ $bulan == 5 ? 'selected' : '-' }}>Mei</option>
<option value="6" {{ $bulan == 6 ? 'selected' : '-' }}>Juni</option>
<option value="7" {{ $bulan == 7 ? 'selected' : '-' }}>Juli</option>
<option value="8" {{ $bulan == 8 ? 'selected' : '-' }}>Agustus</option>
<option value="9" {{ $bulan == 9 ? 'selected' : '-' }}>September</option>
<option value="10" {{ $bulan == 10 ? 'selected' : '-' }}>Oktober</option>
<option value="11" {{ $bulan == 11 ? 'selected' : '-' }}>November</option>
<option value="12" {{ $bulan == 12 ? 'selected' : '-' }}>Desember</option>
</select>
</div>
</div>
<div class="row mb-4">
<div class="col-sm-2"></div>
<div class="col-sm-8">
<a href="#" id="periodeUrl" class="btn btn-success btn-sm m-r-5"><i class="bi bi-filter m-r-10"></i>Filter</a>
<a href="#" id="periodeGenerate" class="btn btn-primary btn-sm"><i class="bi bi-save m-r-10"></i>Generate</a>
</div>
</div>
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th>Tanggal</th>
<th>Bulan</th>
<th>tahun</th>
<th>Hari</th>
<th>Libur</th>
<th></th>
</tr>
</thead>
<tbody>
@forelse ($periode as $index => $i)
<tr>
<td>{{ $i->tanggal }}</td>
<td>{{ Carbon\Carbon::now()->month($i->bulan)->isoFormat('MMMM') }}</td>
<td>{{ $i->tahun }}</td>
<td>{{ $i->hari }}</td>
<td>
@if ($i->is_libur == 1)
<span class="fw-bold text-danger">Libur</span>
@else
<span class="fw-bold text-success">Tidak</span>
@endif
</td>
<td class="text-center">
@if ($i->is_libur == 1)
<a href="{{ route('periodeBatalkanLibur', $i->id) }}" class="btn btn-sm btn-danger"><i class="bi bi-trash m-r-10"></i>Batalkan Libur</a>
@else
<a href="{{ route('periodeLibur', $i->id) }}" class="btn btn-sm btn-primary"><i class="bi bi-check m-r-10"></i>Liburkan</a>
@endif
</td>
</tr>
@empty
<tr>
<td colspan="6" class="text-center">Tidak ada data. Silahkan generate</td>
</tr>
@endforelse
</tbody>
</table>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
<script>
getParams();
function getParams(){
bulan = $('#bulan').val();
url = "{{ route('periode') }}?bulan=" + bulan
urlGenerate = "{{ route('generatePeriode', ':bulan') }}".replace(':bulan', bulan);
$('#periodeUrl').attr('href', url)
$('#periodeGenerate').attr('href', urlGenerate)
}
</script>
</html> |
package it.corona.eboot.model;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.*;
import javax.persistence.*;
import java.time.Instant;
import java.time.LocalDateTime;
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@ToString
@Entity
@Table(name = "review")
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class Review {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Integer id;
@Column(name = "rating", nullable = false)
private Double rating;
@Column(name = "description", nullable = false, length = 500)
private String description;
@Column(name = "creation_datetime", insertable = false)
@JsonIgnore
private LocalDateTime creationDatetime;
@ToString.Exclude
@ManyToOne
@JoinColumn(name = "user_id", nullable = false)
private User user;
@ToString.Exclude
@ManyToOne
@JoinColumn(name = "product_id", nullable = false)
@JsonIgnore
private Product product;
@JsonGetter(value = "product_name")
public String getProductName(){
return this.product.getName();
}
@JsonGetter(value = "user")
public String getUsername(){
return this.user.getUsername();
}
} |
type ArrayOfObjects = Array<{
id: number;
[key: string]: any;
}>;
/**
* Creates an index map for an array of objects based on a specified key.
*
* @function
* @param {ArrayOfObjects[]} array - The array of objects to create the index map from.
* @param {string} idKey - The key in the objects to use for indexing.
* @returns {Record<any, any>} An index map where the keys are the values from the idKey of the objects and the values are their indices in the array.
* @example
* const arr = [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}];
* const indexMap = createIndexMap(arr, 'id');
* console.log(indexMap); // {1: 0, 2: 1}
*/
declare function createIndexMap(array: ArrayOfObjects, idKey: string): Record<any, any>;
/**
* Retrieves the index of an object in an array using its ID from a pre-constructed index map.
*
* @function
* @param {Record<any, any>} indexMap - The index map where the keys are object IDs and the values are their indices in the original array.
* @param {string} id - The ID of the object whose index needs to be retrieved.
* @returns {number} The index of the object in the original array. Returns `undefined` if the ID is not found in the index map.
* @example
* const indexMap = {1: 0, 2: 1};
* const index = findIndexById(indexMap, '1');
* console.log(index); // 0
*/
declare function findIndexById(indexMap: Record<any, any>, id: string): number;
/** @format */
/**
* Checks if two arrays are equal by comparing their elements.
*
* @function
* @param {any[]} arr1 - The first array to compare.
* @param {any[]} arr2 - The second array to compare.
* @returns {boolean} Returns `true` if the arrays are equal, otherwise `false`.
* @example
* const array1 = [1, 2, 3];
* const array2 = [1, 2, 3];
* const areEqual = IS_ARRAY_EQUAL(array1, array2);
* console.log(areEqual); // true
*
* @note This function uses `xorWith` and `isEqual` for comparison and `isEmpty` to check the result. Ensure these utilities are imported and available in the scope.
*/
declare const IS_ARRAY_EQUAL: (arr1: any[], arr2: any[]) => boolean;
/** @format */
/**
* Checks if a value is an array or not.
*
* @function
* @param {any[]} array - value to check if array or not.
* @returns {boolean} Returns `true` if the value provided is an array
*/
declare const IS_VALUE_ARRAY: (array: any) => boolean;
/** @format */
/**
* Checks if a value is a an array and if it contains an element.
*
* @function
* @param {any[]} array - value to check if array or not.
* @returns {boolean} Returns `true` if the value provided is an array and if it contains an element
*/
declare const IS_VALID_ARRAY: (array: any) => boolean;
declare const FILE_SIZE_100MB: number;
declare const FILE_SIZE_5MB: number;
declare const FILE_SIZE_3MB: number;
/** @format */
/**
* Checks if file size is greater than 100MB
*
* @function
* @param {any[]} fileSize - file size of the file for checking
* @returns {boolean} Returns `true` if the value is greater than 100MB.
*/
declare const IS_FILE_LARGER_100MB: (fileSize: number) => boolean;
/**
* Checks if file size is greater than 5MB
*
* @function
* @param {any[]} fileSize - file size of the file for checking
* @returns {boolean} Returns `true` if the value is greater than 5MB.
*/
declare const IS_FILE_LARGER_5MB: (fileSize: number) => boolean;
/**
* Checks if file size is greater than 3MB
*
* @function
* @param {any[]} fileSize - file size of the file for checking
* @returns {boolean} Returns `true` if the value is greater than 3MB.
*/
declare const IS_FILE_LARGER_3MB: (fileSize: number) => boolean;
/**
* Calculates the height of a 16:10 rectangle from the width.
* @param width The width of the rectangle.
* @returns The height of the rectangle.
*/
declare const calcHeight1610: (width: number) => number;
/** @format */
/**
* A utility for formatting numbers as currency in Philippine Peso (PHP) using the Filipino locale.
*
* @constant
* @type {Intl.NumberFormat}
* @example
* const amount = 1234.56;
* console.log(formatCurrencyPHP.format(amount)); // "1,234.56"
*
* @note This utility uses the "fil-PH" locale and is set to display numbers in decimal style with a minimum of 2 fraction digits.
*/
declare const formatCurrencyPHP: Intl.NumberFormat;
/** @format */
/**
* HEY SUCCESS Decodes an ID token and extracts user information and roles.
*
* @function
* @param {Object} params - The parameters for decoding.
* @param {string} params.IdToken - The ID token to decode.
* @param {Object} params.ROLE_ID - An object containing role identifiers.
* @returns {Object} An object containing user details and roles.
* @property {string} name - The user's name.
* @property {string} fname - The user's first name.
* @property {string} lname - The user's last name.
* @property {string} email - The user's email address.
* @property {boolean} email_verified - Indicates whether the user's email is verified.
* @property {string} username - The user's username.
* @property {string[]} roles - The roles assigned to the user.
* @property {boolean} isUserFreelancer - Indicates if the user is a freelancer.
* @property {boolean} isUserHSAdmin - Indicates if the user is an HS admin.
* @property {boolean} isUserFacilitator - Indicates if the user is a facilitator.
* @property {boolean} isUserBusiness - Indicates if the user is a business admin.
* @example
* const tokenDetails = hs_decodeIdToken({ IdToken: 'yourTokenHere', ROLE_ID: { freelancer: 'freelancerRoleID', hs_admin: 'hsAdminRoleID', facilitator: 'facilitatorRoleID', business_admin: 'businessAdminRoleID' } });
* console.log(tokenDetails);
*
* @note This function uses the `jwt-decode` library to decode the ID token.
*/
declare const hs_decodeIdToken: ({ IdToken, ROLE_ID }: {
IdToken: string;
ROLE_ID: any;
}) => {
name: string;
fname: string;
lname: string;
email: string;
email_verified: boolean;
username: string;
roles: string[];
};
/** @format */
declare const PASSWORD_HAS_NUMBER: (number: string) => boolean;
declare const PASSWORD_HAS_MIXED_LETTERS: (number: string) => boolean;
declare const PASSWORD_HAS_SPECIAL_CHARACTERS: (number: string) => boolean;
/** @format */
/**
* Limits the given text to a specified number of words.
* @param text The original text.
* @param wordLimit The maximum number of words.
* @returns The limited text.
*/
declare function limitWords(text: string, wordLimit: number): string;
/**
* Calculates the number of words in a given text.
*
* @function
* @param {string} [text=""] - The text whose word count needs to be determined. Defaults to an empty string.
* @returns {number} The number of words in the text.
* @example
* const wordCount = getWordLength("Hello, how are you?");
* console.log(wordCount); // 4
*
* @note This function splits the text based on whitespace to determine word count.
*/
declare function getWordLength(text?: string): number;
/** @format */
/**
* Removes all spaces from a string and converts it to lowercase.
*
* @function
* @param {string} string_param - The string from which spaces need to be removed and then converted to lowercase.
* @returns {string} The modified string without spaces and in lowercase.
* @example
* const modifiedString = stringRemoveSpaceLowercase("Hello World");
* console.log(modifiedString); // "helloworld"
*
* @note This function uses regular expressions to remove spaces from the string.
*/
declare const stringRemoveSpaceLowercase: (string_param: string) => string;
/** @format */
/**
* Capitalizes the first letter of a string or each substring separated by a specified character.
*
* @function
* @param {Object} params - The parameters for capitalization.
* @param {string} params.string - The string to be capitalized.
* @param {string} params.character - The character used to split the string.
* @returns {string} The capitalized string or capitalized substrings joined by the specified character.
* @example
* const capitalizedString = customCapitalize({ string: 'hello-world', character: '-' });
* console.log(capitalizedString); // "Hello-World"
*
* @note This function assumes the `capitalize` function is available in the scope to capitalize individual strings.
*/
declare const customCapitalize: ({ string, character }: {
string: string;
character: string;
}) => string;
/** @format */
/**
* Converts a given text to a Base64 data URI for PNG/JPEG images.
*
* @function
* @param {string} text - The text to be converted to a Base64 data URI.
* @returns {string} A Base64 data URI formatted for PNG/JPEG images.
* @example
* const base64Data = convertToBase64('yourBase64EncodedImageHere');
* console.log(base64Data); // "data:image/png/jpeg;base64, yourBase64EncodedImageHere"
*
* @note This function assumes the provided text is a valid Base64 encoded PNG or JPEG image.
*/
declare const convertToBase64: (text: string) => string;
export { FILE_SIZE_100MB, FILE_SIZE_3MB, FILE_SIZE_5MB, IS_ARRAY_EQUAL, IS_FILE_LARGER_100MB, IS_FILE_LARGER_3MB, IS_FILE_LARGER_5MB, IS_VALID_ARRAY, IS_VALUE_ARRAY, PASSWORD_HAS_MIXED_LETTERS, PASSWORD_HAS_NUMBER, PASSWORD_HAS_SPECIAL_CHARACTERS, calcHeight1610, convertToBase64, createIndexMap, customCapitalize, findIndexById, formatCurrencyPHP, getWordLength, hs_decodeIdToken, limitWords, stringRemoveSpaceLowercase }; |
import { useFilteredItemsByText } from "~/toolkit/hooks/useFilteredItemsByText";
import {
PagingContext,
usePagedItems,
usePagingStats,
} from "~/toolkit/hooks/usePaging";
import { SortDirType, useSorting } from "~/toolkit/hooks/useSorting";
interface UseTableProps {
filterKeys?: string[];
sortKey: string;
sortDir?: SortDirType;
initialPage?: number;
pageSize?: number;
shallow?: boolean;
initialFilter?: string;
}
interface TableStats {
totalItems: number;
start: number;
end: number;
}
export interface UseTableResult<T> {
showingItems: T[];
sorting: Omit<ReturnType<typeof useSorting>, "sortedItems">;
paging: PagingContext;
filtering: Omit<ReturnType<typeof useFilteredItemsByText>, "filteredItems">;
stats: TableStats;
}
// Based off of https://codesandbox.io/s/compount-components-with-a-hook-txolo?from-embed=&file=/table/table.hooks.js:0-844
export function useTable<T>(
allItems: T[],
{
filterKeys = [],
sortKey,
sortDir = "asc",
initialPage = 1,
pageSize = 25,
shallow = false,
initialFilter = "",
}: UseTableProps
) {
const { filteredItems, ...filtering } = useFilteredItemsByText(
allItems,
filterKeys,
initialFilter
);
const { sortedItems, ...sorting } = useSorting(filteredItems, {
sortKey,
sortDir,
});
pageSize = pageSize || allItems.length;
const [showingItems, paging] = usePagedItems(sortedItems, pageSize, {
initialPage,
shallow,
});
const stats = usePagingStats(
sortedItems.length,
pageSize,
paging.currentPage
);
return {
showingItems,
sorting,
paging,
filtering,
stats,
} as UseTableResult<T>;
}
interface TableQueryParams {
page?: string;
sortKey?: string;
sortDir?: string;
filter?: string;
} |
<!--BEGIN SIGN-IN FORM-->
<form
novalidate
class="osp-chat-form osp-chat-form--sign-in"
[formGroup]="user"
(ngSubmit)="onSubmit(user)">
<input
type="text"
class="osp-chat-form__input"
placeholder="Username"
formControlName="name">
<span class="osp-chat-form__hint"
*ngIf="!user.get('name').valid && user.get('name').touched">Your name must be at least 6 latin characters and digits</span>
<input
type="email"
class="osp-chat-form__input"
placeholder="Email"
formControlName="email">
<span class="osp-chat-form__hint"
*ngIf="!user.get('email').valid && user.get('email').touched">Please enter valid email</span>
<div class="osp-chat-form-group" formGroupName="passwords">
<input
type="password"
class="osp-chat-form__input"
placeholder="Enter password"
formControlName="password">
<span class="osp-chat-form__hint"
*ngIf="!user.get('passwords').get('password').valid && user.get('passwords').get('password').touched">Your password must be at least 8 latin characters and digits</span>
<input
type="password"
class="osp-chat-form__input"
placeholder="Password"
formControlName="passwordConfirmed">
<span class="osp-chat-form__hint"
*ngIf="!user.get('passwords').valid && user.get('passwords').get('passwordConfirmed').touched">The passwords are not identical</span>
</div>
<input type="submit"
class="osp-chat-form__submit osp-chat-form__submit--sign-in"
value="Sign-in"
[disabled]="user.invalid">
</form>
<!--END SIGN-IN FORM-->
<app-alt-login></app-alt-login> |
<!DOCTYPE node PUBLIC
"-//freedesktop//DTD D-Bus Object Introspection 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
<node name="/" xmlns:doc="http://www.freedesktop.org/dbus/1.0/doc.dtd">
<!--
org.gnome.evolution.dataserver.AddressBookCursor:
@short_description: Address book cursor objects
@since: 3.10
This interface allows for interaction with an address book cursor backend.
-->
<interface name="org.gnome.evolution.dataserver.AddressBookCursor">
<!--
Total:
The total number of contacts for this cursor query
-->
<property name="Total" type="u" access="read"/>
<!--
Position:
The current cursor position in the cursor query
-->
<property name="Position" type="u" access="read"/>
<!--
Step:
@revision_guard: The expected revision of the addressbook
@flags: The #EBookCursorStepFlags
@origin: The #EBookCursorOrigin
@count: The number of contacts to try and fetch, negative values step the cursor in reverse
@n_results: The number contacts actually traversed in this step.
@vcards: The returned contact list
@new_total: The total amount of contacts after moving the cursor
@new_position: The cursor position after moving
Step the cursor by @count contacts from @origin
This will also result in changes of the Position and Total properties
The @revision_guard will be checked against the current addressbook
revision, if the revisions differ then %E_CLIENT_ERROR_OUT_OF_SYNC
will be reported.
-->
<method name="Step">
<arg name="revision_guard" direction="in" type="s"/>
<arg name="flags" direction="in" type="i"/>
<arg name="origin" direction="in" type="i"/>
<arg name="count" direction="in" type="i"/>
<arg name="n_results" direction="out" type="i"/>
<arg name="vcards" direction="out" type="as"/>
<arg name="new_total" direction="out" type="u"/>
<arg name="new_position" direction="out" type="u"/>
</method>
<!--
SetAlphabeticIndex:
@index: The alphabetic index to set
@locale: The locale for which @index is known to be valid
Sets the cursor's alphabetic index, the index must be valid for @locale
and @locale is expected to be the current locale of the addressbook.
If the addressbook's locale has changed and doesn't match the @locale
argument then an error will be returned and the call should be retried.
This will also result in changes of the Position and Total properties
-->
<method name="SetAlphabeticIndex">
<arg name="index" direction="in" type="u"/>
<arg name="locale" direction="in" type="s"/>
<arg name="new_total" direction="out" type="u"/>
<arg name="new_position" direction="out" type="u"/>
</method>
<!--
SetQuery:
@query: The new query for this cursor
Changes the query for the given cursor
This will also result in changes of the Position and Total properties
-->
<method name="SetQuery">
<arg name="query" direction="in" type="s"/>
<arg name="new_total" direction="out" type="u"/>
<arg name="new_position" direction="out" type="u"/>
</method>
<!--
Dispose
Delete the server side resources for this cursor
-->
<method name="Dispose"/>
</interface> |
/** @module @lexical/link */
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import type {
DOMConversionMap,
DOMConversionOutput,
EditorConfig,
GridSelection,
LexicalCommand,
LexicalNode,
NodeKey,
NodeSelection,
RangeSelection,
SerializedElementNode,
} from 'lexical';
import {addClassNamesToElement} from '@lexical/utils';
import {
$applyNodeReplacement,
$getSelection,
$isElementNode,
$isRangeSelection,
createCommand,
ElementNode,
Spread,
} from 'lexical';
export type LinkAttributes = {
rel?: null | string;
target?: null | string;
};
export type SerializedLinkNode = Spread<
{
type: 'link';
url: string;
version: 1;
},
Spread<LinkAttributes, SerializedElementNode>
>;
/** @noInheritDoc */
export class LinkNode extends ElementNode {
/** @internal */
__url: string;
/** @internal */
__target: null | string;
/** @internal */
__rel: null | string;
static getType(): string {
return 'link';
}
static clone(node: LinkNode): LinkNode {
return new LinkNode(
node.__url,
{rel: node.__rel, target: node.__target},
node.__key,
);
}
constructor(url: string, attributes: LinkAttributes = {}, key?: NodeKey) {
super(key);
const {target = null, rel = null} = attributes;
this.__url = url;
this.__target = target;
this.__rel = rel;
}
createDOM(config: EditorConfig): HTMLAnchorElement {
const element = document.createElement('a');
element.href = this.__url;
if (this.__target !== null) {
element.target = this.__target;
}
if (this.__rel !== null) {
element.rel = this.__rel;
}
addClassNamesToElement(element, config.theme.link);
return element;
}
updateDOM(
prevNode: LinkNode,
anchor: HTMLAnchorElement,
config: EditorConfig,
): boolean {
const url = this.__url;
const target = this.__target;
const rel = this.__rel;
if (url !== prevNode.__url) {
anchor.href = url;
}
if (target !== prevNode.__target) {
if (target) {
anchor.target = target;
} else {
anchor.removeAttribute('target');
}
}
if (rel !== prevNode.__rel) {
if (rel) {
anchor.rel = rel;
} else {
anchor.removeAttribute('rel');
}
}
return false;
}
static importDOM(): DOMConversionMap | null {
return {
a: (node: Node) => ({
conversion: convertAnchorElement,
priority: 1,
}),
};
}
static importJSON(
serializedNode: SerializedLinkNode | SerializedAutoLinkNode,
): LinkNode {
const node = $createLinkNode(serializedNode.url, {
rel: serializedNode.rel,
target: serializedNode.target,
});
node.setFormat(serializedNode.format);
node.setIndent(serializedNode.indent);
node.setDirection(serializedNode.direction);
return node;
}
exportJSON(): SerializedLinkNode | SerializedAutoLinkNode {
return {
...super.exportJSON(),
rel: this.getRel(),
target: this.getTarget(),
type: 'link',
url: this.getURL(),
version: 1,
};
}
getURL(): string {
return this.getLatest().__url;
}
setURL(url: string): void {
const writable = this.getWritable();
writable.__url = url;
}
getTarget(): null | string {
return this.getLatest().__target;
}
setTarget(target: null | string): void {
const writable = this.getWritable();
writable.__target = target;
}
getRel(): null | string {
return this.getLatest().__rel;
}
setRel(rel: null | string): void {
const writable = this.getWritable();
writable.__rel = rel;
}
insertNewAfter(
selection: RangeSelection,
restoreSelection = true,
): null | ElementNode {
const element = this.getParentOrThrow().insertNewAfter(
selection,
restoreSelection,
);
if ($isElementNode(element)) {
const linkNode = $createLinkNode(this.__url, {
rel: this.__rel,
target: this.__target,
});
element.append(linkNode);
return linkNode;
}
return null;
}
canInsertTextBefore(): false {
return false;
}
canInsertTextAfter(): false {
return false;
}
canBeEmpty(): false {
return false;
}
isInline(): true {
return true;
}
extractWithChild(
child: LexicalNode,
selection: RangeSelection | NodeSelection | GridSelection,
destination: 'clone' | 'html',
): boolean {
if (!$isRangeSelection(selection)) {
return false;
}
const anchorNode = selection.anchor.getNode();
const focusNode = selection.focus.getNode();
return (
this.isParentOf(anchorNode) &&
this.isParentOf(focusNode) &&
selection.getTextContent().length > 0
);
}
}
function convertAnchorElement(domNode: Node): DOMConversionOutput {
let node = null;
if (domNode instanceof HTMLAnchorElement) {
const content = domNode.textContent;
if (content !== null && content !== '') {
node = $createLinkNode(domNode.getAttribute('href') || '', {
rel: domNode.getAttribute('rel'),
target: domNode.getAttribute('target'),
});
}
}
return {node};
}
export function $createLinkNode(
url: string,
attributes?: LinkAttributes,
): LinkNode {
return $applyNodeReplacement(new LinkNode(url, attributes));
}
export function $isLinkNode(
node: LexicalNode | null | undefined,
): node is LinkNode {
return node instanceof LinkNode;
}
export type SerializedAutoLinkNode = Spread<
{
type: 'autolink';
version: 1;
},
SerializedLinkNode
>;
// Custom node type to override `canInsertTextAfter` that will
// allow typing within the link
export class AutoLinkNode extends LinkNode {
static getType(): string {
return 'autolink';
}
static clone(node: AutoLinkNode): AutoLinkNode {
return new AutoLinkNode(
node.__url,
{rel: node.__rel, target: node.__target},
node.__key,
);
}
static importJSON(serializedNode: SerializedAutoLinkNode): AutoLinkNode {
const node = $createAutoLinkNode(serializedNode.url, {
rel: serializedNode.rel,
target: serializedNode.target,
});
node.setFormat(serializedNode.format);
node.setIndent(serializedNode.indent);
node.setDirection(serializedNode.direction);
return node;
}
static importDOM(): null {
// TODO: Should link node should handle the import over autolink?
return null;
}
exportJSON(): SerializedAutoLinkNode {
return {
...super.exportJSON(),
type: 'autolink',
version: 1,
};
}
insertNewAfter(
selection: RangeSelection,
restoreSelection = true,
): null | ElementNode {
const element = this.getParentOrThrow().insertNewAfter(
selection,
restoreSelection,
);
if ($isElementNode(element)) {
const linkNode = $createAutoLinkNode(this.__url, {
rel: this._rel,
target: this.__target,
});
element.append(linkNode);
return linkNode;
}
return null;
}
}
export function $createAutoLinkNode(
url: string,
attributes?: LinkAttributes,
): AutoLinkNode {
return $applyNodeReplacement(new AutoLinkNode(url, attributes));
}
export function $isAutoLinkNode(
node: LexicalNode | null | undefined,
): node is AutoLinkNode {
return node instanceof AutoLinkNode;
}
export const TOGGLE_LINK_COMMAND: LexicalCommand<
string | ({url: string} & LinkAttributes) | null
> = createCommand('TOGGLE_LINK_COMMAND');
export function toggleLink(
url: null | string,
attributes: LinkAttributes = {},
): void {
const {target} = attributes;
const rel = attributes.rel === undefined ? 'noopener' : attributes.rel;
const selection = $getSelection();
if (!$isRangeSelection(selection)) {
return;
}
const nodes = selection.extract();
if (url === null) {
// Remove LinkNodes
nodes.forEach((node) => {
const parent = node.getParent();
if ($isLinkNode(parent)) {
const children = parent.getChildren();
for (let i = 0; i < children.length; i++) {
parent.insertBefore(children[i]);
}
parent.remove();
}
});
} else {
// Add or merge LinkNodes
if (nodes.length === 1) {
const firstNode = nodes[0];
// if the first node is a LinkNode or if its
// parent is a LinkNode, we update the URL, target and rel.
const linkNode = $isLinkNode(firstNode)
? firstNode
: $getLinkAncestor(firstNode);
if (linkNode !== null) {
linkNode.setURL(url);
if (target !== undefined) {
linkNode.setTarget(target);
}
if (rel !== null) {
linkNode.setRel(rel);
}
return;
}
}
let prevParent: ElementNode | LinkNode | null = null;
let linkNode: LinkNode | null = null;
nodes.forEach((node) => {
const parent = node.getParent();
if (
parent === linkNode ||
parent === null ||
($isElementNode(node) && !node.isInline())
) {
return;
}
if ($isLinkNode(parent)) {
linkNode = parent;
parent.setURL(url);
if (target !== undefined) {
parent.setTarget(target);
}
if (rel !== null) {
linkNode.setRel(rel);
}
return;
}
if (!parent.is(prevParent)) {
prevParent = parent;
linkNode = $createLinkNode(url, {rel, target});
if ($isLinkNode(parent)) {
if (node.getPreviousSibling() === null) {
parent.insertBefore(linkNode);
} else {
parent.insertAfter(linkNode);
}
} else {
node.insertBefore(linkNode);
}
}
if ($isLinkNode(node)) {
if (node.is(linkNode)) {
return;
}
if (linkNode !== null) {
const children = node.getChildren();
for (let i = 0; i < children.length; i++) {
linkNode.append(children[i]);
}
}
node.remove();
return;
}
if (linkNode !== null) {
linkNode.append(node);
}
});
}
}
function $getLinkAncestor(node: LexicalNode): null | LexicalNode {
return $getAncestor(node, (ancestor) => $isLinkNode(ancestor));
}
function $getAncestor(
node: LexicalNode,
predicate: (ancestor: LexicalNode) => boolean,
): null | LexicalNode {
let parent: null | LexicalNode = node;
while (
parent !== null &&
(parent = parent.getParent()) !== null &&
!predicate(parent)
);
return parent;
} |
import 'package:flutter/material.dart';
import 'package:fluttershop/data/models/responses/address_response_model.dart';
import '../../../core/components/spaces.dart';
import '../../../core/core.dart';
import '../models/address_model.dart';
class AddressTile extends StatelessWidget {
final bool isSelected;
final Address data;
final VoidCallback onTap;
final VoidCallback onEditTap;
const AddressTile({
super.key,
required this.data,
this.isSelected = false,
required this.onTap,
required this.onEditTap,
});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onTap,
child: Container(
decoration: BoxDecoration(
borderRadius: const BorderRadius.all(Radius.circular(12.0)),
boxShadow: isSelected
? [
BoxShadow(
color: AppColors.black.withOpacity(0.1),
blurRadius: 2,
offset: const Offset(0, 2),
spreadRadius: 0,
blurStyle: BlurStyle.outer,
),
]
: null,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SpaceHeight(24.0),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
'${data.name} - ${data.phone}',
style: const TextStyle(
fontSize: 16,
),
),
),
const SpaceHeight(4.0),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Flexible(
child: Text(
data.fullAddress!,
style: const TextStyle(
fontSize: 16,
),
),
),
const SpaceWidth(14.0),
Icon(
isSelected
? Icons.radio_button_checked
: Icons.circle_outlined,
color: isSelected ? AppColors.primary : AppColors.grey,
),
],
),
),
const SpaceHeight(24.0),
if (isSelected) ...[
const Divider(color: AppColors.primary),
Center(
child: TextButton(
onPressed: onEditTap,
child: const Text('Edit'),
),
),
],
],
),
),
);
}
} |
import React from 'react';
import { useTransition } from 'react-spring';
import { IToastMessage } from '../../contexts/ToastProvider';
import { Container } from './styles';
import Toast from './Toast';
interface IToastContainerProps {
messages: IToastMessage[];
}
const ToastContainer: React.FC<IToastContainerProps> = ({ messages }) => {
const transition = useTransition(messages, {
from: { right: '-120%', opacity: 0 },
enter: { right: '0%', opacity: 1 },
leave: { right: '-120%', opacity: 0 },
});
return (
<Container>
{transition((style, item) => (
<Toast key={item.id} message={item} style={style} />
))}
</Container>
);
};
export default ToastContainer; |
import React, { useState } from "react";
import Signup from "./components/register";
import Login from "./components/login";
import OTP from "./components/otp";
import { loginApi, otpVerificationApi, signupApi } from "../../api/auth";
import { useNavigate } from "react-router-dom";
const AuthStates = {
SIGNUP: "signup",
LOGIN: "login",
OTP: "otp",
};
const AuthenticationLayer = () => {
const [authState, setAuthState] = useState(AuthStates.LOGIN);
const [loading, setLoading] = useState(false);
const navigate = useNavigate();
const onLoginClick = async (email, password) => {
try {
setLoading(true);
await loginApi(email, password);
setLoading(false);
setAuthState(AuthStates.OTP);
} catch (error) {
setLoading(false);
console.error("Login failed:", error);
}
};
const onOtpVerify = async (otp) => {
try {
setLoading(true);
await otpVerificationApi(otp);
setLoading(false);
navigate("/");
} catch (error) {
setLoading(false);
console.error("OTP verification failed:", error);
}
};
const onSignup = async (name, email, password) => {
try {
setLoading(true);
await signupApi(name, email, password);
setLoading(false);
setAuthState(AuthStates.OTP);
} catch (error) {
setLoading(false);
console.error("Signup failed:", error);
}
};
return (
<div>
{authState === AuthStates.LOGIN && (
<Login
onSwitch={() => setAuthState(AuthStates.SIGNUP)}
onLoginClick={onLoginClick}
/>
)}
{authState === AuthStates.OTP && <OTP onClick={onOtpVerify} />}
{authState === AuthStates.SIGNUP && (
<Signup
onSwitch={() => setAuthState(AuthStates.LOGIN)}
onSignUpClick={onSignup}
/>
)}
{loading && <p>Loading...</p>} {/* Display loading indicator */}
</div>
);
};
export default AuthenticationLayer; |
import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Link } from "react-router-dom";
import Chart from "chart.js/auto";
import { Doughnut, Line } from "react-chartjs-2";
import "./dashboard.css";
import { allUser } from "../../reduxToolkit/actions/userAction";
import { getAdminProducts } from "../../reduxToolkit/actions/productAction";
import { getAllOrders } from "../../reduxToolkit/actions/orderAction";
const DashBoard = () => {
const dispatch = useDispatch();
const { users } = useSelector((state) => state.allUsers);
const { products } = useSelector((state) => state.allProductAdmin);
const { orders } = useSelector((state) => state.allOrders);
let outOfStock = 0;
products?.forEach((item) => {
if (item.stock === 0) {
outOfStock++;
}
});
let totalAmount = 0;
orders &&
orders.forEach((item) => {
totalAmount += item.totalPrice;
});
const lineState = {
labels: ["InitialAmount", "Amount Earn"],
datasets: [
{
backgroundColor: "#FF6D60",
label: "TOTAL AMOUNT",
data: [0, totalAmount],
fill: false,
borderColor: "#fff",
},
],
};
const doughState = {
labels: ["Out of Stock", "InStock"],
datasets: [
{
label: 'Quanlity:',
data: [outOfStock, products.length - outOfStock], // Đưa dữ liệu vào đây, ví dụ có 12 và 18 là 2 giá trị
backgroundColor: [
'#F45050',
'#9384D1',
],
borderWidth: [0, 0]
},
],
};
const optionsDoughnut = {
maintainAspectRatio: true,
responsive: true,
plugins: {
legend: {
labels: {
color: 'white',
},
},
},
};
const optionsLine = {
responsive: true,
plugins: {
legend: {
labels: {
font: {
size: 16, // kích thước chữ
family: "Arial", // font chữ
},
color: "#fff", // màu chữ
},
},
},
scales: {
x: {
grid: {
color: "#fff", // màu của đường kẻ trên trục x
},
ticks: {
font: {
size: 14, // kích thước chữ trên trục x
family: "Arial", // font chữ trên trục x
},
color: "#fff", // màu của chữ trên trục x
},
},
y: {
grid: {
color: "#fff", // màu của đường kẻ trên trục y
},
ticks: {
font: {
size: 14, // kích thước chữ trên trục y
family: "Arial", // font chữ trên trục y
},
color: "#fff", // màu của chữ trên trục y
},
beginAtZero: true,
},
},
};
useEffect(() => {
dispatch(allUser());
dispatch(getAdminProducts());
dispatch(getAllOrders());
}, [dispatch]);
return (
<div className="dashboard">
<div className="container">
<div className="dashboard_summary">
<p>
Total Amount: <br /> {totalAmount} VND
</p>
</div>
<div className="dashboard_summary2">
<Link to="/admin/allproducts">
<p>Products</p>
<p>{products?.length}</p>
</Link>
<Link to="/admin/product/orders">
<p>Orders</p>
<p>{orders?.length}</p>
</Link>
<Link to="/admin/allusers">
<p>Users</p>
<p>{users?.length}</p>
</Link>
</div>
<div className="lineChart">
<Line data={lineState} options={optionsLine} />
</div>
<div className="doughnutChart">
<Doughnut data={doughState} options={optionsDoughnut} />
</div>
</div>
</div>
);
};
export default DashBoard; |
from flask import Flask, render_template,request,redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime as dt
#<-----------------------------------To do List App------------------------------------->
# CRUD:
# Create
# Read
# Update
# Delete
app = Flask(__name__)
# configure the SQLite database, relative to the app instance folder
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///todo.db"
db = SQLAlchemy(app)
class TodoList(db.Model):
sno = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(200), nullable=False)
desc = db.Column(db.String(500), nullable=False)
time = db.Column(db.DateTime, default=dt.utcnow)
def __repr__(self):
return f'{self.sno} - {self.title}'
#<-----------------------------------To do List App------------------------------------->
@app.route('/',methods=['GET','POST'])
def index():
if request.method == 'POST':
title = request.form['title']
desc = request.form['desc']
todo = TodoList(title=title,desc=desc)
db.session.add(todo)
db.session.commit()
allTodo = TodoList.query.all()
return render_template('index.html',alltodo=allTodo)
@app.route('/delete/<int:sno>')
def delete(sno):
todo = TodoList.query.filter_by(sno=sno).first()
db.session.delete(todo)
db.session.commit()
return redirect('/')
@app.route('/update/<int:sno>',methods=['GET','POST'])
def update(sno):
if request.method == 'POST':
title = request.form['title']
desc = request.form['desc']
todo = TodoList.query.filter_by(sno=sno).first()
todo.title = title
todo.desc = desc
db.session.add(todo)
db.session.commit()
return redirect('/')
todo = TodoList.query.filter_by(sno=sno).first()
return render_template('update.html',todo=todo)
@app.route('/show')
def show():
allTodo = TodoList.query.all()
print(allTodo)
return "This is the show page of the to do list app"
if __name__ == '__main__':
app.run(debug=True) |
import React, { useState, useRef, useContext } from "react";
import { Nav, Overlay } from "react-bootstrap";
import { AiOutlineUser } from "react-icons/ai";
import { SlArrowDown } from "react-icons/sl";
import { useNavigate } from "react-router-dom";
import useStyle from "./Style";
import Cookies from "js-cookie";
import userContext from "../../Utils/userContext";
import Avatar from "react-avatar";
const UserChoices = ({ userChoices }) => {
const classes = useStyle();
const [showChoices, setShowChoices] = useState(false);
const { activeUser } = useContext(userContext);
const ref = useRef(null);
const handleUserChoices = (event) => {
event.preventDefault();
setShowChoices(!showChoices);
};
const closeUserChoices = () => {
setShowChoices(false);
};
const navigate = useNavigate();
const logOutSystem = () => {
const cookieNames = Object.keys(Cookies.get());
cookieNames.forEach((cookieName) => {
Cookies.remove(cookieName, { path: "/" });
});
localStorage.clear();
navigate("/log-in");
window.location.reload();
};
return (
<Nav.Item>
<Nav.Link
className="d-flex align-items-center"
ref={ref}
onClick={handleUserChoices}
>
{activeUser?.image ? (
<Avatar round src={activeUser.image} size="40px" />
) : (
<div className={classes.iconContainer}>
<AiOutlineUser size={"30px"} color="#576871" />
</div>
)}
<SlArrowDown
size={20}
className={`ml-2 ${classes.hoveringColor} ${
showChoices ? classes.clickedBtn : ""
}`}
/>
</Nav.Link>
<Overlay
show={showChoices}
containerPadding={20}
target={ref}
placement="bottom-start"
rootClose={true}
onHide={closeUserChoices}
>
<div className={classes.userChoicesContainer}>
{userChoices.map((userChoice, index) => (
<div key={index} className={classes.choiceItem}>
<duv
onClick={() => {
if (userChoice.title === "Logout") {
closeUserChoices();
logOutSystem();
} else {
closeUserChoices();
navigate(userChoice.link);
}
}}
className={`${classes.choiceLink}`}
>
{userChoice.title}
</duv>
{userChoice.id !== userChoices[userChoices.length - 1].id && (
<hr className="m-2"></hr>
)}
</div>
))}
</div>
</Overlay>
</Nav.Item>
);
};
export default UserChoices; |
import { useEffect, useState } from "react"
import axiosClient from "../axios-client"
import { Link } from "react-router-dom"
import { useStateContext } from "../contexts/ContextProvider"
export default function Users() {
const [users, setUsers] = useState([])
const [loading, setLoading] = useState(false)
const {setNotification} = useStateContext()
useEffect(()=>{
getUsers();
},[])
const onDelete = (u)=>{
if (!window.confirm('Are you sure you want to delete this user?')){
return
}
axiosClient.delete(`/users/${u.id}`)
.then(()=> {
setNotification("User was successfully deleted")
getUsers()
})
}
const getUsers = () =>{
setLoading(true)
axiosClient.get('/users')
.then(({data})=>{
setLoading(false)
setUsers(data.data);
})
.catch(()=>{
setLoading(false);
})
}
return(
<div>
<div style={{display: 'flex', justifyContent:'space-between', alignItems: 'center'}}>
<h2>Users</h2>
<Link to="/users/new" className="btn-add">Add new</Link>
</div>
<div className="card animated fadeInDown">
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Create Date</th>
<th>Actions</th>
</tr>
</thead>
{loading &&
<tbody>
<tr>
<td colSpan="5" className="text-center">Loading ...</td>
</tr>
</tbody>}
<tbody>
{users.map(u => (
<tr key={u.id}>
<td>{u.id}</td>
<td>{u.name}</td>
<td>{u.email}</td>
<td>{u.created_at}</td>
<td>
<Link to={'/users/'+u.id} className="btn-edit">Edit</Link>
<button onClick={ev => onDelete(u)} className="btn-delete">Delete</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)
} |
// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'dart:convert';
class RouteModel {
final String startPoint;
final String endPoint;
final DateTime date;
RouteModel({
required this.startPoint,
required this.endPoint,
required this.date,
});
RouteModel copyWith({
String? startPoint,
String? endPoint,
DateTime? date,
}) {
return RouteModel(
startPoint: startPoint ?? this.startPoint,
endPoint: endPoint ?? this.endPoint,
date: date ?? this.date,
);
}
Map<String, dynamic> toMap() {
return <String, dynamic>{
'startPoint': startPoint,
'endPoint': endPoint,
'date': date.millisecondsSinceEpoch,
};
}
factory RouteModel.fromMap(Map<String, dynamic> map) {
return RouteModel(
startPoint: map['startPoint'] as String,
endPoint: map['endPoint'] as String,
date: DateTime.fromMillisecondsSinceEpoch(map['date'] as int),
);
}
String toJson() => json.encode(toMap());
factory RouteModel.fromJson(String source) =>
RouteModel.fromMap(json.decode(source) as Map<String, dynamic>);
@override
String toString() =>
'RouteModel(startPoint: $startPoint, endPoint: $endPoint, date: $date)';
@override
bool operator ==(covariant RouteModel other) {
if (identical(this, other)) return true;
return other.startPoint == startPoint &&
other.endPoint == endPoint &&
other.date == date;
}
@override
int get hashCode => startPoint.hashCode ^ endPoint.hashCode ^ date.hashCode;
} |
<template>
<div class="goodsinfo-container">
<transition
v-on:before-enter="beforeEnter"
v-on:enter="enter"
v-on:after-enter="afterEnter">
<div class="ball" v-show="ballFrag" ref="ball"></div>
</transition>
<!--卡片式布局-->
<div class="mui-card first">
<div class="mui-card-content">
<div class="mui-card-content-inner">
<Swipe :lubotuList="lubotuList" isfull="false"></Swipe>
</div>
</div>
</div>
<div class="mui-card">
<div class="mui-card-header">{{goods.title}}</div>
<div class="mui-card-content">
<div class="mui-card-content-inner">
<p class="price">
市场价:
<del>¥{{goods.market_price}}</del>
 , 销售价:<span class="now_price">¥{{goods.sell_price}}</span>
</p>
<p>
购买数量:
<GoodsInfosNumBox @getcount="getSelectCount" :maxNum="goods.stock_quantity"></GoodsInfosNumBox>
</p>
<p>
<mt-button type="primary" size="small">立即购买</mt-button>
<mt-button type="danger" size="small" @click="addShopCart"> 加入购物车</mt-button>
</p>
</div>
</div>
</div>
<div class="mui-card">
<div class="mui-card-header">商品参数</div>
<div class="mui-card-content">
<div class="mui-card-content-inner">
<p>商品货号:{{goods.goods_no}}</p>
<p>库存情况:{{goods.stock_quantity}}件</p>
<p>上架时间:{{goods.add_time|dateFormat}}</p>
</div>
</div>
<div class="mui-card-footer">
<mt-button size="large" type="primary" plain @click="goDesc(id)">图文介绍</mt-button>
<mt-button size="large" type="danger" plain @click="goComment(id)">商品评论</mt-button>
</div>
</div>
</div>
</template>
<script>
import Swipe from '../subcomponents/Swipe'
import {reqluobotu02, reqGoodsInfos} from '../../api/index'
import GoodsInfosNumBox from '../subcomponents/GoodsInfo-Numbox'
export default {
data() {
return {
lubotuList: [],
id: this.$route.params.id,
goods: Object,
ballFrag: false,
selectCount: 1
}
},
components: {
Swipe,
GoodsInfosNumBox
},
created() {
this.getlunbotu(),
this.getGoodsInfos()
},
methods: {
async getlunbotu() {
const result = await reqluobotu02()
if (result.code === 0) {
this.lubotuList = result.data
}
},
async getGoodsInfos() {
const result = await reqGoodsInfos(this.id)
if (result.code === 0) {
this.goods = result.data
}
},
//使用编程导航的方式 跳转到商品描述 和 评论页面
goDesc(id) {
this.$router.push({name: "goodsdesc", params: {id}})
},
goComment(id) {
this.$router.push({name: "goodscomment", params: {id}})
},
addShopCart() {
this.ballFrag = !this.ballFrag
//创建一个商品信息
const goods = {
id: this.id,
count: this.selectCount,
price: this.goods.sell_price,
selected: true
}
//调用
this.$store.commit("addToCar", goods)
},
beforeEnter: function (el) {
el.style.transform = "translate(0px, 0px)"
},
afterEnter(el) {
this.ballFrag = !this.ballFrag
},
enter(el, done) {
el.offsetWidth;
const ballPosition = this.$refs.ball.getBoundingClientRect();
const badgePosition = document.getElementById('badge').getBoundingClientRect();
const xDist = badgePosition.left - ballPosition.left;
const yDist = badgePosition.top - ballPosition.top;
el.style.transform = `translate(${xDist}px,${yDist}px)`;
el.style.transition = 'all 1s ease';
done()
},
getSelectCount(count) {
this.selectCount = count
console.log("父组件拿到的值:" + count)
}
}
}
</script>
<style>
/*.goodsinfo-container {
background-color: #eee
overflow hidden
.now_price {
color red
font-size 16px
font-weight bold
}
.mui-card-footer {
display block
button {
margin 10px 0px
}
}
.ball {
width: 15px
height: 15px
background-color: red
border-radius 50%
position absolute
z-index 199
left: 154px
top: 409px
}
}
*/
.goodsinfo-container {
background-color: #eee;
overflow: hidden;
}
.goodsinfo-container .now_price {
color: red;
font-size: 16px;
font-weight: bold
}
.goodsinfo-container .mui-card-footer {
display: block;
}
.goodsinfo-container .mui-card-footer button {
margin: 10px 0px;
}
.goodsinfo-container .ball {
width: 15px;
height: 15px;
background-color: red;
border-radius: 50%;
position: absolute;
z-index: 199;
left: 154px;
top: 409px;
}
</style> |
<?php
namespace ImageOptimization\Modules\Optimization\Components;
use ImageOptimization\Classes\Async_Operation\{
Async_Operation,
Async_Operation_Hook,
Async_Operation_Queue,
};
use ImageOptimization\Classes\Image\{
Image_Meta,
Image_Optimization_Error_Type,
Image_Status
};
use ImageOptimization\Classes\Logger;
use ImageOptimization\Modules\Oauth\Classes\Exceptions\Quota_Exceeded_Error;
use ImageOptimization\Modules\Oauth\Components\Connect;
use ImageOptimization\Modules\Optimization\Classes\Exceptions\Image_File_Already_Exists_Error;
use ImageOptimization\Modules\Optimization\Classes\Optimize_Image;
use ImageOptimization\Modules\Settings\Classes\Settings;
use Throwable;
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
class Upload_Optimization {
public function handle_upload( int $attachment_id ) {
if ( ! Settings::get( Settings::OPTIMIZE_ON_UPLOAD_OPTION_NAME ) ) {
return;
}
if ( ! Connect::is_connected() || ! Connect::is_activated() ) {
return;
}
$attachment_post = get_post( $attachment_id );
if ( ! wp_attachment_is_image( $attachment_post ) ) {
return;
}
$meta = new Image_Meta( $attachment_id );
try {
$meta
->set_status( Image_Status::OPTIMIZATION_IN_PROGRESS )
->save();
Async_Operation::create(
Async_Operation_Hook::OPTIMIZE_ON_UPLOAD,
[ 'attachment_id' => $attachment_id ],
Async_Operation_Queue::OPTIMIZE
);
} catch ( Throwable $t ) {
$meta
->set_status( Image_Status::OPTIMIZATION_FAILED )
->save();
}
}
/** @async */
public function optimize_image_on_upload( int $image_id ) {
try {
$oi = new Optimize_Image(
$image_id,
'upload',
);
$oi->optimize();
} catch ( Quota_Exceeded_Error $qe ) {
( new Image_Meta( $image_id ) )
->set_status( Image_Status::OPTIMIZATION_FAILED )
->set_error_type( Image_Optimization_Error_Type::QUOTA_EXCEEDED )
->save();
} catch ( Image_File_Already_Exists_Error $fe ) {
( new Image_Meta( $image_id ) )
->set_status( Image_Status::OPTIMIZATION_FAILED )
->set_error_type( Image_Optimization_Error_Type::FILE_ALREADY_EXISTS )
->save();
} catch ( Throwable $t ) {
Logger::log( Logger::LEVEL_ERROR, 'Optimization error. Reason: ' . $t->getMessage() );
( new Image_Meta( $image_id ) )
->set_status( Image_Status::OPTIMIZATION_FAILED )
->set_error_type( Image_Optimization_Error_Type::GENERIC )
->save();
}
}
public function __construct() {
add_action( 'add_attachment', [ $this, 'handle_upload' ] );
add_action( Async_Operation_Hook::OPTIMIZE_ON_UPLOAD, [ $this, 'optimize_image_on_upload' ] );
}
} |
import { memo, useCallback } from 'react';
import { classNames } from 'shared/libs/class-names';
import { Button } from 'shared/ui/button';
import CopyIcon from 'shared/assets/icons/copy.svg';
import cls from './article-code-block.module.scss';
import { ArticleBlockCode } from '../../../model/types/article';
import { Icon } from 'shared/ui/icon';
interface Props {
className?: string;
block: ArticleBlockCode;
}
const ArticleCodeBlock = memo((props: Props) => {
const { className, block } = props;
const handleCopy = useCallback(() => {
navigator.clipboard.writeText(block.content.join('\n'));
}, [block]);
return (
<pre className={classNames(cls.articleCodeBlock, className)}>
<Button className={cls.copyButton} onClick={handleCopy}>
<Icon Svg={CopyIcon} />
</Button>
<code>{block.content.join('\n')}</code>
</pre>
);
});
export { ArticleCodeBlock }; |
const express = require('express');
const app = express();
const mysql = require("mysql");
const cors = require("cors");
const bcrypt = require("bcrypt");
const saltRounds = 10;
const {calcularHorasTrabalhadasEsteMes, pegarSalarioBase, pegarHorasExtras, calcularDescontos} = require("./funcoes");
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "1234",
database: "dbpointwork"
})
let horaAtual = new Date();
let dia = horaAtual.getDate();
let mes = horaAtual.getMonth() + 1;
let ano = horaAtual.getFullYear();
let dataFormatada = `${ano}-${mes < 10 ? '0' + mes : mes}-${dia < 10 ? '0' + dia : dia}`;
app.use(express.json());
app.use(cors());
app.post("/cadastrar-cargo", (req, res) => {
const cargo = req.body.cargo;
const salario_base = req.body.salario_base;
const carga_horaria = req.body.carga_horaria;
db.query("SELECT * FROM tbcargo WHERE cargo = ?", [cargo],
(err, result) => {
if (err) {
res.send(err);
}
if (result.length == 0) {
db.query(
'INSERT INTO tbcargo (cargo, salario_base, carga_horaria) VALUES (?, ?, ?)',
[cargo, salario_base, carga_horaria],
(err, result) => {
if (err) {
res.send(err);
}
res.send({ msg: "Cargo " + cargo + " cadastrado com sucesso" });
}
);
} else {
res.send({ msg: "Cargo " + cargo + " já cadastrado anteriormente" })
}
});
});
app.post("/registrar", (req, res) => {
const email = req.body.email;
const senha = req.body.senha;
const nome = req.body.nome;
const cpf = req.body.cpf;
const idCargo = req.body.cargo;
const dataAdimissao = req.body.admissao;
const dataDemissao = req.body.demissao;
db.query("SELECT * FROM tbfuncionario WHERE email = ?", [email],
(err, result) => {
if (err) {
res.send(err);
}
if (result.length == 0) {
bcrypt.hash(senha, saltRounds, (err, hash) => {
db.query(
"INSERT INTO tbfuncionario (nome, email, senha, cpf, id_cargo, data_admissao, data_demissao) VALUES (?, ?, ?, ?, ?, ?, ?)",
[nome, email, hash, cpf, idCargo, dataAdimissao, dataDemissao],
(err, result) => {
if (err) {
res.send(err);
}
res.send({ msg: "Cadastrado com sucesso" });
}
);
});
} else {
res.send({ msg: "Usuário já cadastrado" });
}
});
})
app.post('/login', (req, res) => {
const email = req.body.email;
const senha = req.body.senha;
db.query("SELECT * FROM tbfuncionario WHERE email = ?", [email],
(err, result) => {
if (err) {
res.send(err);
}
if (result.length > 0) {
bcrypt.compare(senha, result[0].senha, (err, result) => {
if (err) {
res.send(err);
}
if (result) {
res.send({ msg: "Usuário logado com sucesso" })
} else {
res.send({ msg: "Senha incorreta" })
}
});
} else {
res.send({ msg: "Usuário não encontrado" })
}
});
});
app.get('/funcionarios', (req, res) => {
db.query("SELECT id, nome, email, cpf FROM tbfuncionario", (err, result) => {
if (err) {
console.error("erro aqui", err);
res.send(err);
} else {
res.send(result);
}
});
});
app.put("/alterar-funcionario/:id", (req, res) => {
const idFuncionario = req.params.id;
const novoNome = req.body.novoNome;
const novoCpf = req.body.novoCpf;
const novoEmail = req.body.novoEmail;
const sqlParts = [];
const sqlValues = [];
if (novoNome) {
sqlParts.push("nome = ?");
sqlValues.push(novoNome);
}
if (novoEmail) {
sqlParts.push("email = ?");
sqlValues.push(novoEmail);
}
if (novoCpf) {
sqlParts.push("cpf = ?");
sqlValues.push(novoCpf);
}
if (sqlParts.length === 0) {
return res.status(400).send({ msg: "Nenhum dado para atualizar" });
}
const sqlQuery = `UPDATE tbfuncionario SET ${sqlParts.join(", ")} WHERE id = ?`;
sqlValues.push(idFuncionario);
db.query(sqlQuery, sqlValues, (err, result) => {
if (err) {
res.send(err);
} else {
res.send({ msg: "Funcionário alterado com sucesso" });
}
});
});
app.delete("/funcionarios/:id", (req, res) => {
const idFuncionario = req.params.id;
db.query(
"DELETE FROM tbfuncionario WHERE id = ?",
[idFuncionario],
(err, result) => {
if (err) {
res.send(err);
} else {
res.send({ msg: "Funcionário deletado com sucesso" });
}
}
);
});
app.post('/cartao-ponto/:id', (req, res) => {
const idFuncionario = req.params.id;
// Verificar se o funcionário já registrou o ponto de entrada hoje
db.query(
'SELECT * FROM tbregistro_ponto WHERE id_funcionario = ? AND DATE(hora_entrada) = CURDATE()',
[idFuncionario, horaAtual],
(err, result) => {
if (err) {
console.error('Erro ao consultar registro de entrada:', err);
return res.status(500).json({ msg: 'Erro no servidor verificação entrada' });
}
if (result.length === 0) {
// O funcionário ainda não registrou o ponto hoje, então registramos a entrada
db.query(
'INSERT INTO tbregistro_ponto (id_funcionario, hora_entrada, data) VALUES (?, ?, CURDATE())',
[idFuncionario, horaAtual],
(err, result) => {
if (err) {
return res.status(500).json({ msg: 'Erro no servidor registro entrada' });
}
res.json({ msg: 'Ponto de entrada registrado com sucesso' });
}
);
} else if (result.length === 1 && !result[0].hora_saida_intervalo) {
// O funcionário já registrou a entrada hoje, mas ainda não registrou a saída para o intervalo
db.query(
'UPDATE tbregistro_ponto SET hora_saida_intervalo = ? WHERE id_funcionario = ?',
[horaAtual, idFuncionario],
(err, result) => {
if (err) {
console.error('Erro ao atualizar ponto de saída do intervalo:', err);
return res.status(500).json({ msg: 'Erro no servidor verificação saida do intervalo' });
}
res.json({ msg: 'Ponto de saída do intervalo registrado com sucesso' });
}
);
} else if (result.length === 1 && !result[0].hora_entrada_intervalo) {
// O funcionário já registrou a saida para o intervalo, mas ainda não registrou a entrada do intervalo
db.query(
'UPDATE tbregistro_ponto SET hora_entrada_intervalo = ? WHERE id_funcionario = ?',
[horaAtual, idFuncionario],
(err, result) => {
if (err) {
console.error('Erro ao atualizar ponto de entrada do intervalo', err);
return res.status(500).json({ msg: 'Erro no servidor verificação entrada do intervalo' });
}
res.json({ msg: 'Ponto de entrada do intevalo registrado com sucesso' });
}
);
} else if (result.length === 1 && !result[0].hora_saida) {
//O funcionário já registrou a entrada do intervalo, mas não resgistrou a saída
db.query(
'UPDATE tbregistro_ponto SET hora_saida = ? WHERE id_funcionario = ?',
[horaAtual, idFuncionario],
(err, result) => {
if (err) {
console.error('Erro ao atualizar ponto de saida', err);
return res.status(500).json({ msg: 'Erro no servidor verificação saída' });
}
res.json({ msg: 'Ponto de saída registrado com sucesso' });
}
);
} else {
// O funcionário já registrou a entrada e saída hoje
res.status(400).json({ msg: 'Você já registrou o ponto de entrada e saída hoje' });
}
}
);
});
// Obter Registros do dia
app.get("/cartao-ponto/:id", (req, res) => {
const idFuncionario = req.params.id
db.query(
'SELECT hora_entrada, hora_saida_intervalo, hora_entrada_intervalo, hora_saida FROM tbregistro_ponto WHERE id_funcionario = ?',
[idFuncionario], (err, result) => {
if (err) {
console.log("Erro ao obter registros de ponto", err);
res.send(err);
} else {
res.send(result);
}
}
);
});
app.post("/registrar-avisos/:id", (req, res) => {
const idFuncionario = req.params.id;
const tituloAviso = req.body.titulo;
const conteudoAviso = req.body.conteudo;
if (idFuncionario || tituloAviso || conteudoAviso != null) {
db.query(
'INSERT INTO tbavisos (titulo, conteudo, data_criacao, id_funcionario) VALUES (?, ?, ?, ?)',
[tituloAviso, conteudoAviso, dataFormatada, idFuncionario],
(err, result) => {
if (err) {
console.error("erro ao inserir aviso", err);
res.send(err);
} else {
res.send({ msg: "Aviso registrado" })
}
}
);
} else {
res.send({ msg: "Todos os campos devem ser preenchidos" })
}
});
app.get("/avisos", (req, res) => {
db.query(
'SELECT id, titulo, conteudo, data_criacao FROM tbavisos',
(err, result) => {
if (err) {
res.send(err);
} else {
res.send(result);
}
}
);
});
app.delete('/avisos/delete/:id', (req, res) => {
const idAviso = req.params.id;
db.query(
'DELETE FROM tbavisos WHERE id = ?',
[idAviso],
(err, result) => {
if (err) {
res.send(err);
} else {
res.send({ msg: 'Aviso deletado' });
}
}
);
});
app.delete('/avisos/deletar-todos', (req, res) => {
db.query(
'DELETE FROM tbavisos',
(err, result) => {
if (err) {
res.send(err);
} else {
res.send({ msg: 'Todos os avisos foram deletados' });
}
}
);
});
app.post('/registroHolerite/:id', async (req, res) => {
const idFuncionario = req.params.id;
const resultadoSalarioBase = await pegarSalarioBase(idFuncionario);
const valorHorasExtras = await pegarHorasExtras(idFuncionario, resultadoSalarioBase.salario_base, resultadoSalarioBase.carga_horaria);
const descontos = await calcularDescontos(resultadoSalarioBase.salario_base);
const valorTotal = resultadoSalarioBase.salario_base + valorHorasExtras - descontos;
valorTotalFixado = valorTotal.toFixed(2);
db.query(
'SELECT DISTINCT mes FROM tbhorasextras WHERE id_funcionario = ? AND mes = MONTH(CURDATE())',
[idFuncionario],
(err, result) => {
if (err) {
console.error(err);
res.send(err);
} else if (result.length > 0) {
// Iterar sobre cada registro único de mês encontrado
result.forEach((row) => {
const mes = row.mes; // Valor do mês recuperado da tabela
const dataEmissao = `${mes}`;
// Inserir um registro na tabela tbholerite para cada mês
db.query(
'INSERT INTO tbholerite (id_funcionario, mes_emissao, valor, desconto) VALUES (?, ?, ?, ?)',
[idFuncionario, dataEmissao, valorTotalFixado, descontos],
(err, result) => {
if (err) {
console.error("Erro ao adicionar valor holerite", err);
res.send(err);
}
}
);
});
res.send({ msg: 'Valores registrados no holerite com sucesso' });
} else {
res.send({ msg: 'Não foi possível encontrar o mês na tabela de horas extras' });
}
}
);
});
app.get('/holerite/:id', (req, res) => {
const idFuncionario = req.params.id;
db.query(
'SELECT tbholerite.valor, tbfuncionario.nome, tbcargo.salario_base, tbcargo.carga_horaria, tbhorasextras.quantidade_horas_extras, tbholerite.mes_emissao, tbholerite.desconto ' +
'FROM tbholerite ' +
'INNER JOIN tbfuncionario ON tbholerite.id_funcionario = tbfuncionario.id ' +
'INNER JOIN tbcargo ON tbfuncionario.id_cargo = tbcargo.id ' +
'LEFT JOIN tbhorasextras ON tbholerite.id_funcionario = tbhorasextras.id_funcionario ' +
'WHERE tbholerite.id_funcionario = ?',
[idFuncionario],
(err, result) => {
if (err) {
console.error(err);
} else {
res.send(result);
}
}
);
});
async function main() {
app.listen(3001, () => {
console.log("rodando")
});
await calcularHorasTrabalhadasEsteMes(7);
}
main(); |
namespace Kontur.Cache.Bench
{
using Kontur.Cache.Bench.Builders;
using NDesk.Options;
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
public class CacheBenchOptions
{
public CacheBenchOptions()
{
CacheSize = 100;
Seed = 123;
MaxKeyLength = 20;
CleanInterval = TimeSpan.FromSeconds(5);
ThreadCount = 8;
Proportion = 0.5;
CacheType = "concurrent";
}
public int MaxKeyLength { get; set; }
public string CacheType { get; set; }
public int ThreadCount { get; set; }
public int CacheSize { get; set; }
public double Proportion { get; set; }
public int Seed { get; set; }
public TimeSpan CleanInterval { get; set; }
}
class Program
{
private static CacheBench bench;
private static Timer timer;
private static Stopwatch stopwatch = new Stopwatch();
private static long lastTime = 0;
private static long lastStatistics;
public static int Main(string[] args)
{
var showHelp = false;
var options = new CacheBenchOptions();
var optionSet = new OptionSet();
optionSet.Add("type=", "Cache type", x => options.CacheType = x);
optionSet.Add("threadCount=", "Thread count", x => options.ThreadCount = int.Parse(x));
optionSet.Add("h|help", "show help", x => showHelp = true);
optionSet.Add("cacheSize=", "Cache size", x => options.CacheSize = int.Parse(x));
optionSet.Add("proportion=", "Proportion", x => options.Proportion = double.Parse(x));
optionSet.Add("seed=", "Random seed", x => options.Seed = int.Parse(x));
optionSet.Add("cleanInterval=", "(sec)", x => options.CleanInterval = TimeSpan.FromSeconds(int.Parse(x)));
try
{
optionSet.Parse(args);
if (!showHelp)
{
if (string.IsNullOrEmpty(options.CacheType))
{
throw new OptionException("Missing required value for option \"type\"", "type");
}
}
}
catch (OptionException e)
{
Console.Write("CacheBench: ");
Console.WriteLine(e.Message);
Console.WriteLine("Try 'CacheBench --help' for more information.");
return -1;
}
if (showHelp)
{
ShowHelp(optionSet);
return 0;
}
Execute(options);
return 0;
}
internal static CacheSample<string> CreateSample(CacheBenchOptions options)
{
ICacheSampleBuilder<string> sampleBuilder = null;
switch (options.CacheType)
{
case "concurrent":
sampleBuilder = new ConcurrentCacheSampleBuilder<string>(options.CacheSize, options.Seed, options.MaxKeyLength, options.CleanInterval);
break;
case null:
case "simple":
sampleBuilder = new CacheSampleBuilder<string>(options.CacheSize, options.Seed, options.MaxKeyLength, options.CleanInterval);
break;
default:
throw new ApplicationException(string.Format("Unknown cache type \"{0}\"", options.CacheType));
}
return sampleBuilder.Build();
}
internal static void Execute(CacheBenchOptions options)
{
var cacheSample = CreateSample(options);
bench = new CacheBench(options.ThreadCount, options.Seed, options.Proportion);
stopwatch.Start();
timer = new Timer(OnTimer);
timer.Change(1000, 1000);
bench.Run(cacheSample);
Console.WriteLine("Press any key to exit");
Console.Read();
stopwatch.Stop();
bench.Stop();
timer.Dispose();
// вывести затраченное время, кол-во операций, средняя скорость
Console.WriteLine("Time " + stopwatch.ElapsedMilliseconds);
var allOperation = bench.GetStatistics().Sum();
Console.WriteLine("Operations " + allOperation);
Console.WriteLine("Average speed " + (allOperation / stopwatch.ElapsedMilliseconds));
Console.ReadLine();
Console.ReadLine();
}
internal static void OnTimer(object state)
{
var operations = bench.GetStatistics().Sum();
var elapsedTime = stopwatch.ElapsedMilliseconds;
Console.WriteLine("{0} operations per second", (operations - lastStatistics) / (elapsedTime - lastTime));
lastTime = elapsedTime;
lastStatistics = operations;
}
private static void ShowHelp(OptionSet optionSet)
{
Console.WriteLine("Usage: CacheBench [OPTIONS]+");
Console.WriteLine();
Console.WriteLine("Options:");
optionSet.WriteOptionDescriptions(Console.Out);
}
}
} |
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { MenuItem } from 'primeng/api';
import { LayoutService } from "./service/app.layout.service";
import { Subscription } from 'rxjs';
import { StorageService } from '../_services/storage.service';
import { AuthService } from '../_services/auth.service';
import { EventBusService } from '../_shared/event-bus.service';
@Component({
selector: 'app-topbar',
templateUrl: './app.topbar.component.html'
})
export class AppTopBarComponent implements OnInit {
items!: MenuItem[];
private roles: string[] = [];
isLoggedIn = false;
showAdminBoard = false;
showModeratorBoard = false;
username?: string;
eventBusSub?: Subscription;
@ViewChild('menubutton') menuButton!: ElementRef;
@ViewChild('topbarmenubutton') topbarMenuButton!: ElementRef;
@ViewChild('topbarmenu') menu!: ElementRef;
constructor(public layoutService: LayoutService, private storageService: StorageService,
private authService: AuthService,
private eventBusService: EventBusService) { }
ngOnInit(): void {
this.isLoggedIn = this.storageService.isLoggedIn();
if (this.isLoggedIn) {
const user = this.storageService.getUser();
this.roles = user.roles;
this.showAdminBoard = this.roles.includes('ROLE_ADMIN');
this.showModeratorBoard = this.roles.includes('ROLE_MODERATOR');
this.username = user.username;
}
this.eventBusSub = this.eventBusService.on('logout', () => {
this.logout();
});
}
logout(): void {
this.authService.logout().subscribe({
next: res => {
console.log(res);
this.storageService.clean();
window.location.reload();
},
error: err => {
console.log(err);
}
});
}
} |
import React, {useState, useEffect} from "react";
import "./styles.css";
import axios from "axios";
import PokeCard from "./components/PokeCard/PokeCard";
const App = () => {
const [pokeList, setPokelist] = useState([])
const [pokeName, setPokeName] = useState("")
const getPokemon = () => {
axios
.get("https://pokeapi.co/api/v2/pokemon/?limit=151")
.then(response => setPokelist (response.data.results))
.catch(err => console.log(err));
};
useEffect(()=>{getPokemon()}, [])
const changePokeName = (event) => {
setPokeName(event.target.value)
};
return (
<div className="App">
{}
<select onChange={changePokeName}>
<option value={""}>Nenhum</option>
{}
{pokeList.map(pokemon => {
return (
<option key={pokemon.name} value={pokemon.name}>
{pokemon.name}
</option>
);
})}
</select>
{}
{pokeName && <PokeCard pokeName={pokeName} />}
</div>
);
}
export default App |
# Go 功能框架
> 原文:<https://medium.com/google-cloud/go-functions-framework-120ace237fe2?source=collection_archive---------0----------------------->

谷歌云功能+ Go(上田拓也的 Logo—[src](https://github.com/golang-samples/gopher-vector))
在本帖中,您将了解开源 Go Functions 框架,该框架使您能够在您的计算机上开发 Golang Google Cloud 函数,并将它们部署到云中。
那么,为什么 Go Functions 框架如此重要呢?嗯,它使…
* 💻**Go 中谷歌云功能的本地测试**
* 🔢**Google Cloud 上应用代码的透明版本管理**
* 🌐**一次编写,随处运行:**云功能,云运行,其他云
就我个人而言,我非常喜欢如何轻松地使用`localhost`来测试我的功能。
## 设置您的环境
在我们开始之前,让我们首先确保我们运行在相同的环境中。使用以下命令打印您的 go 版本:
```
go version
```
输出应该是 Go 1.11 或者更高。如果没有,通过卸载并重新安装 Go 来更新 Go:[https://golang.org/dl/](https://golang.org/dl/)
然后,让我们为名为`hello`的函数创建一个新目录:
```
mkdir -p hello/cmd
cd hello
```
创建 Go 模块:
```
go mod init example.com/hello
```
用以下内容创建一个`function.go`文件(任意包名):
一个简单的“你好”包裹。
为我们的`main`包创建一个包含文件`cmd/main.go`的文件夹`cmd`,内容如下:
我们的`main program that starts the Function Framework.`
这个文件使用 Go Functions 框架来启动我们的函数。
## 测试
使用以下命令在本地测试您的函数:
```
go run cmd/main.go
```
您的 Google Cloud 功能现已在本地运行。你可以卷曲你的函数来调用你的函数:
```
curl localhost:8080
```
您将看到输出:
```
Hello, Functions Framework!
```
厉害!
## 部署到 Google 云功能
要部署到 Google Cloud 功能,请运行以下命令:
```
gcloud functions deploy HelloWorld --runtime go111 --trigger-http
```
大约 2 分钟后,您将看到如下所示的 URL:
> https://us-central 1-my-project . cloud functions . net/hello world
您可以通过访问您的 URL 来调用该函数。
从命令行,这个脚本将获得 URL 和`curl`您的函数:
```
curl $(gcloud functions describe HelloWorld --format 'value(httpsTrigger.url)')
```
缺德!😄
您刚刚在计算机上测试了 Go 功能,然后部署到理论上可以扩展到每 100 秒 100,000,000 个请求的 Google Cloud 上([🔗](https://cloud.google.com/functions/quotas))。
如果你想跟踪更新,或者了解更多,请查看 GitHub repo:[https://GitHub . com/Google cloud platform/functions-framework-go](https://github.com/GoogleCloudPlatform/functions-framework-go)
## 感谢阅读
你可能也会对这篇博文和视频感兴趣:
* [🖊️jbd 为 Go 介绍谷歌云功能](/google-cloud/google-cloud-functions-for-go-57e4af9b10da)
* [📹Eno 和 Angela(+可爱的地鼠)介绍 Go 对函数的支持](https://www.youtube.com/watch?v=RbnyUpVRq_4) |
[circle-ds](README.md) / Exports
# circle-ds
## Table of contents
### Classes
- [CircularArrayList](classes/CircularArrayList.md)
- [CircularDeque](classes/CircularDeque.md)
- [CircularDoublyLinkedList](classes/CircularDoublyLinkedList.md)
- [CircularLinkedDeque](classes/CircularLinkedDeque.md)
- [CircularLinkedList](classes/CircularLinkedList.md)
- [CircularLinkedQueue](classes/CircularLinkedQueue.md)
- [CircularLinkedStack](classes/CircularLinkedStack.md)
- [CircularMap](classes/CircularMap.md)
- [CircularQueue](classes/CircularQueue.md)
- [CircularSet](classes/CircularSet.md)
- [CircularSkipList](classes/CircularSkipList.md)
- [CircularStack](classes/CircularStack.md)
### Interfaces
- [Bounded](interfaces/Bounded.md)
- [CircularSkipListConfig](interfaces/CircularSkipListConfig.md)
- [Collection](interfaces/Collection.md)
- [Deque](interfaces/Deque.md)
- [List](interfaces/List.md)
- [Queue](interfaces/Queue.md)
- [SkipList](interfaces/SkipList.md)
- [Stack](interfaces/Stack.md)
### Variables
- [BoundedEvent](modules.md#boundedevent)
## Variables
### BoundedEvent
• `Const` **BoundedEvent**: `Object`
An enumeration of event types supported by [Bounded](interfaces/Bounded.md) collections.
This object defines a set of constants representing event names that can
be emitted by instances of collections implementing the [Bounded](interfaces/Bounded.md) interface.
These events signify specific actions or changes in the state of the collection.
Defined events include:
- `Overflow`: Indicates that the collection has reached its capacity, and
as a result, one or more elements have been removed to accommodate new elements.
This event is triggered during operations that add elements to the collection when
it exceeds its capacity, or when capacity is updated below the collection's current
size. Listeners attached to this event will receive an array of elements that were
removed due to the overflow. Removed elements may be sent across 1 or more event
instances.
This object is marked as `const` to ensure that its properties are read-only,
preventing modification of event names which could lead to inconsistencies in
event handling across the application.
#### Type declaration
| Name | Type |
| :------ | :------ |
| `Overflow` | ``"overflow"`` |
#### Defined in
[types/boundedEvent.ts:21](https://github.com/havelessbemore/circle-ds/blob/3ecd468/src/types/boundedEvent.ts#L21) |
//#define NonArray
//#define StringArray
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise04 {
class Program {
static void Main(string[] args) {
Stopwatch sw = new Stopwatch();
sw.Start();
#if NonArray
var line = "Novelist=谷崎潤一郎;BestWork=春琴抄;Born=1886";
printBook(line);
/*
var words = line.Split(';');
foreach (var item in words) {
var pair = item.Split('=');
Console.WriteLine("{0} : {1}", ToJapanese( pair[0]), pair[1]);
}
*/
#elif StringArray
var lines = new string[] {
"Novelist=谷崎潤一郎;BestWork=春琴抄;Born=1886",
"Novelist=夏目漱石;BestWork=坊ちゃん;Born=1887",
"Novelist=太宰治;BestWork=人間失格;Born=1909",
"Novelist=宮沢賢治;BestWork=銀河鉄道の夜;Born=1896",
"Novelist=谷崎潤一郎;BestWork=春琴抄;Born=1886",
"Novelist=夏目漱石;BestWork=坊ちゃん;Born=1887",
"Novelist=太宰治;BestWork=人間失格;Born=1909",
"Novelist=宮沢賢治;BestWork=銀河鉄道の夜;Born=1896",
"Novelist=谷崎潤一郎;BestWork=春琴抄;Born=1886",
"Novelist=夏目漱石;BestWork=坊ちゃん;Born=1887",
"Novelist=太宰治;BestWork=人間失格;Born=1909",
"Novelist=宮沢賢治;BestWork=銀河鉄道の夜;Born=1896",
};
printBooksForArray(lines);
/*
foreach (var line in lines) {
var words = line.Split(';');
foreach (var item in words) {
var pair = item.Split('=');
Console.WriteLine("{0} : {1}", ToJapanese(pair[0]), pair[1]);
}
}
*/
#endif
Console.WriteLine("実行時間 = {0}", sw.Elapsed.ToString(@"ss\.ffff"));
}
private static string ToJapanese(string key) {
switch (key) {
case "Novelist":
return "作家";
case "BestWork":
return "代表作";
case "Born":
return "誕生年";
default:
return "引数エラー";
}
}
private static string[] lineDecompose(string line) {
var words = line.Split(';');
int equalPoint;
for (int i = 0; i < words.Length; i++) {
equalPoint = words[i].IndexOf('=');
words[i] = words[i].Remove(0, equalPoint + 1);
}
return words;
}
#if NonArray
//1冊の本用のメソッド
private static void printBook(string line) {
var formatWords = new String[]{
"作家 :",
"代表作:",
"誕生年:",
};
var words = lineDecompose(line);
for (int i = 0; i < words.Length; i++) {
Console.WriteLine(formatWords[i] + words[i]);
}
}
#endif
#if StringArray
//複数の本用のメソッド
private static void printBooksForArray(string[] lines) {
var formatWords = new String[]{
"作家 :",
"代表作:",
"誕生年:",
};
var words = new string[3];
for (int i = 0; i < lines.Length; i++) {
words = lineDecompose(lines[i]);
for (int j = 0; j < words.Length; j++) {
Console.WriteLine(formatWords[j] + words[j]);
}
Console.WriteLine("----------------");
}
}
#endif
}
} |
#' Install Packages from GitHub
#'
#' @param packages character vector of the names of the packages.
#' You can specify \code{ref} argument (see below) using \code{package_name[@ref|#pull]}.
#' If both are specified, the values in repo take precedence.
#' @param ask logical. Indicates ask to confirm before install.
#' @param ref character vector. Desired git reference.
#' Could be a commit, tag, or branch name, or a call to \code{\link{github_pull}}.
#' Defaults to "master".
#' @param build_vignettes logical. If \code{TRUE}, will build vignettes.
#' @param dependencies logical. Indicating to also install uninstalled packages which the packages depends on/links to/suggests.
#' See argument dependencies of \code{\link{install.packages}}.
#' @param verbose logical. Indicating to print details of package building and installation. Dfault is \code{TRUE}.
#' @param quiet logical. Not \code{verbose}.
#' @param lib character vector giving the library directories where to install the packages.
#' Recycled as needed. Defaults to the first element of \code{\link{.libPaths}()}.
#' @param ... additional arguments to control installation of package, passed to \code{\link{install_github}}.
#'
#' @return TRUE if success.
#'
#' @details
#' \code{githubinstall()} is an alias of \code{gh_install_packages()}.
#'
#' @examples
#' \dontrun{
#' gh_install_packages("AnomalyDetection")
#' githubinstall("AnomalyDetection")
#' }
#'
#' @rdname gh_install_packages
#'
#' @export
gh_install_packages <- function(packages, ask = TRUE, ref = "master",
build_vignettes = FALSE, dependencies = NA,
verbose = TRUE, quiet = !verbose, lib = NULL, ...) {
# Adjust arguments
if (length(lib) == 1)
lib <- rep(lib, length(packages))
dependencies <- recommend_dependencies(ask, build_vignettes, dependencies, quiet)
pac_and_ref <- separate_into_package_and_reference(packages, ref)
packages <- pac_and_ref$packages
reference_list <- pac_and_ref$reference_list
# Suggest repositories
repos <- lapply(packages, select_repository)
titles <- vapply(repos, attr, character(1), "title")
repos <- unlist(repos)
attr(repos, "title") <- titles
# Confirm to install
if (ask) {
target <- paste0(format_choices(repos), collapse = "\n - ")
msg <- sprintf("Suggestion:\n - %s", target)
message(msg)
prompt <- sprintf("Do you want to install the package%s (Y/n)? ", ifelse(length(repos) == 1, "", "s"))
answer <- substr(readline(prompt), 1L, 1L)
if (!(answer %in% c("", "y", "Y"))) {
message("cancelled by user\n")
stop_without_message()
}
}
# Check conflict
repos <- remove_conflict_repos(repos, lib, quiet, ask)
if (length(repos) == 0) {
message("cancelled by user\n")
stop_without_message()
}
# Install
results <- vector("list", length(repos))
for (i in seq_along(repos)) {
repo <- repos[i]
ref <- reference_list[[i]]
lib.loc <- lib[i]
results[[i]] <- install_package(repo = repo, ref = ref, quiet = quiet,
dependencies = dependencies,
build_vignettes = build_vignettes,
lib = lib.loc, ... = ...)
}
names(results) <- repos
if(length(results) == 1) {
invisible(results[[1]])
} else {
invisible(results)
}
}
#' @rdname gh_install_packages
#' @export
githubinstall <- gh_install_packages
#' @importFrom devtools install_github
install_package <- function(repo, ref, quiet, dependencies, build_vignettes, lib, ...) {
lib_paths <- .libPaths()
.libPaths(c(lib, lib_paths))
result <- install_github(repo = repo, ref = ref, quiet = quiet,
dependencies = dependencies,
build_vignettes = build_vignettes, ... = ...)
.libPaths(lib_paths)
log_installed_packages(repo = repo, ref = ref)
result
} |
import React from "react";
import { Card, CardFooter, CardHeader } from "@/components/ui/card";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import Link from "next/link";
import { useParams } from "next/navigation";
import { dateView } from "@/lib/dayjs";
export default function BoardItem(props: Post) {
const { name, title, createdDate, commentCount, picture, articleId } = props;
const params = useParams();
return (
<div className="grid gap-4">
<Link
className="font-bold relative"
href={`/club/${params.id}/board/${articleId}`}
>
<div className="absolute w-full h-full hover:bg-white/60 transition-colors duration-300"></div>
<Card>
<CardHeader className="p-2 flex flex-row items-center">
<div className="flex items-center w-full text-sm font-semibold">
<Avatar className="w-8 h-8 border ml-2">
<AvatarImage alt={name} src={picture} />
<AvatarFallback>{name}</AvatarFallback>
</Avatar>
<div className="w-full pl-4">{name}</div>
<div className="px-4 text-xs w-fit grid gap-1.5 font-normal text-gray-400">
<div className="w-fit text-nowrap">{dateView(createdDate)}</div>
</div>
</div>
</CardHeader>
<CardFooter className="p-2 pb-4 grid gap-2">
<div className="">
<div className="px-2 pb-4 text-sm w-full font-normal">
{title}
</div>
</div>
<div className="px-2 text-xs w-full grid gap-1.5 font-semibold">
<div>댓글 {commentCount}개</div>
</div>
</CardFooter>
</Card>
</Link>
</div>
);
} |
<!-- Copyright © 2018-2019 Inria. All rights reserved. -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Dynamic SVG</title>
</head>
<body>
<p>
This page is an example of HTML/JS interacting with the lstopo SVG output.
</p>
<p>
Load a SVG that was exported with lstopo's <b>native</b> SVG backend
(e.g. with <tt>lstopo --of nativesvg foo.svg</tt>):
</p>
<input type="file" name="myFile" accept=".svg" onchange="openFile(event)">
<br>
<br>
<object id="img" type="image/svg+xml">
</object>
<br>
<p id='caption' style='display:none'>
Click on a box to change its background color
and replace its first text line (if any) with its SVG object id.
</p>
<p id='drag' style='display:none'>
<input type='checkbox' id='draggable' onclick='enableDrag()'>Make boxes draggable</input>
</p>
</body>
<footer>
<script type="text/javascript">
function openFile(event) {
let image = document.getElementById('img')
image.data = null
var input = event.target;
var TextReader = new FileReader()
TextReader.onload = async function(){
var parser = new DOMParser()
let blob = new Blob([TextReader.result], {type: 'image/svg+xml'})
let url = URL.createObjectURL(blob)
image.data = await url
setTimeout(function(){
document.getElementById('caption').style = ''
document.getElementById('drag').style = ''
document.getElementById("draggable").checked = false
svgObject = document.getElementById('img').contentDocument
let svgElement = svgObject.getElementById('Machine_0_rect')
if(svgObject.getElementById('Machine_0_rect')){
start(svgObject)
}else{
const h1 = document.createElement('h1')
h1.innerHTML = "Your svg file doesn't have the good format to load javascript"
document.body.appendChild(h1)
}
},200)
}
TextReader.readAsText(input.files[0], "UTF-8")
}
function enableDrag(){
let svgObject = document.getElementById('img').contentDocument
const elements = svgObject.getElementsByTagName('rect')
for (let element of elements) {
element.classList.toggle("draggable")
}
}
function start(svgObject){
makeDraggable(svgObject)
const texts = svgObject.getElementsByTagName('text')
for (let text of texts) {
text.setAttribute("style", text.getAttribute("style") + ";pointer-events:none;")
}
const elements = svgObject.getElementsByTagName('rect')
for (let element of elements) {
if(!element.id.includes("Bridge")){
element.addEventListener('click', function(e) {
changeColor(svgObject, e.target)
changeText(svgObject, e.target)
})
}
}
}
function changeColor(svgObject, element){
oldColor = element.getAttribute("saveColor")
if(!oldColor){
element.setAttribute("saveColor", element.getAttribute("fill"))
element.setAttribute("fill", "red")
}else{
element.setAttribute("fill", oldColor)
element.removeAttribute("saveColor")
}
}
function changeText(svgObject, element){
if(element.id == "")
return
const text = svgObject.getElementById(element.id.replace('rect', 'text'))
let textContent = element.getAttribute("saveText")
if(!textContent){
element.setAttribute("saveText", text.innerHTML)
textContent = element.id
}else{
element.removeAttribute("saveText")
}
let svg = svgObject.documentElement;
let svgNS = svg.namespaceURI;
let newText = text.cloneNode(false)
newText.appendChild(svgObject.createTextNode(textContent))
svg.removeChild(text)
svg.appendChild(newText)
}
function makeDraggable(svgObject) {
let selectedElement = null
let text = null
let marginTextX = null
let marginTextY = null
svgObject.addEventListener('mousedown', startDrag)
svgObject.addEventListener('mousemove', drag)
svgObject.addEventListener('mouseup', endDrag)
svgObject.addEventListener('mouseleave', endDrag)
function startDrag(evt) {
if (evt.target.classList.contains('draggable')) {
selectedElement = evt.target;
text = getText(svgObject, selectedElement.id)
marginTextX = text.getAttribute("x") - selectedElement.getAttribute("x")
marginTextY = text.getAttribute("y") - selectedElement.getAttribute("y")
}
}
function drag(evt) {
if (selectedElement) {
evt.preventDefault();
let textDragX = evt.clientX + marginTextX
let textDragY = evt.clientY + marginTextY
let dragX = evt.clientX;
let dragY = evt.clientY;
selectedElement.setAttribute("x", dragX);
selectedElement.setAttribute("y", dragY);
text.setAttribute("x", textDragX);
text.setAttribute("y", textDragY);
}
}
function endDrag(evt) {
selectedElement = null
}
}
</script>
</footer>
</html> |
<!DOCTYPE html>
<html>
<head>
<title>punkdrop</title>
</head>
<body>
<h1>Welcome to punkdrop</h1>
<h2>Web file sharing made easy</h2>
<p>Your generated key: <strong id="userKey"></strong></p>
<div>
<input type="file" id="file" />
<button onclick="sendFile()">Send File</button>
</div>
<div>
<label for="message">Message</label>
<div>
<textarea id="message"></textarea>
</div>
<label for="receiver">To</label>
<input type="text" id="receiver" />
<button onclick="sendToUser()">Send</button>
</div>
<div id="output"></div>
<script>
const userKey = "USER_KEY";
let socket;
function sendToUser() {
const to = document.getElementById("receiver");
const msg = document.getElementById("message");
const message = {
type: "message",
receiver: to.value,
content: msg.value,
};
socket.send(JSON.stringify(message));
}
function connectWebSocket() {
socket = new WebSocket(`ws://localhost:8080/ws?key=${userKey}`);
socket.onopen = function (event) {
appendMessage("WebSocket connected");
};
socket.onmessage = function (event) {
appendMessage("Received: " + event.data);
};
socket.onclose = function (event) {
appendMessage("WebSocket closed");
};
}
function sendFile() {
const fileInput = document.getElementById("file");
const file = fileInput.files[0];
if (!file) {
alert("Please select a file.");
return;
}
// Implement file sending logic here
}
function testConnection() {
socket.send("Hello, world!");
}
function appendMessage(message) {
const output = document.getElementById("output");
const p = document.createElement("p");
p.textContent = message;
output.appendChild(p);
}
document.addEventListener("DOMContentLoaded", function () {
connectWebSocket();
const keyElem = document.getElementById("userKey");
keyElem.textContent = userKey;
});
</script>
</body>
</html> |
package com.ruoyi.system.controller;
import java.util.ArrayList;
import java.util.List;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.utils.ShiroUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.StudentCourseRecord;
import com.ruoyi.system.service.IStudentCourseRecordService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
/**
* 学员课程记录管理Controller
*
* @author dhy
* @date 2023-04-04
*/
@Controller
@RequestMapping("/system/record")
public class StudentCourseRecordController extends BaseController
{
private String prefix = "system/record";
@Autowired
private IStudentCourseRecordService studentCourseRecordService;
@RequiresPermissions("system:record:view")
@GetMapping()
public String record()
{
return prefix + "/record";
}
/**
* 查询学员课程记录管理列表
*/
@RequiresPermissions("system:record:list")
@PostMapping("/list")
@ResponseBody
public TableDataInfo list(StudentCourseRecord studentCourseRecord)
{
startPage();
List<StudentCourseRecord> list = studentCourseRecordService.selectStudentCourseRecordList(studentCourseRecord);
for (StudentCourseRecord stdCR:list
) {
stdCR.setName(studentCourseRecordService.selectStudentById(stdCR.getStudentId()).getName());
stdCR.setTopic(studentCourseRecordService.selectCourseById(stdCR.getCourseId()).getTopic());
}
List<SysRole> roleList = ShiroUtils.getSysUser().getRoles();
boolean flag = false;
for (SysRole role:roleList
) {
if (role.getRoleKey().equals("LevelB"))
{
flag = true;
break;
}
if (role.getRoleKey().equals("LevelA"))
{
flag = true;
break;
}
if (role.getRoleKey().equals("admin"))
{
flag = true;
break;
}
}
if(!flag)
{
List<StudentCourseRecord> list1 = new ArrayList<>();
Long id = ShiroUtils.getSysUser().getStudentId();
for (StudentCourseRecord stdCR :list
) {
if(stdCR.getStudentId()==id)
{
list1.add(stdCR);
break;
}
}
return getDataTable(list1);
}
return getDataTable(list);
}
/**
* 导出学员课程记录管理列表
*/
@RequiresPermissions("system:record:export")
@Log(title = "学员课程记录管理", businessType = BusinessType.EXPORT)
@PostMapping("/export")
@ResponseBody
public AjaxResult export(StudentCourseRecord studentCourseRecord)
{
List<StudentCourseRecord> list = studentCourseRecordService.selectStudentCourseRecordList(studentCourseRecord);
ExcelUtil<StudentCourseRecord> util = new ExcelUtil<StudentCourseRecord>(StudentCourseRecord.class);
return util.exportExcel(list, "学员课程记录管理数据");
}
/**
* 新增学员课程记录管理
*/
@GetMapping("/add")
public String add()
{
return prefix + "/add";
}
/**
* 新增保存学员课程记录管理
*/
@RequiresPermissions("system:record:add")
@Log(title = "学员课程记录管理", businessType = BusinessType.INSERT)
@PostMapping("/add")
@ResponseBody
public AjaxResult addSave(StudentCourseRecord studentCourseRecord)
{
return toAjax(studentCourseRecordService.insertStudentCourseRecord(studentCourseRecord));
}
/**
* 修改学员课程记录管理
*/
@RequiresPermissions("system:record:edit")
@GetMapping("/edit/{id}")
public String edit(@PathVariable("id") Long id, ModelMap mmap)
{
StudentCourseRecord studentCourseRecord = studentCourseRecordService.selectStudentCourseRecordById(id);
mmap.put("studentCourseRecord", studentCourseRecord);
return prefix + "/edit";
}
/**
* 修改保存学员课程记录管理
*/
@RequiresPermissions("system:record:edit")
@Log(title = "学员课程记录管理", businessType = BusinessType.UPDATE)
@PostMapping("/edit")
@ResponseBody
public AjaxResult editSave(StudentCourseRecord studentCourseRecord)
{
return toAjax(studentCourseRecordService.updateStudentCourseRecord(studentCourseRecord));
}
/**
* 删除学员课程记录管理
*/
@RequiresPermissions("system:record:remove")
@Log(title = "学员课程记录管理", businessType = BusinessType.DELETE)
@PostMapping( "/remove")
@ResponseBody
public AjaxResult remove(String ids)
{
return toAjax(studentCourseRecordService.deleteStudentCourseRecordByIds(ids));
}
} |
use chrono::{DateTime, Utc};
use clap::{Args, Parser};
use notify_rust::Notification;
use nvml_wrapper::enum_wrappers::device::TemperatureSensor;
use nvml_wrapper::enums::device::UsedGpuMemory;
use nvml_wrapper::struct_wrappers::device::ProcessInfo;
use nvml_wrapper::Nvml;
use std::{
fs::{File, OpenOptions},
io::Write,
path::Path,
};
use sysinfo::{Pid, System};
fn capitalize(input: String) -> String {
let mut chars = input.chars();
match chars.next() {
None => String::new(),
Some(first) => first
.to_uppercase()
.chain(chars.map(|c| c.to_ascii_lowercase()))
.collect(),
}
}
fn send_notification(name: &str, body: &str, icon: &str) {
Notification::new()
.summary(name)
.body(body)
.icon(icon)
.show()
.unwrap();
}
fn get_gpu_usage() -> GpuInfo {
let nvml = Nvml::init().unwrap();
let device = nvml.device_by_index(0).unwrap();
let name = device.name().unwrap();
let total_utilization = device.utilization_rates().unwrap();
let memory_usage = device.memory_info().unwrap();
let temperature = device.temperature(TemperatureSensor::Gpu).unwrap();
let graphics_processes: Vec<ProcessInfo> = device.running_graphics_processes_v2().unwrap();
GpuInfo {
name,
total_utilization: format!("{}%", total_utilization.gpu),
memory_usage: (memory_usage.used >> 20, memory_usage.total >> 20),
temperature,
graphics_processes,
}
}
fn get_target_process_info(gpu_info: GpuInfo, target_process: &str) -> SingleProcessInfo {
gpu_info
.graphics_processes
.iter()
.filter(|process| {
let sys = System::new_all();
let process_name = get_process_name(&sys, process.pid);
process_name == target_process
})
.map(|process| SingleProcessInfo {
name: get_process_name(&System::new_all(), process.pid),
memory_usage: match process.used_gpu_memory {
UsedGpuMemory::Used(used) => used >> 20,
_ => 0,
},
})
.collect::<Vec<SingleProcessInfo>>()
.pop()
.unwrap()
}
fn get_process_name(sys: &sysinfo::System, pid: u32) -> String {
if let Some(process) = sys.process(Pid::from_u32(pid)) {
return process.name().to_string();
}
String::from("")
}
fn print_info(gpu_info: GpuInfo, target_process_info: SingleProcessInfo) {
println!(
"Name: {:#?}\nTotal utilization: {:#?}\nMemory usage: {:#?}/{:#?} MB\nTemperature: {:#?}°C\n{} memory usage: {:#?} MB",
gpu_info.name,
gpu_info.total_utilization,
gpu_info.memory_usage.0,
gpu_info.memory_usage.1,
gpu_info.temperature,
target_process_info.name,
target_process_info.memory_usage
);
}
fn init_log(path: &str) -> File {
if Path::new(path).exists() {
OpenOptions::new().append(true).open(path).unwrap()
} else {
File::create(path).unwrap()
}
}
fn log_info(
gpu_info: GpuInfo,
log_path: &str,
target_process_info: Option<SingleProcessInfo>,
delimiter: &str,
) {
let mut file = init_log(log_path);
let mut log = String::new();
let now: DateTime<Utc> = Utc::now();
log.push_str(format!("{} | ", now.format("%a %b %e %T %Y")).as_str());
log.push_str(format!("{}{}", gpu_info.name, delimiter).as_str());
log.push_str(
format!(
"Total utilization: {}{}",
gpu_info.total_utilization, delimiter
)
.as_str(),
);
log.push_str(
format!(
"Memory usage: {}/{} MB{}",
gpu_info.memory_usage.0, gpu_info.memory_usage.1, delimiter
)
.as_str(),
);
log.push_str(format!("Temperature: {}°C{}", gpu_info.temperature, delimiter).as_str());
match target_process_info {
Some(target_process_info) => {
log.push_str(
format!(
"{} memory usage: {} MB",
target_process_info.name, target_process_info.memory_usage
)
.as_str(),
);
}
None => {
for process in gpu_info.graphics_processes {
let process_name = capitalize(get_process_name(&System::new_all(), process.pid));
log.push_str(
format!(
"{} memory usage: {} MB",
process_name,
match process.used_gpu_memory {
UsedGpuMemory::Used(used) => used >> 20,
_ => 0,
}
)
.as_str(),
);
}
}
}
log.push('\n');
file.write_all(log.as_bytes()).unwrap();
}
#[derive(Debug, Clone)]
struct GpuInfo {
name: String,
total_utilization: String,
memory_usage: (u64, u64),
temperature: u32,
graphics_processes: Vec<ProcessInfo>,
}
#[derive(Debug, Clone)]
struct SingleProcessInfo {
name: String,
memory_usage: u64,
}
/// Simple program to get the GPU usage of a process
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Arguments {
#[command(flatten)]
name_or_loging: NameOrLoging,
/// Print info about the GPU and the process
#[arg(short, long, requires = "name")]
print_info: bool,
/// Disable the notification
#[arg(short, long, requires = "name")]
disable_notification: bool,
/// Path to the log file
#[arg(
short = 'L',
long,
default_value = "/tmp/gpu-usage.log",
requires = "loging"
)]
log_path: String,
/// Log delimiter
#[arg(short, long, default_value = ", ", requires = "loging")]
delimiter: String,
}
#[derive(Args, Debug)]
#[group(required = true, multiple = true)]
struct NameOrLoging {
/// Name of the a process
#[arg(short, long)]
name: Option<String>,
/// Log the GPU usage
#[arg(short, long)]
loging: bool,
}
fn main() {
let args: Arguments = Arguments::parse();
let gpu_info: GpuInfo = get_gpu_usage();
if args.name_or_loging.name.is_some() {
let target_process_info: SingleProcessInfo =
get_target_process_info(gpu_info.clone(), args.name_or_loging.name.unwrap().as_str());
if !args.disable_notification {
send_notification(
"GPU Usage",
format!(
"{} is utilizing {} MB of memory",
capitalize(target_process_info.name.clone()),
target_process_info.memory_usage
)
.as_str(),
"dialog-information",
);
}
if args.print_info {
print_info(gpu_info.clone(), target_process_info.clone());
}
if args.name_or_loging.loging {
log_info(
gpu_info,
&args.log_path,
Some(target_process_info),
args.delimiter.as_str(),
);
}
} else if args.name_or_loging.loging {
log_info(gpu_info, &args.log_path, None, args.delimiter.as_str());
} else {
println!("Please provide a process name or enable loging")
}
} |
<?php
// (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
class TikiFilter
{
/**
* Provides a filter instance based on the input. Either a filter
* can be passed or a name.
*
* @param mixed
* @return \Zend\Filter\FilterInterface
*/
public static function get( $filter )
{
if ( $filter instanceof \Zend\Filter\FilterInterface ) {
return $filter;
}
switch( $filter )
{
case 'alpha':
return new TikiFilter_Alpha; // Removes all but alphabetic characters.
case 'word':
return new TikiFilter_Word; // A single word of alphabetic characters (im pretty sure) ?I18n?
case 'alnum':
return new TikiFilter_Alnum; // Only alphabetic characters and digits. All other characters are suppressed. I18n support
case 'digits':
return new Zend\Filter\Digits; // Removes everything except for digits eg. '12345 to 67890' returns 1234567890
case 'int':
return new Zend\Filter\ToInt; // Allows you to transform a sclar value which contains into an integer. eg. '-4 is less than 0' returns -4
case 'isodate':
return new TikiFilter_IsoDate;
case 'isodatetime':
return new TikiFilter_IsoDate('Y-m-d H:i:s');
case 'username':
case 'groupname':
case 'pagename':
case 'topicname':
case 'themename':
case 'email':
case 'url':
case 'text':
case 'date':
case 'time':
case 'datetime':
// Use striptags
case 'striptags':
return new Zend\Filter\StripTags; // Strips XML and HTML tags
case 'xss':
return new TikiFilter_PreventXss; // Leave everything except for potentially malicious HTML
case 'purifier':
return new TikiFilter_HtmlPurifier('temp/cache'); // Strips non-valid HTML and potentially malicious HTML.
case 'wikicontent':
return new TikiFilter_WikiContent;
case 'rawhtml_unsafe':
case 'none':
return new TikiFilter_RawUnsafe;
case 'lang':
return new Zend\Filter\PregReplace('/^.*([a-z]{2})(\-[a-z]{2}).*$/', '$1$2');
case 'imgsize':
return new Zend\Filter\PregReplace('/^.*(\d+)\s*(%?).*$/', '$1$2');
case 'attribute_type':
return new TikiFilter_AttributeType;
default:
trigger_error('Filter not found: ' . $filter, E_USER_WARNING);
return new TikiFilter_PreventXss;
}
}
} |
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { HttpService } from '../../../services/http.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-category-create',
template: `<div class="container-fluid">
<div class="card">
<div class="card-body">
<form class="row g-3" [formGroup]="reacForm">
<div class="col-12">
<label for="exampleInputUsername1" class="form-label"
>Tên danh mục</label
>
<input
type="text"
class="form-control"
formControlName="categoryName"
/>
</div>
<div class="col-12">
<button
type="submit"
class="btn btn-primary me-2"
(click)="create($event)"
>
Thêm thông tin
</button>
<a href="category-list" class="btn btn-light">Hủy</a>
</div>
</form>
</div>
</div>
</div> `,
})
export class CategoryCreateComponent implements OnInit {
public reacForm!: FormGroup;
constructor(
private http: HttpService,
private fb: FormBuilder,
private router: Router
) {}
ngOnInit(): void {
this.initForm();
}
private initForm() {
this.reacForm = this.fb.group({
categoryName: [],
});
}
public create(event: any) {
const newObj = {
categoryName: this.reacForm.get('categoryName')?.value,
};
this.http.create('category', newObj).subscribe(
(res) => {
alert('Thêm thành công.');
this.router.navigate(['/category-list']);
},
(err) => {
alert(err.message);
}
);
}
} |
from os import truncate
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.popup import Popup
from kivy.graphics.texture import Texture
from kivy.clock import Clock
from kivy.core.window import Window
from kivy.config import Config
from kivy.properties import ListProperty
from os.path import expanduser
from os.path import join
import cv2
from face_swap_helper_webcam import FaceSwapHelperWebcam
from image_capture import ImageCapture
from webcam import WebCam
from file_chooser import FileChooser
Config.set('input', 'mouse', 'mouse,disable_multitouch')
class FaceSwap(BoxLayout):
HOME_DIR = expanduser('~')
IMAGE_CAPTURE_FILE_EXTENSION = ".png"
helper = FaceSwapHelperWebcam()
Window.minimum_width = 400
Window.minimum_height = 300
fullscreen_camera = False
def build(self):
self.set_webcam_spinner()
def update(self, dt):
try:
self.helper.update_face_swap()
except cv2.error as e:
print(e)
except RuntimeError as e:
print(e)
if self.helper.paused:
self.ids['notification'].text = "paused"
self.ids['notification'].color = (0, 0, 1, 1)
self.ids['swapped_image'].texture = self.get_texture(
self.helper.webcam_image.image)
return
if self.helper.successful:
self.ids['swapped_image'].texture = self.get_texture(
self.helper.swapped_face)
self.ids['notification'].text = "successful"
self.ids['notification'].color = (0, 1, 0, 1)
else:
self.ids['swapped_image'].texture = self.get_texture(
self.helper.webcam_image.image)
self.ids['notification'].text = "no face detected"
self.ids['notification'].color = (1, 0, 0, 1)
def get_texture(self, img):
flipped_img = cv2.flip(img, 0)
texture = Texture.create(size=(img.shape[1], img.shape[0]), colorfmt='bgr')
texture.blit_buffer(flipped_img.tobytes(), colorfmt='bgr', bufferfmt='ubyte')
return texture
def capture(self):
ImageCapture().capture(self.helper, self.HOME_DIR + "\\Pictures\\Face Swap\\",
self.IMAGE_CAPTURE_FILE_EXTENSION)
def set_webcam_spinner(self):
webcams = []
for i in range(WebCam.count_webcams()):
webcams.append("Webcam " + str(i))
self.ids["webcam_spinner"].values = webcams
self.ids["webcam_spinner"].bind(text = self.change_webcam)
def change_webcam(self, spinner, text):
self.ids["webcam_spinner"].text = text
webcam_number = int(text[len(text) - 1 : len(text)])
self.helper.set_webcam(webcam_number)
def open_file_chooser(self):
content = FileChooser(load=self.change_source_image, cancel=self.dismiss_file_chooser)
content.ids['filechooser'].rootpath = self.HOME_DIR
content.ids['filechooser'].filters = ['*.bmp', '*.pbm', '*.pgm', '*.ppm',
'*.sr', '*.ras', '*.jpeg', '*.jpg',
'*.jpe', '*.jp2', '*.tiff', '*.tif',
'*.png']
self.file_chooser_popup = Popup(title="Load image", content=content,
size_hint=(0.9, 0.9))
self.file_chooser_popup.open()
self.helper.paused = True
def dismiss_file_chooser(self):
self.file_chooser_popup.dismiss()
self.helper.paused = False
def change_source_image(self, path, filename):
filepath = join(path, filename[0]).replace("\\", "\\\\")
try:
self.helper.set_source_image(filepath)
except:
self.ids['notification'].text = "cannot detect face in source image"
self.ids['notification'].color = (1, 0, 0, 1)
return
self.ids['source_image'].texture = self.get_texture(
self.helper.source_image.image)
self.file_chooser_popup.dismiss()
self.helper.paused = False
def change_flip_camera(self):
self.helper.flip_camera = not self.helper.flip_camera
if(self.helper.flip_camera):
self.ids['flip_camera'].text = "Flip Camera (on)"
else:
self.ids['flip_camera'].text = "Flip Camera (off)"
def toogle_camera_fullscreen(self, root):
if(self.fullscreen_camera):
self.fullscreen_camera = False
self.ids['swapped_image'].size = (root.width / 2, root.height / 2)
self.ids['swapped_image'].center = (self.parent.center[0], self.parent.center[1]) #self.parent.center #
else:
self.fullscreen_camera = True
self.ids['swapped_image_button'].size = (root.width, root.height)
self.ids['swapped_image'].size = (root.width, root.height)
self.ids['swapped_image'].center = (root.center_x, root.center_y)
class FaceSwapApp(App):
def build(self):
self.icon = 'images/logo.png'
self.title = "Face Swap"
self.fs = FaceSwap()
self.fs.build()
Clock.schedule_interval(
self.fs.update, 1.0/self.fs.helper.get_framerate())
return self.fs
if __name__ == '__main__':
FaceSwapApp().run() |
import jwt from "jsonwebtoken";
import { envs } from ".";
export const JWT_SEED=envs.JWT_SEED
export class JwtAdapter {
static async generateToken(
payload: Object,
duration: string = "2h"
): Promise<string | null> {
return new Promise((resolve) => {
//todo generacion del seed
//Siempre se resuelve algo o null o el token
jwt.sign(payload, JWT_SEED, { expiresIn: duration }, (err, token) => {
if (err) return resolve(null);
//en este piunto si todo sale bien se envia el token
resolve(token!);
});
});
}
//*Sin promesa
// signToken = (email: string) => {
// if (!process.env.JWT_SECRET_SEED) {
// throw new Error("No hay Semilla de error");
// }
// return jwt.sign(
// //!Payload
// { email },
// //!Seed
// "SEED",
// //!Opciones
// { expiresIn: "1d" }
// );
// };
//* El tipo T tiene la firma <{id:string}> especificado en la llamada al metodo const payload=await JwtAdapter.validateToken<{id:string}>(token)
static validateToken<T>(token:string):Promise<T|null>{
return new Promise((resolve)=>{
jwt.verify(token,JWT_SEED,(error,decoded)=>{
//si viene el error enviamos null
if(error) return resolve(null)
//si no hay error enviamos el token decodificado, SIEMPRE ENVIAMREMOS ALGO por el resolv de manera exitosa. definimos el tipo de datos de decode como T ya que es el tipo que se envio desde la llamada al metodo
resolve(decoded as T)
})
})
}
} |
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import * as z from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useToast } from "@/components/ui/use-toast";
import { signIn } from "next-auth/react";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "../ui/card";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "../ui/form";
import { Input } from "../ui/input";
import { Button } from "../ui/button";
import UnderlineLink from "../links/UnderlineLink";
const formSchema = z.object({
username: z.string().refine(
(value) => {
if (value.length < 6) return false;
// Al menos un número
if (!/\d/.test(value)) return false;
// No debe contener caracteres especiales
if (/[^a-zA-Z0-9]/.test(value)) return false;
return true;
},
{
message:
"Username must: minimum 6 characters, a number, no strange characters.",
}
),
email: z.string().email(),
password: z.string().refine(
(value) => {
// Mínimo 6 caracteres
if (value.length < 6) return false;
// Al menos una mayúscula
if (!/[A-Z]/.test(value)) return false;
// Al menos un número
if (!/\d/.test(value)) return false;
return true;
},
{
message:
"Password must have: at least 6 characters, at least one number and one capital letter.",
}
),
});
type UserFormValues = z.infer<typeof formSchema>;
const SingUpFrom = () => {
const router = useRouter();
const { toast } = useToast();
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const defaultValues: UserFormValues = {
username: "",
email: "",
password: "",
};
const form = useForm<UserFormValues>({
resolver: zodResolver(formSchema),
defaultValues,
});
const resetForm = () => {
setError("");
form.reset();
};
const onCancel = () => {
resetForm();
router.push("/");
};
const onSubmit = async (data: UserFormValues) => {
setLoading(true);
await fetch("/api/auth/register", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
})
.then(() => {
setLoading(false);
setError("");
signIn("credentials", {
username: data.username,
password: data.password,
callbackUrl: "/",
}).then((callback) => {
if (callback?.ok) {
toast({
variant: "success",
title: "Success",
description: "User created successfully",
});
}
if (callback?.error) {
toast({
variant: "destructive",
title: "Error",
description: callback.error,
});
}
});
})
.catch((error) => {
console.log(error);
setError(error);
toast({
variant: "destructive",
title: "Error",
description: error,
});
})
.finally(() => {
setLoading(false);
});
};
return (
<Card>
<CardHeader>
<CardTitle>Register</CardTitle>
<CardDescription>
To use our system, enter a username and password
</CardDescription>
</CardHeader>
<CardContent>
<div className="text-red-500">{error}</div>
{loading && <div className="text-sm italic">Loading...</div>}
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="space-y-8 w-full"
>
<div className="grid gap-4 pb-4">
<FormField
control={form.control}
name="username"
render={({ field }) => (
<FormItem>
<FormLabel>User</FormLabel>
<FormControl>
<Input
disabled={loading}
placeholder="username"
autoComplete="off"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input
disabled={loading}
placeholder="email"
type="email"
autoComplete="off"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>Password</FormLabel>
<FormControl>
<Input
disabled={loading}
placeholder="Password"
type="password"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="text-sm">
Do you have an account?{" "}
<UnderlineLink href="/sign-in">Sign In</UnderlineLink>
</div>
<div className="flex justify-end items-center ">
<div className="flex gap-x-4">
<Button
variant="destructive"
type="button"
onClick={onCancel}
>
Cancel
</Button>
<Button variant="secondary" disabled={loading} type="submit">
Register
</Button>
</div>
</div>
</div>
</form>
</Form>
</CardContent>
</Card>
);
};
export default SingUpFrom; |
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
// Components
import { HomeComponent } from './home/home.component';
import { ContactUsComponent } from './contact-us/contact-us.component';
import { ProductComponent } from './product/product.component';
import { ProductPageComponent } from './product-page/product-page.component';
const routes: Routes = [
{
path: 'home',
component: HomeComponent
}, {
path: 'contactUs',
component: ContactUsComponent
}, {
path: 'product',
component: ProductComponent
}, {
path: 'productPage',
component: ProductPageComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { } |
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Resources\User\UserResource;
use App\Repositories\Contracts\IUserRepository;
use App\Services\Auth\AuthService;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\RegisterRequest;
use App\Http\Requests\Auth\LoginRequest;
use App\Http\Resources\ErrorResource;
use App\Http\Resources\SuccessResource;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
class AuthController extends Controller
{
public function __construct(
private AuthService $authService,
private IUserRepository $userRepository,
)
{
}
public function login(LoginRequest $request)
{
dd(111111);
$token = Auth::attempt($request->only(['email', 'password']));
if (!$token) {
return ValidationException::withMessages(['credentials' => 'Wrong credentials']);
}
return SuccessResource::make([
'data' => [
'user' => UserResource::make($this->userRepository->findById(auth()->id())),
'auth' => [
'token' => $token
]
]
]);
}
public function user(): SuccessResource
{
return SuccessResource::make([
'data' => [
'user' => UserResource::make($this->userRepository->findById(auth()->id())),
]
]);
}
public function register(RegisterRequest $request): SuccessResource
{
$this->authService->register($request->validated());
return SuccessResource::make([
'message' => "User registered"
]);
}
public function logout(): SuccessResource
{
auth()->logout();
return SuccessResource::make([
'message' => 'Successfully logout'
]);
}
public function refresh()
{
return SuccessResource::make([
'data' => [
'user' => UserResource::make($this->userRepository->findById(auth()->id())),
'auth' => [
'token' => Auth::refresh()
]
]
]);
}
} |
package owners
import "context"
// Repository defines owner storage interface.
type Repository interface {
// Save adds a new owner to the owner store.
Save(ctx context.Context, owner Owner) (Owner, error)
// Updates a given owner entity
Update(ctx context.Context, owner Owner) error
// Retrieve retrieves an owner given their id
Retrieve(ctx context.Context, id string) (Owner, error)
// Search retrieves an owner given their fname, lname and phone.
Search(ctx context.Context, owner Owner) (Owner, error)
// RetrieveAll retrieves a subst of owners.
RetrieveAll(ctx context.Context, offset, limit uint64) (OwnerPage, error)
RetrieveByPhone(ctx context.Context, phone string) (Owner, error)
} |
//文件压缩-Huffman实现
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXSIZE 32
struct tnode { //Huffman树结构
char c;
int weight; //树节点权重,叶节点为字符和它的出现次数
struct tnode *left,*right;
} ;
int Ccount[128]={0}; //存放每个字符的出现次数,如Ccount[i]表示ASCII值为i的字符出现次数
struct tnode *Root=NULL; //Huffman树的根节点
char HCode[128][MAXSIZE]={{0}}; //字符的Huffman编码,如HCode['a']为字符a的Huffman编码(字符串形式)
int Step=0; //实验步骤
FILE *Src, *Obj;
void statCount(); //步骤1:统计文件中字符频率
void createHTree(); //步骤2:创建一个Huffman树,根节点为Root
void makeHCode(); //步骤3:根据Huffman树生成Huffman编码
void atoHZIP(); //步骤4:根据Huffman编码将指定ASCII码文本文件转换成Huffman码文件
void print1(); //输出步骤1的结果
void print2(struct tnode *p); //输出步骤2的结果
void print3(); //输出步骤3的结果
void print4(); //输出步骤4的结果
int main()
{
if((Src=fopen("input.txt","r"))==NULL) {
fprintf(stderr, "%s open failed!\n", "input.txt");
return 1;
}
if((Obj=fopen("output.txt","w"))==NULL) {
fprintf(stderr, "%s open failed!\n", "output.txt");
return 1;
}
scanf("%d",&Step); //输入当前实验步骤
statCount(); //实验步骤1:统计文件中字符出现次数(频率)
(Step==1)?print1():1; //输出实验步骤1结果
createHTree(); //实验步骤2:依据字符频率生成相应的Huffman树
(Step==2)?print2(Root):2; //输出实验步骤2结果
makeHCode(); //实验步骤3:依据Root为树的根的Huffman树生成相应Huffman编码
(Step==3)?print3():3; //输出实验步骤3结果
(Step>=4)?atoHZIP(),print4():4;//实验步骤4:据Huffman编码生成压缩文件,并输出实验步骤4结果
fclose(Src);
fclose(Obj);
return 0;
}
//【实验步骤1】开始
void statCount()
{
char c;
Ccount[0]=1;
while((c=fgetc(Src))!=EOF)
{
if(c!='\n')
Ccount[c]++;
}
}
//【实验步骤1】结束
//【实验步骤2】开始
void createHTree()
{
struct tnode *p=NULL, *tree[1005],*temp=NULL;
int i,j=0,k;
for(i=0;i<128;i++)
{
if(Ccount[i]!=0)
{
p=(struct tnode*)malloc(sizeof(struct tnode));
p->c=i,p->weight=Ccount[i];
p->left=p->right=NULL;
tree[j++]=p;
}
}
for(i=0,j=j-1;i<=j;i++)
{
for(k=0;k<=j-i-1;k++)
{
if(tree[k]->weight<tree[k+1]->weight)
{
temp=tree[k];
tree[k]=tree[k+1];
tree[k+1]=temp;
}
else if(tree[k]->weight==tree[k+1]->weight)
{
if(tree[k]->c<tree[k+1]->c)
{
temp=tree[k];
tree[k]=tree[k+1];
tree[k+1]=temp;
}
}
}
}
for(j;j>0;)
{
p=(struct tnode*)malloc(sizeof(struct tnode));
p->left=p->right=NULL;
p->left=tree[j],p->right=tree[j-1];
p->weight=p->left->weight+p->right->weight;
j-=2;
for(i=0;i<=j;i++)
if(p->weight>=tree[i]->weight) break;
for(k=j+1;k>i;k--)
tree[k]=tree[k-1];
tree[i]=p;
j++;
}
Root=tree[0];
}
//【实验步骤2】结束
//【实验步骤3】开始
void makeHCode()
{
int level=0;
struct tnode *p=Root;
char Huffman[1005]={0};
frontorder(p,'0',0,Huffman);
}
void frontorder(struct tnode *p,char code,int level,char Huffman[])
{
if(level!=0)
Huffman[level-1]=code;
if(p->left==NULL&&p->right==NULL)
{
Huffman[level]='\0';
strcpy(HCode[p->c],Huffman);
}
else
{
frontorder(p->left,'0',level+1,Huffman);
frontorder(p->right,'1',level+1,Huffman);
}
}
//【实验步骤3】结束
//【实验步骤4】开始
void atoHZIP()
{
unsigned char *pc,hc=0;
int c=0,i=0;
fseek(Src,0,SEEK_SET);
do{
c=fgetc(Src);
if(c==EOF) c=0;
for(pc=HCode[c];*pc!='\0';pc++)
{
hc=(hc<<1)|(*pc-'0');
i++;
if(i==8)
{
fputc(hc,Obj);
printf("%x", hc);
i=0;
}
}
if(c==0&&i!=0)
{
while(i++<8) hc=(hc<<1);
fputc(hc,Obj);
}
}while(c);
}
//【实验步骤4】结束
void print1()
{
int i;
printf("NUL:1\n");
for(i=1; i<128; i++)
if(Ccount[i] > 0)
printf("%c:%d\n", i, Ccount[i]);
}
void print2(struct tnode *p)
{
if(p != NULL){
if((p->left==NULL)&&(p->right==NULL))
switch(p->c){
case 0: printf("NUL ");break;
case ' ': printf("SP ");break;
case '\t': printf("TAB ");break;
case '\n': printf("CR ");break;
default: printf("%c ",p->c); break;
}
print2(p->left);
print2(p->right);
}
}
void print3()
{
int i;
for(i=0; i<128; i++){
if(HCode[i][0] != 0){
switch(i){
case 0: printf("NUL:");break;
case ' ': printf("SP:");break;
case '\t': printf("TAB:");break;
case '\n': printf("CR:");break;
default: printf("%c:",i); break;
}
printf("%s\n",HCode[i]);
}
}
}
void print4()
{
long int in_size, out_size;
fseek(Src,0,SEEK_END);
fseek(Obj,0,SEEK_END);
in_size = ftell(Src);
out_size = ftell(Obj);
printf("\n原文件大小:%ldB\n",in_size);
printf("压缩后文件大小:%ldB\n",out_size);
printf("压缩率:%.2f%%\n",(float)(in_size-out_size)*100/in_size);
} |
<template>
<header :class="['w-full', 'text-sm', headerHeightClass]">
<div class="fixed left-0 top-0 h-16 w-full bg-white">
<div
class="mx-auto flex h-full flex-nowrap border-b border-solid border-brand-gray-1 px-8"
>
<router-link
:to="{ name: 'Home' }"
class="flex h-full items-center text-xl"
>{{ projectName }}</router-link
>
<nav class="ml-24 h-full">
<ul class="flex h-full list-none">
<li
v-for="menuItem in menuItems"
:key="menuItem.text"
class="ml-9 h-full first:ml-0"
>
<router-link
:to="menuItem.url"
class="flex h-full items-center py-2.5"
>{{ menuItem.text }}</router-link
>
</li>
</ul>
</nav>
<div class="ml-auto flex h-full items-center">
<action-button text="2023.11.13 일 기준" type="secondary" />
</div>
</div>
</div>
</header>
</template>
<script>
import ActionButton from "@/components/Shared/ActionButton.vue";
export default {
name: "MainNav",
components: { ActionButton: ActionButton },
data() {
return {
projectName: "PressLeaderBoard",
menuItems: [
{ text: "종합지", url: "/category/종합지" },
{ text: "방송/통신사", url: "/category/방송-통신사" },
{ text: "경제지", url: "/category/경제지" },
{ text: "인터넷/IT지", url: "/category/인터넷-IT지" },
{ text: "매거진", url: "/category/매거진" },
{ text: "전문지", url: "/category/전문지" },
{ text: "지역지", url: "/category/지역지" },
],
isLoggedIn: false,
};
},
computed: {
headerHeightClass() {
return {
"h-16": !this.isLoggedIn,
"h-32": this.isLoggedIn,
};
},
},
};
</script> |
package main
import (
"fmt"
"log"
"net"
"context"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
posts "grpc-example/server/posts"
)
var (
serverURL = "localhost:10000"
portServer = 10000
)
type Server struct {
posts.UnimplementedPostServiceServer
}
func (s *Server) GetPosts(ctx context.Context, in *posts.Empty) (*posts.PostList, error) {
log.Println("GetPosts")
return &posts.PostList{
Posts: []*posts.Post{
&posts.Post{
Id: 1,
Title: "Titulo 1",
Text: "bla bla bla",
},
&posts.Post{
Id: 2,
Title: "Titulo 2",
Text: "bla bla bla",
},
},
}, nil
}
func main() {
fmt.Println("Server running on", serverURL)
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", portServer))
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := Server{}
grpcServer := grpc.NewServer()
posts.RegisterPostServiceServer(grpcServer, &s)
reflection.Register(grpcServer)
if err := grpcServer.Serve(lis); err != nil {
log.Fatalf("failed to serve: %s", err)
}
} |
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pdf/const/app_color.dart';
import 'package:pdf/view/DocumentScreen/document_screen.dart';
import 'package:pdf/view/Favorites/favorites.dart';
import 'package:pdf/view/RecentSreen/recent_screen.dart';
class CustomBottomNavigationBar extends StatefulWidget {
const CustomBottomNavigationBar({super.key});
@override
// ignore: library_private_types_in_public_api
_CustomBottomNavigationBarState createState() =>
_CustomBottomNavigationBarState();
}
class _CustomBottomNavigationBarState extends State<CustomBottomNavigationBar> {
int _currentIndex = 0;
final List<Widget> _screens = [
MyDocumentScreen(),
MyFavoritesScreen(),
MyRecentScreen(),
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: _screens[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: (index) {
setState(() {
_currentIndex = index;
});
},
backgroundColor: Color(0xffFED766),
selectedItemColor: Colors.blue,
items: [
BottomNavigationBarItem(
icon: Container(
padding:
EdgeInsets.only(top: 7.h, bottom: 7.h, right: 7.w, left: 7.w),
decoration: ShapeDecoration(
color: AppColors.mutiRed,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5)),
),
child: Icon(
Icons.description,
color: _currentIndex == 0 ? Colors.blue : Colors.white,
),
),
label: 'Document',
),
BottomNavigationBarItem(
icon: Container(
padding:
EdgeInsets.only(top: 7.h, bottom: 7.h, right: 7.w, left: 7.w),
decoration: ShapeDecoration(
color: AppColors.mutiRed,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5)),
),
child: Icon(
Icons.favorite,
color: _currentIndex == 1 ? Colors.blue : Colors.white,
),
),
label: 'Favorites',
),
BottomNavigationBarItem(
icon: Container(
padding:
EdgeInsets.only(top: 7.h, bottom: 7.h, right: 7.w, left: 7.w),
decoration: ShapeDecoration(
color: AppColors.mutiRed,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5)),
),
child: Icon(
Icons.access_time,
color: _currentIndex == 2 ? Colors.blue : Colors.white,
),
),
label: 'Recent',
),
],
),
);
}
} |
/*
* Copyright (C) 2010 SL-King d.o.o
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of version 2.1 of the GNU Lesser
* General Public License as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _c_KGKMLCONNECTIONCAPABILITIES_H
#define _c_KGKMLCONNECTIONCAPABILITIES_H
/// \brief
/// The FdoIConnectionCapabilities interface declares the feature provider's capabilities.
class c_KgKmlConnectionCapabilities : public FdoIConnectionCapabilities
{
public:
c_KgKmlConnectionCapabilities ();
protected:
virtual ~c_KgKmlConnectionCapabilities ();
protected:
virtual void Dispose ();
public:
/// \brief
/// Gets an FdoThreadCapability value that declares the feature provider's level of thread safety.
///
/// \return
/// Returns the connection thread capability.
///
FDOKGKML_API virtual FdoThreadCapability GetThreadCapability();
/// \brief
/// Gets the spatial context extent types supported by the feature provider.
///
/// \param length
/// Output the number of spatial context types.
///
/// \return
/// Returns the list of spatial context extent types.
///
FDOKGKML_API virtual FdoSpatialContextExtentType* GetSpatialContextTypes(FdoInt32& Length);
/// \brief
/// Determines if the feature provider supports persistent locking.
///
/// \return
/// Returns true if the feature provider supports persistent locking.
///
FDOKGKML_API virtual bool SupportsLocking();
/// \brief
/// Gets an array of the FdoLockType values supported by the feature provider.
///
/// \param size
/// Output the number of lock types
///
/// \return
/// Returns the list of lock types
///
FDOKGKML_API virtual FdoLockType* GetLockTypes(FdoInt32& Size);
/// \brief
/// Determines if the feature provider supports connection timeout.
///
/// \return
/// Returns true if the feature provider supports connection timeout.
///
FDOKGKML_API virtual bool SupportsTimeout();
/// \brief
/// Determines if the feature provider supports transactions.
///
/// \return
/// Returns true if the feature provider supports transactions.
///
FDOKGKML_API virtual bool SupportsTransactions();
/// \brief
/// Determines if the feature provider supports save point.
///
/// \return
/// Returns true if the feature provider supports save point.
///
FDOKGKML_API virtual bool SupportsSavePoint();
/// \brief
/// Determines true if the feature provider supports long transactions.
///
/// \return
/// Returns true if the feature provider supports long transactions.
///
FDOKGKML_API virtual bool SupportsLongTransactions();
/// \brief
/// Determines if the feature provider supports SQL commands.
///
/// \return
/// Returns true if the feature provider supports SQL commands.
///
FDOKGKML_API virtual bool SupportsSQL();
/// \brief
/// Determines if the feature provider supports XML configuration.
///
/// \return
/// Returns true if the feature provider supports the setting of a configuration.
///
FDOKGKML_API virtual bool SupportsConfiguration();
/// \brief
/// Determines if the provider supports multiple spatial contexts.
///
/// \return
/// Returns true if the provider supports multiple spatial contexts.
///
FDOKGKML_API virtual bool SupportsMultipleSpatialContexts();
/// \brief
/// Determines if the provider supports specifying the coordinate system by name or ID without specifying the WKT
/// when creating a new spatial context.
///
/// \return
/// Returns true if the provider supports specifying the coordinate system by name or ID without specifying the WKT
/// when creating a new spatial context.
///
FDOKGKML_API virtual bool SupportsCSysWKTFromCSysName();
#ifdef _FDO_3_2
/// \brief
/// Determines if write is supported by the provider or by the datastore depending on whether this request is at
/// the provider or datastore level.
///
/// \return
/// Returns true if write is supported by the provider or by the datastore depending on whether this request is at
/// the provider or datastore level.
FDOKGKML_API virtual bool SupportsWrite();
/// \brief
/// Determines if the provider or datastore can support more than one user writing to a single datastore at
/// one time.
///
/// \return
/// Returns true if the provider or datastore can support more than one user writing to a single datastore at
/// one time.
FDOKGKML_API virtual bool SupportsMultiUserWrite();
/// \brief
/// Determines if the provider can support the flush function. Flush is used to write any outstanding data
/// to the datastore. This is mainly used by the file based providers to ensure that any cached data is writen to the file.
///
/// \return
/// Returns true if the provider or datastore can support the flush function.
///
FDOKGKML_API virtual bool SupportsFlush();
#endif
};
#endif |
// Copyright 2024 out of sCope team - Michał Ogiński
#pragma once
#include "CoreMinimal.h"
#include "UI/ObsidianWidgetController.h"
#include "GameplayTagContainer.h"
#include "ObsidianTypes/UserIterface/ObsidianUIEffectClassification.h"
#include "ObsidianTypes/UserIterface/ObsidianUIData.h"
#include "MainOverlayWidgetController.generated.h"
class UOStackingDurationalEffectInfo;
class UObsidianDurationalEffectInfo;
class UObsidianAbilitySystemComponent;
class UObsidianEffectInfoBase;
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnAttributeValueChangedSignature, float, NewValue);
UENUM(BlueprintType)
enum class EObsidianInfoWidgetType : uint8
{
EIWT_SimpleEffectInfo UMETA(DisplayName = "Simple Effect Info"),
EIWT_DurationalEffectInfo UMETA(DisplayName = "Durational Effect Info"),
EIWT_StackingEffectInfo UMETA(DisplayName = "Stacking Effect Info"),
EIWT_StackingDurationalEffectInfo UMETA(DisplayName = "Stacking Durational Effect Info"),
EIWT_MAX UMETA(DisplayName = "Default MAX")
};
USTRUCT(BlueprintType)
struct FObsidianEffectUIDataWidgetRow : public FTableRowBase
{
GENERATED_BODY()
public:
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly)
EObsidianInfoWidgetType InfoWidgetType = EObsidianInfoWidgetType::EIWT_SimpleEffectInfo;
UPROPERTY(EditAnywhere, BlueprintReadOnly)
FGameplayTag EffectTag = FGameplayTag();
UPROPERTY(EditAnywhere, BlueprintReadOnly)
EObsidianUIEffectClassification EffectClassification = EObsidianUIEffectClassification::EUEC_NoClassification;
UPROPERTY(EditAnywhere, BlueprintReadOnly)
FText EffectName = FText();
UPROPERTY(EditAnywhere, BlueprintReadOnly)
FText EffectDesc = FText();
UPROPERTY(EditAnywhere, BlueprintReadOnly)
TObjectPtr<UTexture2D> EffectImage = nullptr;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, meta=(EditCondition="InfoWidgetType == EObsidianInfoWidgetType::EIWT_SimpleEffectInfo", EditConditionHides))
TSubclassOf<UObsidianEffectInfoBase> SimpleEffectWidget;
/** Indicates that this effect is an Aura Gameplay Ability that will be cleared manually */
UPROPERTY(EditAnywhere, BlueprintReadOnly, meta=(EditCondition="InfoWidgetType == EObsidianInfoWidgetType::EIWT_SimpleEffectInfo", EditConditionHides))
bool bAuraEffect = false;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, meta=(EditCondition="InfoWidgetType == EObsidianInfoWidgetType::EIWT_DurationalEffectInfo", EditConditionHides))
TSubclassOf<UObsidianDurationalEffectInfo> DurationalEffectWidget;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, meta=(EditCondition="InfoWidgetType == EObsidianInfoWidgetType::EIWT_StackingEffectInfo", EditConditionHides))
TSubclassOf<UObsidianEffectInfoBase> StackingEffectWidget;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, meta=(EditCondition="InfoWidgetType == EObsidianInfoWidgetType::EIWT_StackingDurationalEffectInfo", EditConditionHides))
TSubclassOf<UOStackingDurationalEffectInfo> StackingDurationalEffectWidget;
UPROPERTY(BlueprintReadOnly, meta = (AllowPrivateAccess = true))
float EffectDuration = 0.f;
};
/** Broadcasts DataTable Row that corresponds to a given asset tag */
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FEffectUIDataWidgetRow, FObsidianEffectUIDataWidgetRow, Row);
/** Broadcasts DataTable Row that corresponds to a given asset tag as well as the stacking information */
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FStackingEffectUIDataWidgetRow, FObsidianEffectUIDataWidgetRow, Row, FObsidianEffectUIStackingData, StackingData);
/** Delegate used for notifying Progress Globes to display the healing/replenish amount */
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FEffectUIGlobeData, const float&, EffectDuration, const float&, EffectMagnitude);
DECLARE_DYNAMIC_DELEGATE_OneParam(FOnAuraWidgetDestructionInfoReceived, const FGameplayTag, WidgetTag);
/**
*
*/
UCLASS(BlueprintType, Blueprintable)
class OBSIDIAN_API UMainOverlayWidgetController : public UObsidianWidgetController
{
GENERATED_BODY()
public:
// ~ Start of UObsidianWidgetController
virtual void OnWidgetControllerSetupCompleted() override;
// ~ End of UObsidianWidgetController
UFUNCTION(BlueprintCallable, BlueprintPure=false, Category = "Obsidian|Health")
void UpdateHealthInfoGlobe(const float& Magnitude) const;
UFUNCTION(BlueprintCallable, BlueprintPure=false, Category = "Obsidian|Mana")
void UpdateManaInfoGlobe(const float& Magnitude) const;
virtual void SetInitialAttributeValues() const override;
public:
UPROPERTY(BlueprintAssignable, Category = "Obsidian|Attributes|Health")
FOnAttributeValueChangedSignature OnHealthChangedDelegate;
UPROPERTY(BlueprintAssignable, Category = "Obsidian|Attributes|Health")
FOnAttributeValueChangedSignature OnMaxHealthChangedDelegate;
UPROPERTY(BlueprintAssignable, Category = "Obsidian|Attributes|Mana")
FOnAttributeValueChangedSignature OnManaChangedDelegate;
UPROPERTY(BlueprintAssignable, Category = "Obsidian|Attributes|Mana")
FOnAttributeValueChangedSignature OnMaxManaChangedDelegate;
UPROPERTY(BlueprintAssignable, Category = "Obsidian|Attributes|EnergyShield")
FOnAttributeValueChangedSignature OnEnergyShieldChangedDelegate;
UPROPERTY(BlueprintAssignable, Category = "Obsidian|Attributes|MaxEnergyShield")
FOnAttributeValueChangedSignature OnMaxEnergyShieldChangedDelegate;
UPROPERTY(BlueprintAssignable, Category = "Obsidian|Attributes|EnergyShield")
FOnAttributeValueChangedSignature OnSpecialResourceChangedDelegate;
UPROPERTY(BlueprintAssignable, Category = "Obsidian|Attributes|MaxEnergyShield")
FOnAttributeValueChangedSignature OnMaxSpecialResourceChangedDelegate;
UPROPERTY(BlueprintAssignable, Category = "Obsidian|UIData")
FEffectUIDataWidgetRow EffectUIDataWidgetRowDelegate;
UPROPERTY(BlueprintAssignable, Category = "Obsidian|UIData")
FEffectUIGlobeData EffectUIHealthGlobeDataDelegate;
UPROPERTY(BlueprintAssignable, Category = "Obsidian|UIData")
FEffectUIGlobeData EffectUIManaGlobeDataDelegate;
UPROPERTY(BlueprintAssignable, Category = "Obsidian|UIData")
FStackingEffectUIDataWidgetRow EffectStackingUIDataDelegate;
FOnAuraWidgetDestructionInfoReceived OnAuraWidgetDestructionInfoReceivedDelegate;
protected:
virtual void HandleBindingCallbacks(UObsidianAbilitySystemComponent* ObsidianASC) override;
template<typename T>
T* GetDataTableRowByTag(UDataTable* DataTable, const FGameplayTag& Tag);
void HealthChanged(const FOnAttributeChangeData& Data) const;
void MaxHealthChanged(const FOnAttributeChangeData& Data) const;
void EnergyShieldChanged(const FOnAttributeChangeData& Data) const;
void MaxEnergyShieldChanged(const FOnAttributeChangeData& Data) const;
void ManaChanged(const FOnAttributeChangeData& Data) const;
void MaxManaChanged(const FOnAttributeChangeData& Data) const;
void SpecialResourceChanged(const FOnAttributeChangeData& Data) const;
void MaxSpecialResourceChanged(const FOnAttributeChangeData& Data) const;
protected:
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Obsidian|UIData")
TObjectPtr<UDataTable> UIEffectDataWidgetTable;
/** Hero Set */
FDelegateHandle ManaChangedDelegateHandle;
FDelegateHandle MaxManaChangedDelegateHandle;
FDelegateHandle SpecialResourceChangedDelegateHandle;
FDelegateHandle MaxSpecialResourceChangedDelegateHandle;
/** Common Set */
FDelegateHandle HealthChangedDelegateHandle;
FDelegateHandle MaxHealthChangedDelegateHandle;
FDelegateHandle EnergyShieldChangedDelegateHandle;
FDelegateHandle MaxEnergyShieldChangedDelegateHandle;
private:
UFUNCTION()
void DestroyAuraWidget(const FGameplayTag AuraWidgetTag);
};
template <typename T>
T* UMainOverlayWidgetController::GetDataTableRowByTag(UDataTable* DataTable, const FGameplayTag& Tag)
{
return DataTable->FindRow<T>(Tag.GetTagName(), TEXT(""));
} |
import { action, persist, thunk } from 'easy-peasy';
import getPlaylist from '../api';
const playlistModel = persist(
{
data: {},
error: '',
isLoading: false,
addPlaylist: action((state, payload) => {
state.data[payload.playlistId] = payload;
}),
deletePlaylist: action((state, payload) => {
delete state.data[payload];
}),
setLoading: action((state, payload) => {
state.isLoading = payload;
}),
setError: action((state, payload) => {
state.error = payload;
}),
getPlaylist: thunk(
async (
{ addPlaylist, setLoading, setError },
playlistId,
{ getState }
) => {
setError('');
if (getState().data[playlistId]) {
return;
}
setLoading(true);
try {
const playlist = await getPlaylist(playlistId);
addPlaylist(playlist);
} catch (e) {
setError(e.response?.data?.error?.message);
} finally {
setLoading(false);
}
}
),
},
{
storage: 'localStorage',
}
);
export default playlistModel; |
import {Component, OnDestroy, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {Store} from '@ngrx/store';
import {Observable, Subscription} from 'rxjs';
import {LoderStatus} from 'src/app/store/actions/loading.actions';
import {getBusLineSuccess} from 'src/app/store/selectors/bus-line.selectors';
import {AppState} from 'src/app/store/state/app.state';
import {BusLineDetail} from '../../models/bus-line.model';
import * as BusActions from '../../../store/actions/bus-line.actions';
import {getBusLineError, getLoader,} from '../../../store/selectors/bus-line.selectors';
import {TableConfig} from "../shared/table-config";
@Component({
selector: 'app-bus-line',
templateUrl: './bus-line.component.html',
styleUrls: [
'./bus-line.component.scss',
'../shared/css-base/css-base.component.scss',
],
})
export class BusLineComponent extends TableConfig implements OnInit, OnDestroy {
public busLine$: Observable<BusLineDetail[]>;
public busLine!: BusLineDetail[];
public busLineError$: Observable<string>;
public busLineError!: string;
public isLoading$: Observable<boolean>;
public subscription: Subscription[] = [];
constructor(public router: Router, private store: Store<AppState>) {
super(router);
this.busLine$ = this.store.select(getBusLineSuccess);
this.busLineError$ = this.store.select(getBusLineError);
this.isLoading$ = this.store.select(getLoader);
}
public ngOnInit(): void {
this.actionsPageInitial();
this.dataLineBus();
this.tableConfig();
}
public ngOnDestroy(): void {
this.dtTrigger.unsubscribe();
this.subscription.forEach((interrupted) => interrupted.unsubscribe());
}
public actionsPageInitial(): void {
this.store.dispatch(LoderStatus());
this.store.dispatch(BusActions.loadBusLines());
}
public dataLineBus(): void {
this.subscription.push(
this.busLine$.subscribe((data) => {
this.busLine = data;
this.dtTrigger.next();
})
);
this.subscription.push(
this.busLineError$.subscribe((error) => {
this.busLineError = error;
this.dtTrigger.next();
})
);
}
} |
<template>
<q-card class="my-card" :style="style">
<q-card-section :horizontal="!$q.platform.is.mobile">
<q-img v-if="Image" :src="ImgSrc" basic v-on:click.stop="openSelf()">
<!-- Si tiene imagen --->
<template v-if="$q.platform.is.mobile">
<!-- Y es movil -->
<q-btn
:ripple="false"
round
padding="sm sm"
class="absolute-top-right q-ma-xs"
text-color="white"
unelevated
icon="more_vert"
size="20px"
style="background:rgba(0, 0, 0, 0.47);"
>
<q-menu anchor="center right" self="center left">
<q-list bordered style="min-width: 100px">
<q-item
v-if="Type === 'Sheet'"
clickable
v-close-popup
v-ripple
@click="editSelf()"
>
<q-item-section avatar>
<q-icon name="edit" color="blue"></q-icon>
</q-item-section>
<q-item-section>Editar</q-item-section>
</q-item>
<q-item clickable v-close-popup v-ripple @click="renameSelf()">
<q-item-section avatar>
<q-icon name="badge" color="green"></q-icon>
</q-item-section>
<q-item-section>Renombrar</q-item-section>
</q-item>
<q-item clickable v-close-popup v-ripple @click="modifySelf()">
<q-item-section avatar>
<q-icon name="settings_suggest" color="secondary"></q-icon>
</q-item-section>
<q-item-section>Modificar ajustes</q-item-section>
</q-item>
<q-item clickable v-close-popup v-ripple @click="exportSelf()">
<q-item-section avatar>
<q-icon name="publish" color="purple"></q-icon>
</q-item-section>
<q-item-section>Exportar</q-item-section>
</q-item>
<q-separator />
<q-item clickable v-close-popup v-ripple>
<q-item-section avatar>
<q-icon
name="delete"
color="red"
@click.stop="deleteSelf()"
></q-icon>
</q-item-section>
<q-item-section>Eliminar</q-item-section>
</q-item>
</q-list>
</q-menu>
</q-btn>
</template>
<div class="absolute-bottom text-subtitle2 text-center">
{{ Name }}
</div>
<template v-slot:error>
<div class="absolute-full flex flex-center bg-negative text-white">
Cannot load image
</div>
</template>
</q-img>
<!-- Fin "Si tiene imagen" -->
<q-avatar
v-if="!Image"
:icon="Icon"
size="200px"
:color="Color"
:text-color="getWhiteIfColored"
style="padding: 0 0; margin:0;"
square
v-on:click.stop="openSelf()"
>
<!-- Si no tiene imagen --->
<template v-if="$q.platform.is.mobile">
<!-- Y es movil -->
<q-btn
:ripple="false"
round
padding="sm sm"
class="absolute-top-right"
:text-color="reverseDarkModeColor"
unelevated
icon="more_vert"
size="20px"
style="background:rgba(0, 0, 0, 0.47);"
>
<q-menu anchor="center right" self="center left">
<q-list bordered style="min-width: 100px">
<q-item
v-if="Type === 'Sheet'"
clickable
v-close-popup
v-ripple
@click="editSelf()"
>
<q-item-section avatar>
<q-icon name="edit" color="blue"></q-icon>
</q-item-section>
<q-item-section>Editar</q-item-section>
</q-item>
<q-item clickable v-close-popup v-ripple @click="renameSelf()">
<q-item-section avatar>
<q-icon name="badge" color="green"></q-icon>
</q-item-section>
<q-item-section>Renombrar</q-item-section>
</q-item>
<q-item clickable v-close-popup v-ripple @click="modifySelf()">
<q-item-section avatar>
<q-icon name="settings_suggest" color="secondary"></q-icon>
</q-item-section>
<q-item-section>Modificar ajustes</q-item-section>
</q-item>
<q-item clickable v-close-popup v-ripple @click="exportSelf()">
<q-item-section avatar>
<q-icon name="publish" color="purple"></q-icon>
</q-item-section>
<q-item-section>Exportar</q-item-section>
</q-item>
<q-separator />
<q-item
clickable
v-close-popup
v-ripple
@click.stop="deleteSelf()"
>
<q-item-section avatar>
<q-icon name="delete" color="red"></q-icon>
</q-item-section>
<q-item-section>Eliminar</q-item-section>
</q-item>
</q-list>
</q-menu>
</q-btn>
</template>
<div class="absolute-bottom text-subtitle2 text-center">{{ Name }}</div>
</q-avatar>
<template v-if="!$q.platform.is.mobile">
<!-- Si no es movil --->
<q-btn
:ripple="false"
round
padding="xs xs"
class="absolute-top-right q-mr-xl q-mt-xs"
:text-color="reverseDarkModeColor"
unelevated
icon="more_vert"
size="20px"
style="background:rgba(0, 0, 0, 0.47);margin-right:55px"
>
<q-menu anchor="center right" self="center left">
<q-list style="min-width: 100px">
<q-item
v-if="Type == 'Folder'"
clickable
v-close-popup
v-ripple
@click="importSelf()"
>
<q-item-section avatar>
<q-icon name="get_app" color="orange"></q-icon>
</q-item-section>
<q-item-section>Importar</q-item-section>
</q-item>
<q-item clickable v-close-popup v-ripple @click="exportSelf()">
<q-item-section avatar>
<q-icon name="publish" color="purple"></q-icon>
</q-item-section>
<q-item-section>Exportar</q-item-section>
</q-item>
</q-list>
</q-menu>
</q-btn>
<q-card-actions
vertical
class="justify-around q-pa-xs"
:style="getDarkModeBackground"
>
<q-btn
v-if="Type === 'Sheet'"
flat
round
icon="edit"
color="blue"
@click="editSelf()"
/>
<q-btn flat round icon="badge" color="green" @click="renameSelf()" />
<q-btn
flat
round
icon="settings_suggest"
color="secondary"
@click="modifySelf()"
/>
<q-separator />
<q-btn
flat
round
icon="delete"
color="red"
@click.stop="deleteSelf()"
/>
</q-card-actions>
</template>
</q-card-section>
<ModifyContentDialog
:oname="Name"
:oicon="Icon"
:ocolor="Color"
:visible="mcdialog"
></ModifyContentDialog>
</q-card>
</template>
<script>
import { qBreadCumbsEl } from 'src/js/Content';
import { EventBus } from 'src/js/vue-bus';
import ModifyContentDialog from 'components/dialogs/ModifyContentDialog';
import { searchStringInArray } from 'src/js/ValidationHelpers';
let UserPrefs = require('src/js/UserPrefs.js');
export default {
name: 'CardGrid',
data: function() {
return {
mcdialog: false
};
},
props: {
Id: {
type: String,
default: 'Error'
},
Name: {
type: String,
default: 'Error'
},
Image: {
type: Boolean,
default: false
},
Type: {
type: String,
default: function() {
return 'Error';
},
validator: function(newValue) {
if (newValue != 'Folder' || 'Sheet') {
newValue = 'Error';
}
return newValue;
}
},
Icon: {
type: String,
default: function() {
let icon;
switch (this.Type) {
case 'Folder':
icon = 'folder';
break;
case 'Sheet':
icon = 'description';
break;
default:
icon = 'broken_image';
break;
}
return icon;
}
},
Color: {
type: String
},
UsedNames: {
type: Array,
default: () => UserPrefs.TemporalStorage.getItem('sCurrentNames')
}
},
components: {
ModifyContentDialog
},
methods: {
editSelf: function() {
const mode = this.$q.platform.is.mobile ? 'Mobile' : '';
const fm = require(`src/js/FileManager${mode}.js`);
if (mode == '') {
//Si Electron
UserPrefs.TemporalStorage.set('sEditName', this.Name);
UserPrefs.TemporalStorage.set(
'sEditPath',
UserPrefs.TemporalStorage.getItem('sRealPath') +
'/' +
this.Name +
'.md'
);
UserPrefs.TemporalStorage.set('sEditIcon', this.Icon);
UserPrefs.TemporalStorage.set('sLastSheetColor', this.Color);
this.$router.push('/editor');
} else {
//TODO CAPACITOR
}
},
deleteSelf: async function() {
const mode = this.$q.platform.is.mobile ? 'Mobile' : '';
const fm = require(`src/js/FileManager${mode}.js`);
const assosiatedPath =
UserPrefs.TemporalStorage.getItem('sRealPath') + '/' + this.Name;
this.$q
.dialog({
title: 'Confirmar',
message: `¿Seguro que desea eliminar el elemento ${this.Name}?`,
cancel: true
})
.onOk(async () => {
if (mode == '') {
//Si Electron
await fm.removeFolder(assosiatedPath);
EventBus.$emit('reRenderContent');
this.$q.notify({
type: 'info',
message: `"${this.Name}" ha sido borrado.`
});
} else {
//TODO CAPACITOR
}
});
},
renameSelf: async function() {
const mode = this.$q.platform.is.mobile ? 'Mobile' : '';
const fm = require(`src/js/FileManager${mode}.js`);
const assosiatedPath = UserPrefs.TemporalStorage.getItem('sRealPath');
if (mode == '') {
//Si Electron
this.$q
.dialog({
title: 'Renombrar',
message: '¿A que lo quieres renombrar?',
prompt: {
model: '',
isValid: val =>
val.length > 0 &&
val != 'media' &&
val != 'mythickeeper.dat' &&
!searchStringInArray(val, this.UsedNames),
type: 'text'
},
cancel: true,
persistent: true
})
.onOk(async data => {
let oldName = this.Name;
if (this.Type == 'Folder') {
await fm.renameFolder(
assosiatedPath + '/' + this.Name,
assosiatedPath + '/' + data
);
} else {
await fm.renameSheet(
assosiatedPath + '/' + this.Name,
assosiatedPath + '/' + data
);
}
EventBus.$emit('reRenderContent');
this.$q.notify({
type: 'info',
message: `"${oldName}" ha sido renombrado a "${data}"`
});
});
} else {
//TODO CAPACITOR
}
},
openSelf() {
const mode = this.$q.platform.is.mobile ? 'Mobile' : '';
const fm = require(`src/js/FileManager${mode}.js`);
UserPrefs.TemporalStorage.set('sEditName', this.Name);
UserPrefs.TemporalStorage.set('sEditIcon', this.Icon);
UserPrefs.TemporalStorage.set('sLastSheetColor', this.Color);
UserPrefs.TemporalStorage.set('sLastFolderColor', this.Color);
let realpath = UserPrefs.TemporalStorage.getItem('sRealPath');
if (this.Type == 'Folder') {
UserPrefs.TemporalStorage.set('sRealPath', realpath + '/' + this.Name);
EventBus.$emit('pushBread', new qBreadCumbsEl(this.Name, this.Icon));
EventBus.$emit('reRenderContent');
if (UserPrefs.get('kDynamicTitle')) {
EventBus.$emit(
'changeTitle',
UserPrefs.TemporalStorage.getItem('sEditName'),
UserPrefs.TemporalStorage.getItem('sEditIcon'),
UserPrefs.TemporalStorage.getItem('sLastSheetColor')
);
} else {
EventBus.$emit(
'changeTitle',
'default',
UserPrefs.TemporalStorage.getItem('sEditIcon')
);
}
} else {
UserPrefs.TemporalStorage.set(
'sEditPath',
realpath + '/' + this.Name + '.md'
);
UserPrefs.TemporalStorage.set('sLastView', 'Grid');
this.$router.push('/preview');
}
},
modifySelf() {
this.mcdialog = true;
},
enableReEdit() {
this.mcdialog = false;
},
exportSelf: async function() {
const mode = this.$q.platform.is.mobile ? 'Mobile' : '';
const fm = require(`src/js/FileManager${mode}.js`);
let thispath;
if (this.Type == 'Folder') {
thispath =
UserPrefs.TemporalStorage.getItem('sRealPath') + '/' + this.Name;
} else {
thispath =
UserPrefs.TemporalStorage.getItem('sRealPath') +
'/' +
this.Name +
'.md';
}
if (mode == '') {
//Si Electron
const {
ipcRenderer
} = /*this.$q.platform.is.mobile //Innecesario tanto rollo?
? ''
:*/ require('electron');
let DirectoryPath = '';
let selection = ipcRenderer.sendSync('showDirectoryGetter');
if (selection.canceled != true) {
//Si no ha sido cancelado
DirectoryPath = selection.filePaths[0];
await fm.copy(thispath, DirectoryPath + '/');
this.$q.notify({
type: 'positive',
message: `Exportación completada.`
});
}
} else {
//TODO Capacitor
}
},
importSelf: async function() {
const mode = this.$q.platform.is.mobile ? 'Mobile' : '';
const fm = require(`src/js/FileManager${mode}.js`);
const thispath =
UserPrefs.TemporalStorage.getItem('sRealPath') + '/' + this.Name;
if (mode == '') {
//Si Electron
const {
ipcRenderer
} = /*this.$q.platform.is.mobile //Innecesario tanto rollo?
? ''
:*/ require('electron');
let DirectoryPath = '';
let selection = ipcRenderer.sendSync('showDirectoryGetter');
if (selection.canceled != true) {
//Si no ha sido cancelado
DirectoryPath = selection.filePaths[0];
await fm.copy(DirectoryPath, thispath);
this.$q.notify({
type: 'positive',
message: `Importación completada.`
});
}
} else {
//TODO Capacitor
}
}
},
computed: {
reverseDarkModeText: function() {
let color = 'text-black';
if (this.$q.dark.isActive == true) {
color = 'text-white';
}
return color;
},
reverseDarkModeColor: function() {
let color = 'black';
if (this.$q.dark.isActive == true || this.Color != undefined) {
color = 'white';
}
return color;
},
getDarkModeBackground: function() {
let color = this.$q.dark.isActive ? '#1D1D1D' : 'white';
color = `background:${color};`;
return color;
},
getWhiteIfColored: function() {
let color = '';
if (this.Color != undefined) {
color = 'white';
}
return color;
},
style: function() {
let style = '';
if (this.Color != undefined) {
style = 'background: ' + this.Color + ';';
}
return style;
},
ImgSrc: function() {
if (this.Image == true) {
return require(UserPrefs.get('kMediaFolderLocation') + '/' + this.Id);
} else {
return '';
}
}
},
mounted() {},
created() {
EventBus.$on('enableReEdit', this.enableReEdit);
},
beforeDestroy() {
EventBus.$off('enableReEdit', this.enableReEdit);
}
};
</script>
<style lang="sass" scoped>
.my-card
width: 100%
max-height: 210px
max-width: 250px
</style> |
import "./ExpenseForm.css";
import { useState } from "react";
const ExpenseForm = (props) => {
// const [enteredTitle, setEnteredTitle] = useState("");
// const [enterPrice, setEnteredPrice] = useState("");
// const [enterDate, setEnteredDate] = useState("");
const [userInput, setUserInput] = useState({
enteredTitle: "",
enteredPrice: "",
enteredDate: "",
});
const titleHandler = (event) => {
// setUserInput({
// ...userInput,
// EnteredTitle: event.target.value,
// });
setUserInput((prevState) => ({
...prevState,
enteredTitle: event.target.value,
}));
};
const priceHandler = (event) => {
setUserInput((prevState) => ({
...prevState,
enteredPrice: event.target.value,
}));
};
const dateHandler = (event) => {
setUserInput((prevState) => ({
...prevState,
enteredDate: event.target.value,
}));
};
const submitHandler = (event) => {
event.preventDefault();
const expenseData = {
title: userInput.enteredTitle,
amount: userInput.enteredPrice,
date: new Date(userInput.enteredDate),
};
// custom made to save data in its parent
props.onSaveExpenseData(expenseData);
//to clear the form after sumbitting
setUserInput({
enteredDate: "",
enteredPrice: "",
enteredTitle: "",
});
};
return (
<form onSubmit={submitHandler}>
<div className="new-expense__controls">
<div className="new-expense__control">
<label>Title</label>
<input
type="text"
value={userInput.enteredTitle}
onChange={titleHandler}
/>
</div>
<div className="new-expense__control">
<label>Price</label>
<input
type="number"
min="0.01"
step="0.01"
value={userInput.enteredPrice}
onChange={priceHandler}
/>
</div>
<div className="new-expense__control">
<label>Date</label>
<input
type="date"
min="2021-01-01"
max="2023-12-31"
value={userInput.enteredDate}
onChange={dateHandler}
/>
</div>
</div>
<div className="new-expense__actions">
<button type="submit">Add Expense</button>
</div>
</form>
);
};
export default ExpenseForm; |
import React, { useState } from 'react';
import {
View,
StyleSheet,
Text,
Button,
Image,
TouchableOpacity,
ScrollView,
} from 'react-native';
import Input from '../../components/Input';
import { Video, ResizeMode } from 'expo-av';
import * as ImagePicker from 'expo-image-picker';
import { colors } from '../../styles/constants';
type RewardType = {
title: string;
description: string;
value: number;
image: string;
};
type CreateRewardErrorsType = {
title: boolean;
description: boolean;
value: boolean;
};
const CreateReward = () => {
const [reward, setReward] = useState<RewardType>({
title: '',
description: '',
value: 0,
image: '',
});
const [errors, setErrors] = useState<CreateRewardErrorsType>({
title: false,
description: false,
value: false,
});
const [media, setMedia] = useState<string | null>(null);
const [mediaType, setMediaType] = useState<'image' | 'video' | undefined>();
const [status, setStatus] = useState({});
const pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
if (!result.canceled) {
setMedia(result.assets[0].uri);
setMediaType(result.assets[0].type);
}
};
const handleInputChange = (key: string, value: string | number) => {
setReward((prevReward) => ({
...prevReward,
[key]: value,
}));
};
const createRewardHandler = () => {
let tempErrors = {
title: false,
description: false,
value: false,
};
if (reward.title.trim().length === 0) {
tempErrors = { ...tempErrors, title: true };
}
if (reward.description.trim().length === 0) {
tempErrors = { ...tempErrors, description: true };
}
if (reward.value <= 0) {
tempErrors = { ...tempErrors, value: true };
}
if (Object.values(tempErrors).some((error) => error)) {
setErrors(tempErrors);
return;
}
setReward({
title: '',
description: '',
value: 0,
image: '',
});
setErrors({
title: false,
description: false,
value: false,
});
};
return (
<ScrollView style={styles.container}>
<Text style={styles.title}>Create a reward</Text>
<View style={styles.inputContainer}>
<Input
label="Title"
value={reward.title}
onChangeText={(value: string) => handleInputChange('title', value)}
error={errors.title}
errorMessage="Title cannot be empty"
labelStyle={{ fontSize: 20, textAlign: 'center' }}
placeholder="Enter a title"
/>
</View>
<View style={styles.inputContainer}>
<Input
label="Description"
value={reward.description}
onChangeText={(value: string) =>
handleInputChange('description', value)
}
error={errors.description}
errorMessage="Description cannot be empty"
labelStyle={{ fontSize: 20, textAlign: 'center' }}
placeholder="Enter a description"
/>
</View>
<View style={styles.inputContainer}>
<Input
label="Points cost"
value={reward.value.toString()}
onChangeText={(value: string) =>
handleInputChange('value', Number(value))
}
error={errors.value}
errorMessage="Reward value cannot be 0"
labelStyle={{ fontSize: 20, textAlign: 'center' }}
placeholder="Set the reward value"
type="number-pad"
/>
</View>
<View>
<Text style={styles.label}>Image / Video</Text>
<Button title="Pick an image" onPress={pickImage} />
{mediaType === 'image' && media && (
<Image source={{ uri: media }} style={styles.media} />
)}
{mediaType === 'video' && media && (
<Video
source={{ uri: media }}
style={styles.media}
resizeMode={ResizeMode.CONTAIN}
useNativeControls
isLooping
onPlaybackStatusUpdate={(status) => setStatus(() => status)}
/>
)}
</View>
<TouchableOpacity
style={styles.submitButton}
onPress={createRewardHandler}
>
<Text style={styles.submitText}>Create a challenge</Text>
</TouchableOpacity>
</ScrollView>
);
};
const styles = StyleSheet.create({
container: {
gap: 10,
backgroundColor: colors.background,
},
title: {
fontSize: 30,
textAlign: 'center',
marginTop: 10,
},
label: {
fontSize: 20,
textAlign: 'center',
},
inputContainer: { marginHorizontal: 25 },
media: {
width: '90%',
height: 200,
marginTop: 20,
alignSelf: 'center',
},
submitButton: {
borderWidth: 1,
borderColor: 'black',
padding: 10,
alignSelf: 'center',
marginTop: 15,
borderRadius: 8,
backgroundColor: colors.primary,
},
submitText: {
fontWeight: 'bold',
color: '#fff',
},
});
export default CreateReward; |
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Add User</title>
<link rel="stylesheet" href="../../assets/css/bootstrap.min.css" >
<link rel="stylesheet" href="../../assets/css/font-awesome.min.css" >
</head>
<body>
<div class="container mt-4 ">
<div class="row justify-content-center">
<div class="col-md-5">
<div class="card">
<div class="card-header" align="center">
<c:choose>
<c:when test="${users.id!= null}">
<h3>Edit User</h3>
</c:when>
<c:otherwise>
<h3>Add User</h3>
</c:otherwise>
</c:choose>
</div>
<div class="card-body">
<form class="form-horizontal" action="/user/addOrUpdateUser" method="post">
<div class="form-group">
<label for="full_name" class="cols-sm-2 control-label">Name</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"></span> <input type="text"
class="form-control" name="full_name"
id="full_name"
placeholder="Enter Your Name" required
value="${users.full_name }"/>
</div>
</div>
</div>
<div class="form-group">
<label for="email_id" class="cols-sm-2 control-label">Email
Id</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"></span> <input type="email"
class="form-control" name="email_id"
id="email_id"
placeholder="Enter Email Id" required
value="${users.email_id }"/>
</div>
</div>
</div>
<h6 align="center" style="color:red"><c:out value="${MailError}"/></h6>
<div class="form-group">
<label for="address" class="cols-sm-2 control-label">Address</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"></span> <input type="text"
class="form-control" name="address"
id="address"
placeholder="Enter Address" required
value="${users.address }"/>
</div>
</div>
</div>
<div class="form-group">
<label for="contact_number" class="cols-sm-2 control-label">Contact
Number</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"></span> <input type="number"
min="0" class="form-control"
name="contact_number"
id="contact_number"
placeholder="Contact Number" required
value="${users.contact_number }"/>
</div>
</div>
</div>
<h6 align="center" style="color:red"><c:out value="${ContactNumberError}"/></h6>
<div class="form-group">
<label for="name" class="cols-sm-2 control-label">User Name</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"></span> <input type="text"
class="form-control" name="name"
id="name"
placeholder="Enter User Name" required
value="${users.name }"/>
</div>
</div>
</div>
<h6 align="center" style="color:red"><c:out value="${NameError}"/></h6>
<c:if test="${users.id == null}">
<div class="form-group">
<label for="password" class="cols-sm-2 control-label">Password</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"></span> <input
type="password" class="form-control" name="password"
id="password" placeholder="Enter Password" required />
</div>
</div>
</div>
<div class="form-group">
<label for="confirm_password" class="cols-sm-2 control-label">Confirm Password</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"></span> <input
type="text" class="form-control" name="confirm_password"
id="confirm_password" placeholder="Enter Confirm Password" required />
</div>
</div>
</div>
</c:if>
<h6 align="center" style="color:red"><c:out value="${PasswordError}"/></h6>
<c:if test="${users.id!= null}">
<input type="hidden"
class="form-control" name="password" id="password"
placeholder="Enter Password" required
value="${users.password }" />
<input type="hidden"
class="form-control" name="password" id="password"
placeholder="Enter Password" required
value="${users.confirm_password }" />
</c:if>
<c:if test="${users.id == null}">
<div class="form-group " align="center" class="row">
<input type="submit" name="redirectValue" value="Add"
class="btn btn-primary">
<div class="form-group " align="right">
<a href="viewUser?redirectValue=view&id=1" title="Back"><i
class="fa fa-arrow-circle-left" aria-hidden="true" style="font-size:25px"></i></a>
</div>
</div>
</c:if>
<c:if test="${users.id!= null}">
<div class="form-group " align="center" class="row">
<input type="hidden" name="id" value=${users.id }><input
type="submit" name="redirectValue" value="Update"
class="btn btn-primary">
<div class="form-group " align="right">
<a href="/user/viewUser" title="Back"><i
class="fa fa-arrow-circle-left" aria-hidden="true" style="font-size:25px"></i></a>
</div>
</div>
</c:if>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html> |
require 'rails_helper'
describe Sideqik::V1::CodePools do
include UserMacros
include ApiMacros
context "as authorized user" do
login_user
describe "POST /accounts/n/pools" do
it "should create code pool for account" do
post_success "/accounts/#{account.id}/pools", name: 'These Codez'
expect(json_response['name']).to eq 'These Codez'
end
end
context "with existing code pools" do
let(:code_pool1) { create(:code_pool, account: account) }
let(:code_pool2) { create(:code_pool, account: account) }
before { code_pool1 && code_pool2 }
describe "GET /accounts/n/pools" do
it "should return code pools for account" do
get_success "/accounts/#{account.id}/pools"
res = json_response
expect(res.length).to eq 2
expect(res.map{|v| v['id']}).to eq [code_pool1, code_pool2].map(&:id).map(&:to_s)
end
end
describe "PUT /accounts/n/pools/n" do
it "should update code pool" do
post_success "/accounts/#{account.id}/pools/#{code_pool1.id}", codes: "a\nb\nc\nd"
expect(json_response['counts']['total']).to eq 4
end
end
describe "DELETE /accounts/n/pools/n" do
it "should delete code pool" do
expect(account.code_pools.count).to eq 2
delete_success "/accounts/#{account.id}/pools/#{code_pool1.id}"
expect(account.code_pools.count).to eq 1
end
end
end
end
end |
import "dart:convert";
import 'package:apka_s_api/data/ApiKey.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'save.dart';
class Api {
final String period;
Api(this.period);
Future<String> readJsonFile(String path) async {
try {
return await rootBundle.loadString(path);
} catch (e) {
return e.toString();
}
}
Future<List<Coin>?> GetCoins() async {
var url = 'https://api.coinranking.com/v2/coins?timePeriod=$period&x-access-token=${ApiKey().getApiKey}';
Map<String, dynamic>jsonData = <String, dynamic>{};
try {
var save = MySave();
final response = await http.get(Uri.parse(url));
jsonData = json.decode(response.body);
save.saveJson(period, response.body);
save.saveTime(period);
} catch (e) {
return null;
}
return jsonToCoin(jsonData);
}
jsonToCoin(Map<String, dynamic>jsonData) {
List<Coin> result = <Coin>[];
String status = jsonData["status"];
if (status == "success") {
var coins = jsonData["data"]["coins"];
for (var i = 0; i < coins.length; ++i) {
String symbol = "(bez symbolu)";
if (coins[i]["symbol"] != null) {
symbol = coins[i]["symbol"];
}
String name = "(bez názvu)";
if(coins[i]["name"] != null) {
name = coins[i]["name"];
}
String icon = "";
if (coins[i]["iconUrl"] != null) {
icon = coins[i]["iconUrl"];
}
String color="";
if(coins[i]["color"] != null) {
color = coins[i]["color"];
} else {
color = "#000000";
}
var sparklines = coins[i]["sparkline"];
double actual = double.parse(coins[i]["price"]);
List<FlSpot> prices = <FlSpot>[];
int l = 0;
for (int j = 0; j < sparklines.length; ++j) {
if(sparklines[j] != null ) {
double k = double.parse((j-l).toString());
prices.add(FlSpot(k, double.parse(sparklines[j])));
} else {
++l;
}
}
Color trueColor = Color(
int.parse(color.substring(1, 7), radix: 16) + 0x44000000);
result.add(Coin(symbol, name, icon, trueColor, prices, actual, false));
}
} else {
debugPrint("Error: ${jsonData["error"]}");
}
return result;
}
}
class Coin {
final String symbol;
final String name;
final String icon;
final Color color;
final List<FlSpot> prices;
final double actualPrice;
bool active;
Coin(this.symbol, this.name, this.icon, this.color, this.prices, this.actualPrice, this.active);
} |
package ru.stqa.mantis.manager;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.Objects;
import java.util.Properties;
public class ApplicationManager {
private WebDriver driver;
private String string;
private Properties properties;
private SessionHelper sessionHelper;
private HttpSessionHelper httpSessionHelper;
private JamesCliHelper jamesCliHelper;
private MailHelper mailHelper;
private JamesApiHelper jamesApiHelper;
private DeveloperMailHelper developerMailHelper;
private RestApiHelper restApiHelper;
private SoapApiHelper soapApiHelper;
public void init(String browser,Properties properties) {
this.string = browser;
this.properties = properties;
}
public WebDriver driver() {
if (driver == null) {
if ("chrome".equals(string)) {
this.driver = new ChromeDriver();
} else {
if (!"firefox".equals(string)) {
throw new IllegalArgumentException(String.format("Unknown browser %s", string));
}
this.driver = new FirefoxDriver();
}
Runtime.getRuntime().addShutdownHook(new Thread(driver::quit));
this.driver.get(properties.getProperty("web.baseUrl"));
this.driver.manage().window().setSize(new Dimension(1076, 640));
// this.session().login(properties.getProperty("web.username"), properties.getProperty("web.password"));
}
return driver;
}
public SessionHelper session() {
if (sessionHelper == null) {
sessionHelper = new SessionHelper(this);
}
return sessionHelper;
}
public HttpSessionHelper http() {
if (httpSessionHelper == null) {
httpSessionHelper = new HttpSessionHelper(this);
}
return httpSessionHelper;
}
public JamesCliHelper jamesCli() {
if (jamesCliHelper == null) {
jamesCliHelper = new JamesCliHelper(this);
}
return jamesCliHelper;
}
public JamesApiHelper jamesApi() {
if (jamesApiHelper == null) {
jamesApiHelper = new JamesApiHelper(this);
}
return jamesApiHelper;
}
public DeveloperMailHelper developerMail() {
if (developerMailHelper == null) {
developerMailHelper = new DeveloperMailHelper(this);
}
return developerMailHelper;
}
public MailHelper mail() {
if (mailHelper == null) {
mailHelper = new MailHelper(this);
}
return mailHelper;
}
public RestApiHelper rest() {
if (restApiHelper == null) {
restApiHelper = new RestApiHelper(this);
}
return restApiHelper;
}
public SoapApiHelper soap() {
if (soapApiHelper == null) {
soapApiHelper = new SoapApiHelper(this);
}
return soapApiHelper;
}
public String property(String name) {
return properties.getProperty(name);
}
} |
#ifndef RANGESENSOR_H
#define RANGESENSOR_H
#include <vector>
#include <gmapping/sensor/sensor_base/sensor.h>
#include <gmapping/utils/point.h>
#include <gmapping/sensor/sensor_range/sensor_range_export.h>
namespace GMapping{
// 是激光传感器的封装, 它描述了扫描光束的的各种物理特性,继承自类Sensor。
class SENSOR_RANGE_EXPORT RangeSensor: public Sensor{
friend class Configuration;
friend class CarmenConfiguration;
friend class CarmenWrapper;
public:
// 在RangeSensor内部嵌套定义了一个结构体Beam,描述了扫描光束的物理特性,包括相对于传感器坐标系的位置、量程、光束角的正余弦值。
struct Beam{
OrientedPoint pose; //pose relative to the center of the sensor
double span; //spam=0 indicates a line-like beam
double maxRange; //maximum range of the sensor
double s,c; //sinus and cosinus of the beam (optimization);
};
RangeSensor(std::string name);
RangeSensor(std::string name, unsigned int beams, double res, const OrientedPoint& position=OrientedPoint(0,0,0), double span=0, double maxrange=89.0);
inline const std::vector<Beam>& beams() const {return m_beams;}
inline std::vector<Beam>& beams() {return m_beams;}
inline OrientedPoint getPose() const {return m_pose;}
// 用于更新扫描光束属性
void updateBeamsLookup();
bool newFormat;
protected:
// RangeSensor定义了两个成员变量,其中m_pose用于记录传感器的位姿,m_beams则记录了扫描光束的信息。同时提供了set-get函数用于访问这些成员变量。
OrientedPoint m_pose;
std::vector<Beam> m_beams;
};
};
#endif |
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *create_node()
{
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
printf("Enter the data\n");
scanf("%d", &temp->data);
temp->next = NULL;
return temp;
}
struct node *insert_begin(struct node *head)
{
struct node *newnode;
if (head == NULL)
{
head = create_node();
}
else
{
newnode = create_node();
newnode->next = head;
head = newnode;
}
return head;
}
struct node *insert_at_pos(struct node *head)
{
int pos, i = 1;
struct node *temp, *insertnode;
if (head == NULL)
head = create_node();
else
{
printf("Enter position to insert\n");
scanf("%d", &pos);
temp = head;
while (i < pos - 1)
{
temp = temp->next;
i++;
}
insertnode = create_node();
insertnode->next = temp->next;
temp->next = insertnode;
}
return head;
}
struct node *insert_end(struct node *head)
{
struct node *temp;
if (head == NULL)
head = create_node();
else
{
temp = head;
while (temp->next != NULL)
temp = temp->next;
temp->next = create_node();
}
return head;
}
struct node *delete_begin(struct node *head)
{
struct node *temp;
if (head == NULL)
printf("List is empty\n");
else
{
temp = head;
head = temp->next;
temp->next = NULL;
free(temp);
}
return head;
}
struct node *delete_at_pos(struct node *head)
{
int pos, i = 1;
struct node *temp, *deletenode;
if (head == NULL)
printf("List is empty\n");
else
{
printf("Enter position to detete\n");
scanf("%d", &pos);
temp = head;
while (i < pos - 1)
{
temp = temp->next;
i++;
}
deletenode = temp->next;
temp->next = deletenode->next;
free(deletenode);
}
return head;
}
struct node *delete_end(struct node *head)
{
struct node *temp, *prevnode;
if (head == NULL)
printf("List is empty\n");
else
{
temp = head;
while (temp->next != NULL)
{
prevnode = temp;
temp = temp->next;
}
prevnode->next = NULL;
free(temp);
}
return head;
}
void display(struct node *head)
{
struct node *temp;
if (head == NULL)
printf("List is empty\n");
else
{
temp = head;
while (temp != NULL)
{
printf("%d\t", temp->data);
temp = temp->next;
}
printf("\n");
}
}
int main()
{
struct node *head = NULL;
int ch, pos;
while (1)
{
printf("Enter your choice\n");
printf("1.Insert begin\n2.Insert at position\n3.Insert end\n4.Delete begin\n5.delete end\n6.Delete at position\n7.Display\n8.Exit\n");
scanf("%d", &ch);
switch (ch)
{
case 1:
head = insert_begin(head);
break;
case 2:
head = insert_at_pos(head);
break;
case 3:
head = insert_end(head);
break;
case 4:
head = delete_begin(head);
break;
case 5:
head = delete_end(head);
break;
case 6:
head = delete_at_pos(head);
break;
case 7:
display(head);
break;
case 8:
exit(0);
default:
printf("Wrong choice\n");
}
}
} |
import { Injectable } from '@nestjs/common';
import { Todo } from './todo.model';
@Injectable()
export class TodoService {
private todos: Todo[] = [
new Todo({
id: 1,
title: 'Todo 1',
description: 'Description 1',
completed: true,
}),
new Todo({
id: 2,
title: 'Todo 2',
description: 'Description 2',
completed: false,
}),
new Todo({
id: 3,
title: 'Todo 3',
description: 'Description 3',
completed: false,
}),
];
getTodos(): Todo[] {
return this.todos;
}
getTodoById(id: number): Todo {
return this.todos.find((todo) => todo.id === id);
}
createTodo(todo: any): Todo[] {
this.todos.push(todo);
return this.todos;
}
updateTodoById(id: number, completed: boolean): Todo {
const todo = this.getTodoById(id);
todo.completed = completed;
return todo;
}
deleteTodoById(id: number): Todo[] {
const todoIndex = this.todos.findIndex((todo) => todo.id === id);
this.todos.splice(todoIndex, 1);
return this.todos;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.