text
stringlengths 184
4.48M
|
---|
<?php
namespace App\Entity\Enums;
use App\Entity\Traits\EnumsTrait;
use BackedEnum;
enum Priority: string
{
use EnumsTrait;
case Null = '';
case Hight = '1';
case Medium = '0';
case Low = '-1';
/**
* @param BackedEnum|string $enum
* @return string
*/
public static function getLabelFrom(BackedEnum|string $enum): string
{
if(is_string($enum)){
$enum = self::from($enum);
}
return match ($enum) {
self::Hight => 'Alta',
self::Medium => 'Media',
self::Low => 'Baja',
default => '-Seleccione-'
};
}
} |
"""Request API"""
import asyncio
import copy
import datetime
import json
import os
import re
import statistics
import urllib.parse
from functools import reduce
from pathlib import Path
from typing import Any, Dict, List
import httpx
import orjson
import requests
from dateutil import parser
from easy_logger.log_format import splunk_format
from requests import HTTPError, ReadTimeout, Response
from ciphertrust import logging
from ciphertrust.auth import Auth, refresh_token # type: ignore
from ciphertrust.exceptions import CipherMissingParam
from ciphertrust.static import (DEFAULT_HEADERS, DEFAULT_LIMITS_OVERRIDE,
DEFAULT_TIMEOUT_CONFIG_OVERRIDE, ENCODE,
REGEX_NUM)
from ciphertrust.utils import (concat_resources, create_error_response,
format_request, reformat_exception,
return_epoch, return_time, verify_path_exists)
cipher_log = logging.getLogger(__name__)
def standard_request(request: Response, **kwargs: Any) -> dict[str, Any]:
"""Call standard Request.
:return: Adjusted Request Response
:rtype: dict[str,Any]
"""
req: dict[str, Any] = {**request.json(), **format_request(request, **kwargs)}
return req
def delete_request(request: Response, **kwargs: Any) -> dict[str, Any]:
"""Deleteed request response.
:param request: _description_
:type request: Response
:return: _description_
:rtype: dict[str,Any]
"""
ident: str = urllib.parse.urlparse(request.url).path.split("/")[-1]
value_type: str = re.sub(
REGEX_NUM, "", urllib.parse.urlparse(request.url).path.split("/")[-2]
)
delete_response: dict[str, Any] = {
"id": ident,
"message": f"Deleted {value_type} with ID {ident}",
}
req: dict[str, Any] = {**delete_response, **format_request(request, **kwargs)}
return req
def download_request(request: Response, **kwargs: Any) -> dict[str, Any]:
"""Use to Download Tar files. Only supports tar.gz can update.
:return: Adjusted Request Ressponse
:rtype: dict[str,Any]
"""
chunk_size: int = kwargs.pop("chunk_size", 128)
save_path: str = kwargs.pop("save_dir", os.path.expanduser("~"))
if not verify_path_exists(path_dir=save_path):
raise FileExistsError(f"{save_path} does not exist")
parsed_url: urllib.parse.ParseResult = urllib.parse.urlparse(request.url) # type: ignore
save_filename: Path = Path.joinpath(
Path(save_path)
/ f"{datetime.datetime.now().strftime('%Y%m%dT%H%M%S')}_ciphertrust_log_{parsed_url.hostname}.tar.gz"
) # pylint: disable=line-too-long,unknown-option-value
with open(save_filename, "wb") as fild:
for chunk in request.iter_content(chunk_size=chunk_size):
fild.write(chunk)
response: dict[str, Any] = {
"message": "downloaded system logs completed",
"location": str(save_filename),
}
response = {**response, **format_request(request, **kwargs)}
return response
@refresh_token
def ctm_request(
auth: Auth, **kwargs: Any
) -> Response: # pylint: disable=too-many-locals
"""_summary_
Args:
token (Auth): Auth class that is used to refresh bearer token upon expiration.
url_type (str): specify the api call
method (str): specifies the type of HTTPS method used
params (dict, optional): specifies parameters passed to request
data (str, optional): specifies the data being sent
verify (str|bool, optional): sets request to verify with a custom
cert bypass verification or verify with standard library. Defaults to True
timeout (int, optional): sets API call timeout. Defaults to 60
limit (int, Optional): The maximum number of results
offset (int, Optional): The offset of the result entry
get_object (str, Optional): Used if method is "GET", but additional path parameters required
Returns:
_type_: _description_
"""
kwargs.get("headers", {}).update({"Authorization": f"Bearer {auth.token}"})
start_time: float = datetime.datetime.utcnow().timestamp()
try:
response: Response = requests.request(
**kwargs
) # pylint: disable=missing-timeout
except ReadTimeout as err:
error = reformat_exception(err)
end_time: float = datetime.datetime.utcnow().timestamp()
response: Response = create_error_response(
error=error,
status_code=598,
start_time=start_time,
end_time=end_time,
**kwargs,
)
return response
@refresh_token
async def ctm_request_async(
auth: Auth, **kwargs: Any
) -> Dict[str, Any]: # pylint: disable=too-many-locals
"""_summary_
Args:
token (Auth): Auth class that is used to refresh bearer token upon expiration.
url_type (str): specify the api call
method (str): specifies the type of HTTPS method used
params (dict, optional): specifies parameters passed to request
data (str, optional): specifies the data being sent
verify (str|bool, optional): sets request to verify with a custom
cert bypass verification or verify with standard library. Defaults to True
timeout (int, optional): sets API call timeout. Defaults to 60
delete_object (str, required|optional): Required if method is DELETE
put_object (str, required|optional): Required if method is PUT
limit (int, Optional): The maximum number of results
offset (int, Optional): The offset of the result entry
get_object (str, Optional): Used if method is "GET", but additional path parameters required
Returns:
_type_: _description_
"""
try:
client: httpx.AsyncClient = kwargs["client"]
url: str = kwargs.pop("url") # type: ignore
params: Dict[str, Any] = kwargs["params"]
headers: Dict[str, Any] = kwargs.pop("headers", DEFAULT_HEADERS)
except KeyError as err:
error: str = reformat_exception(err)
raise CipherMissingParam(error) # pylint: disable=raise-missing-from
# Add auth to header
# auth = refresh_token(auth=auth)
headers["Authorization"] = f"Bearer {auth.token}"
response: httpx.Response = await client.get(url=url, params=params, headers=headers)
json_response = {
"exec_time_total": response.elapsed.total_seconds(),
"headers": json.loads(
orjson.dumps(response.headers.__dict__["_store"]).decode(ENCODE)
), # pylint: disable=no-member
"exec_time_end": return_time(),
}
return {**json_response, **response.json()}
# TODO: Cannot do as we are talking about hundreds of calls due to the millions of certs stored.
@refresh_token
async def ctm_request_list_all(auth: Auth, **kwargs: Any) -> Dict[str, Any]:
"""_summary_
Args:
auth (Auth): _description_
Returns:
Dict[str,Any]: _description_
"""
# inital response
kwargs["params"] = {"limit": 1}
start_time: float = return_epoch()
resp: dict[str, Any] = ctm_request(auth=auth, **kwargs)
limit: int = 1000
total: int = resp["total"]
# set the total amount of iterations required to get full response
# works when limit is already reached
# TODO: This will send full iterations, but too many calls.
# Reduce the amount of calls to prevent excessive calls.
iterations: int = (
int(total / limit) if (total % limit == 0) else (total // limit + 1)
)
# iterations = 10
response: Dict[str, Any] = {
"total": total,
"exec_time_start": start_time,
"iterations": copy.deepcopy(iterations),
}
full_listed_resp = []
while iterations > 0:
send_iterations = 10 if iterations <= 10 else iterations
tmp_listed_resp = await split_up_req(
auth=auth,
iterations=send_iterations, # type: ignore
limit=limit, # type: ignore
**kwargs,
)
full_listed_resp: Any = full_listed_resp + tmp_listed_resp
iterations -= 10
# print(f"One loop iteration completed new_iterations={iterations}")
response = {**response, **build_responsde(full_listed_resp=full_listed_resp)} # type: ignore
response["exec_time_total"] = datetime.datetime.fromtimestamp(
return_epoch()
) - datetime.datetime.fromtimestamp(start_time)
response["exec_time_start"] = start_time
return response
@refresh_token
async def split_up_req(
auth: Auth, iterations: int, limit: int, **kwargs: Any
) -> List[Dict[str, Any]]:
"""Splitting up requests due to too many being sent and cannot handle.
Trying to adjust with timeout, but still causes errors on return.
:param auth: _description_
:type auth: Auth
:param iterations: _description_
:type iterations: int
:param limit: _description_
:type limit: int
:return: _description_
:rtype: List[Dict[str,Any]]
"""
async with httpx.AsyncClient(
limits=DEFAULT_LIMITS_OVERRIDE,
timeout=DEFAULT_TIMEOUT_CONFIG_OVERRIDE,
verify=kwargs.get("verify", True),
) as client:
tasks: list[Any] = []
for number in range(iterations):
# Set the parameters and increase per run
kwargs["params"] = {
"limit": limit,
"skip": (number * limit + 1) if (number != 0) else 0,
}
kwargs["client"] = client
# print(f"{number=}|{kwargs=}")
tasks.append(asyncio.ensure_future(ctm_request_async(auth=auth, **kwargs)))
full_listed_resp: List[Dict[str, Any]] = await asyncio.gather(*tasks) # type: ignore
return full_listed_resp # type: ignore
def build_responsde(full_listed_resp: list[dict[str, Any]]) -> dict[str, Any]:
"""Build Returned Reponse with statistics.
:param full_listed_resp: _description_
:type full_listed_resp: list[dict[str, Any]]
:return: _description_
:rtype: dict[str, Any]
"""
response: Dict[str, Any] = {
"exec_time_end": 0.0,
"exec_time_min": 0.0,
"exec_time_max": 0.0,
"exec_time_stdev": 0.0,
"resources": [],
}
end_time: float = datetime.datetime.utcnow().timestamp()
elapsed_times: list[float] = [
value["exec_time_total"] for value in full_listed_resp
]
response["elapsed_times"] = elapsed_times
response["exec_time_end"] = end_time
response["exec_time_min"] = min(elapsed_times)
response["exec_time_max"] = max(elapsed_times)
response["exec_time_stdev"] = statistics.stdev(elapsed_times)
response["resources"] = reduce(concat_resources, full_listed_resp)["resources"] # type: ignore
return response
def asyn_get_all(auth: Auth, **kwargs: Any) -> dict[str, Any]:
"""Asyncio get All. Still under eval
:param auth: _description_
:type auth: Auth
:return: _description_
:rtype: dict[str, Any]
"""
return asyncio.run(ctm_request_list_all(auth=auth, **kwargs))
def api_raise_error(
response: Response, method_type: str = "standard", **kwargs: Any
) -> dict[str, Any]:
"""Raises error if response not what was expected
Args:
response (Response): _description_
Raises:
CipherPermission: _description_
CipherAPIError: _description_
"""
formats: dict[str, Any] = {
"standard": standard_request,
"download": download_request,
"delete": delete_request,
}
try:
response.raise_for_status()
return_response = formats[method_type](response, **kwargs)
# print(return_response)
cipher_log.info(
splunk_format(
source="ciphertrust-sdk",
message="CipherTrust API Request",
**{
**return_response["response_statistics"],
**return_response["request_parameters"],
},
)
)
except HTTPError as err:
error: str = reformat_exception(err)
error_message = {
"error": error,
"error_type": "CipherAPIError",
"error_response": f"{response.text if response.text else response.reason}",
}
# Reformat response due to how codes are not returned properly
start_time: float = kwargs.pop("start_time")
response = create_error_response(
error=error,
status_code=response.status_code,
start_time=start_time, # convert_to_epoch(date=start_time),
end_time=return_epoch(),
**kwargs,
)
return_response = {
**error_message,
**standard_request(request=response, start_time=start_time, **kwargs),
}
cipher_log.error(
splunk_format(
source="ciphertrust-sdk",
**{
**return_response["response_statistics"], # type: ignore
**return_response["request_parameters"], # type: ignore
**error_message,
},
)
) # type: ignore
cipher_log.debug(splunk_format(**return_response))
return return_response |
/*using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using OvermorrowMod.Common;
using OvermorrowMod.Common.Cutscenes;
using OvermorrowMod.Common.Particles;
using OvermorrowMod.Content.WorldGeneration;
using OvermorrowMod.Core;
using System;
using System.Linq;
using System.Xml;
using Terraria;
using Terraria.GameContent;
using Terraria.GameContent.Events;
using Terraria.GameContent.ItemDropRules;
using Terraria.ID;
using Terraria.ModLoader;
using Terraria.Utilities;
namespace OvermorrowMod.Content.NPCs.Bosses.Bandits
{
public class ArcherBandit : ModNPC
{
private int DodgeCooldown = 0;
private int RepeatShots = 0;
private bool isNaked = false;
public override bool CanHitPlayer(Player target, ref int cooldownSlot) => false;
public override bool? CanHitNPC(NPC target) => false;
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Archer Bandit");
Main.npcFrameCount[NPC.type] = 15;
}
public override void SetDefaults()
{
NPC.width = 22;
NPC.height = 44;
NPC.aiStyle = -1;
NPC.damage = 21;
NPC.defense = 12;
NPC.lifeMax = 340;
NPC.HitSound = SoundID.NPCHit1;
NPC.DeathSound = SoundID.NPCDeath39;
NPC.knockBackResist = 0;
NPC.boss = true;
NPC.npcSlots = 10f;
}
private ref float AIState => ref NPC.ai[0];
private ref float AICounter => ref NPC.ai[1];
private ref float MiscCounter => ref NPC.ai[2];
private ref float DodgeCounter => ref NPC.ai[3];
private enum AIStates
{
Walk = 0,
Jump = 1,
LongShot = 2,
AngleShot = 3,
JumpShot = 4,
Stun = 5
}
public void Move(Vector2 targetPosition, float moveSpeed, float maxSpeed, float jumpSpeed)
{
if (NPC.Center.X < targetPosition.X)
{
NPC.velocity.X += moveSpeed;
if (NPC.velocity.X > maxSpeed) NPC.velocity.X = maxSpeed;
}
else if (NPC.Center.X > targetPosition.X)
{
NPC.velocity.X -= moveSpeed;
if (NPC.velocity.X < -maxSpeed) NPC.velocity.X = -maxSpeed;
}
if (NPC.collideY && NPC.velocity.Y == 0)
{
Collision.StepUp(ref NPC.position, ref NPC.velocity, NPC.width, NPC.height, ref NPC.stepSpeed, ref NPC.gfxOffY, 1, false, 0);
#region Jump Handling
if (NPC.collideX || CheckGap())
{
NPC.velocity.Y += jumpSpeed;
}
#endregion
}
}
private bool CheckGap()
{
Rectangle npcHitbox = NPC.getRect();
Vector2 checkLeft = new Vector2(npcHitbox.BottomLeft().X, npcHitbox.BottomLeft().Y);
Vector2 checkRight = new Vector2(npcHitbox.BottomRight().X, npcHitbox.BottomRight().Y);
Vector2 hitboxDetection = (NPC.velocity.X < 0 ? checkLeft : checkRight) / 16;
int directionOffset = NPC.direction;
Tile tile = Framing.GetTileSafely((int)hitboxDetection.X + directionOffset, (int)hitboxDetection.Y);
return !tile.HasTile;
}
public override void AI()
{
NPC.TargetClosest();
Player target = Main.player[NPC.target];
switch (AIState)
{
#region Walk
case (int)AIStates.Walk:
FrameUpdate(FrameType.Walk);
float xDistance = Math.Abs(NPC.Center.X - target.Center.X);
if (xDistance < 10 * 16) // Try to stay within 10 tiles away from the player
{
AICounter = 0;
if (NPC.Center.X > target.Center.X) // The NPC is to the right of the player, therefore move to the right
{
Move(target.Center + new Vector2(12 * 16), 0.4f, 1.2f, 2f);
}
else
{
Dust.NewDust(new Vector2((int)NPC.BottomLeft.X / 16, (int)NPC.BottomLeft.Y / 16), 1, 1, DustID.Torch);
// Check if the tile below the NPC is empty
if (Framing.GetTileSafely((int)NPC.BottomLeft.X / 16, (int)NPC.BottomLeft.Y / 16).HasTile)
{
Move(target.Center - new Vector2(12 * 16), 0.35f, 1.2f, 2f);
}
else
{
NPC.velocity = Vector2.Zero;
}
}
// The player is too close, set a timer to determine if they should perform a jump or roll
if (xDistance < 6 * 16)
{
if (DodgeCounter++ >= 10 && DodgeCooldown-- <= 0)
{
NPC.velocity = Vector2.Zero;
AIState = Main.rand.NextBool() ? (int)AIStates.JumpShot : (int)AIStates.JumpShot;
AICounter = 0;
DodgeCounter = 0;
}
}
}
else
{
if (AICounter++ == 60)
{
AIState = Main.rand.NextBool() ? (int)AIStates.AngleShot : (int)AIStates.LongShot;
//AIState = (int)AIStates.AngleShot;
AICounter = 0;
}
}
break;
#endregion
#region Jump
case (int)AIStates.Jump:
FrameUpdate(FrameType.Jump);
if (AICounter++ == 0)
{
int jumpDirection = NPC.Center.X > target.Center.X ? 8 : -8;
if (Framing.GetTileSafely((int)(NPC.BottomLeft.X / 16) - 15, (int)NPC.BottomLeft.Y / 16).HasTile)
{
// Check if the right side of the NPC is near a solid block
if ((Framing.GetTileSafely((int)(NPC.Center.X / 16) + 1, (int)NPC.Center.Y / 16).HasTile && Framing.GetTileSafely((int)(NPC.Center.X / 16) + 1, (int)NPC.Center.Y / 16).TileType != TileID.WoodenBeam))
{
NPC.velocity = new Vector2(-jumpDirection, -4);
Main.NewText("tile behind me");
}
else
{
NPC.velocity = new Vector2(jumpDirection * (Main.rand.NextBool(3) ? -1 : 1), -4);
}
}
else // The NPC will jump off the ledge if they jump, therefore launch in the other direction
{
NPC.velocity = new Vector2(-jumpDirection, -4);
}
}
if (NPC.collideY && NPC.velocity.Y == 0)
{
NPC.velocity.X = 0;
AIState = (int)AIStates.Walk;
AICounter = 0;
DodgeCooldown = 0;
}
break;
#endregion
#region LongShot
case (int)AIStates.LongShot:
NPC.velocity = Vector2.Zero;
if (FrameUpdate(FrameType.LongShot))
{
if (yFrame == 6)
{
if (tempCounter == 61)
{
float particleScale = Main.rand.NextFloat(0.2f, 0.3f);
float particleRotation = Main.rand.NextFloat(0, MathHelper.TwoPi);
float particleTime = 90;
Particle.CreateParticle(Particle.ParticleType<RingSolid>(), NPC.Center + new Vector2(26 * NPC.direction, 0), Vector2.Zero, Color.Orange, 1, particleScale, particleRotation, particleTime);
}
if (tempCounter == 62)
{
for (int i = 0; i < Main.rand.Next(3, 6); i++)
{
float randomScale = Main.rand.NextFloat(0.5f, 0.85f);
float randomAngle = Main.rand.NextFloat(-MathHelper.ToRadians(45), MathHelper.ToRadians(45));
Vector2 RandomVelocity = -Vector2.UnitX.RotatedBy(randomAngle) * Main.rand.Next(4, 7) * NPC.direction;
Color color = Color.Orange;
Particle.CreateParticle(Particle.ParticleType<LightSpark>(), NPC.Center, RandomVelocity, color, 1, randomScale);
}
Lighting.AddLight(NPC.Center + new Vector2(26, -28), 2f, 2f * 0.65f, 0);
Projectile.NewProjectile(NPC.GetSource_FromAI(), NPC.Center, Vector2.UnitX * 12 * NPC.direction, ModContent.ProjectileType<FlameArrow>(), NPC.damage * 2, 2f, Main.myPlayer);
}
}
}
else
{
if (RepeatShots++ < 0)
{
AIState = (int)AIStates.LongShot;
AICounter = 0;
}
else
{
AIState = (int)AIStates.Walk;
AICounter = 0;
RepeatShots = 0;
}
}
break;
#endregion
#region AngleShot
case (int)AIStates.AngleShot:
NPC.velocity = Vector2.Zero;
if (FrameUpdate(FrameType.AngleShot))
{
if (yFrame == 6)
{
if (tempCounter == 61)
{
float particleScale = Main.rand.NextFloat(0.2f, 0.3f);
float particleRotation = Main.rand.NextFloat(0, MathHelper.TwoPi);
float particleTime = 90;
Particle.CreateParticle(Particle.ParticleType<RingSolid>(), NPC.Center + new Vector2(26 * NPC.direction, -28), Vector2.Zero, Color.Purple, 1, particleScale, particleRotation, particleTime);
}
if (tempCounter == 62)
{
for (int i = 0; i < Main.rand.Next(3, 6); i++)
{
float randomScale = Main.rand.NextFloat(0.5f, 0.85f);
float randomAngle = Main.rand.NextFloat(-MathHelper.ToRadians(45), MathHelper.ToRadians(45));
Vector2 RandomVelocity = new Vector2(-1 * NPC.direction, 1).RotatedBy(randomAngle) * Main.rand.Next(4, 7);
Color color = Color.Purple;
Particle.CreateParticle(Particle.ParticleType<LightSpark>(), NPC.Center, RandomVelocity, color, 1, randomScale);
}
Lighting.AddLight(NPC.Center + new Vector2(26, -28), 2f, 0, 2f);
//Vector2 initialVelocity = 7 * new Vector2((float)Math.Cos(45), (float)Math.Sin(45));
// Projectile.NewProjectile(NPC.GetSource_FromAI(), NPC.Center, new Vector2(7 * NPC.direction, -12), ModContent.ProjectileType<SplitArrow>(), NPC.damage, 2f, Main.myPlayer, 0, 0);
//for (int i = 0; i < 4; i++)
//{
// Projectile.NewProjectile(NPC.GetSource_FromAI(), NPC.Center, new Vector2(Main.rand.NextFloat(6, 10) * NPC.direction, -Main.rand.NextFloat(12, 17)), ModContent.ProjectileType<SplitArrow>(), NPC.damage, 2f, Main.myPlayer, 0, 0);
//}
Projectile.NewProjectile(NPC.GetSource_FromAI(), NPC.Center, new Vector2(Main.rand.NextFloat(6, 10) * NPC.direction, -Main.rand.NextFloat(12, 16.5f)), ModContent.ProjectileType<SplitArrow>(), NPC.damage, 2f, Main.myPlayer, 0, 0);
}
}
}
else
{
if (RepeatShots++ < 0)
{
AIState = (int)AIStates.AngleShot;
AICounter = 0;
}
else
{
AIState = (int)AIStates.Walk;
AICounter = 0;
RepeatShots = 0;
}
}
break;
#endregion
#region JumpShot
case (int)AIStates.JumpShot:
const int JUMP_HEIGHT = -11;
FrameUpdate(FrameType.JumpShot);
if (AICounter++ == 0)
{
int jumpDirection = NPC.Center.X > target.Center.X ? 7 : -7;
if (Framing.GetTileSafely((int)(NPC.BottomLeft.X / 16) - 15, (int)NPC.BottomLeft.Y / 16).HasTile)
{
// Check if the right side of the NPC is near a solid block
if ((Framing.GetTileSafely((int)(NPC.Center.X / 16) + 1, (int)NPC.Center.Y / 16).HasTile && Framing.GetTileSafely((int)(NPC.Center.X / 16) + 1, (int)NPC.Center.Y / 16).TileType != TileID.WoodenBeam))
{
NPC.velocity = new Vector2(-jumpDirection, -4);
}
else
{
NPC.velocity = new Vector2(jumpDirection, -4);
Main.NewText("tile behind me FIRE");
}
}
else
{
NPC.velocity = new Vector2(-jumpDirection, -4);
}
Projectile.NewProjectile(null, NPC.Center, new Vector2(-5 * NPC.direction, -3), ModContent.ProjectileType<SlimeFlask>(), 0, 0f, Main.myPlayer);
}
if (NPC.collideY && NPC.velocity.Y == 0 && MiscCounter == 0)
{
NPC.velocity.X = 0;
MiscCounter = 1;
}
if (MiscCounter == 1)
{
int jumpDirection = NPC.Center.X > target.Center.X ? 3 : -3;
if (Framing.GetTileSafely((int)(NPC.BottomLeft.X / 16) - 15, (int)NPC.BottomLeft.Y / 16).HasTile)
{
NPC.velocity = new Vector2(jumpDirection, JUMP_HEIGHT);
}
else // The NPC will jump off the ledge if they jump, therefore launch in the other direction
{
NPC.velocity = new Vector2(-jumpDirection, JUMP_HEIGHT);
}
}
if (MiscCounter >= 1)
{
if (MiscCounter++ == 30)
{
for (int i = 0; i < Main.rand.Next(3, 6); i++)
{
float randomScale = Main.rand.NextFloat(0.5f, 0.85f);
float randomAngle = Main.rand.NextFloat(-MathHelper.ToRadians(45), MathHelper.ToRadians(45));
Vector2 RandomVelocity = new Vector2(1 * -NPC.direction, -1).RotatedBy(randomAngle) * Main.rand.Next(4, 7);
Color color = Color.Orange;
Particle.CreateParticle(Particle.ParticleType<LightSpark>(), NPC.Center, RandomVelocity, color, 1, randomScale);
}
Projectile.NewProjectile(null, NPC.Center, new Vector2(-6 * -NPC.direction, 6), ModContent.ProjectileType<FlameArrow>(), 26, 0f, Main.myPlayer);
}
}
if (NPC.collideY && NPC.velocity.Y == 0 && MiscCounter > 1)
{
NPC.velocity.X = 0;
AIState = (int)AIStates.Walk;
AICounter = 0;
MiscCounter = 0;
DodgeCooldown = 15;
}
break;
#endregion
#region Stun
case (int)AIStates.Stun:
FrameUpdate(FrameType.Stun);
if (NPC.collideY && NPC.velocity.Y == 0)
{
NPC.velocity.X = 0;
}
if (AICounter++ == 120)
{
AIState = (int)AIStates.Walk;
AICounter = 0;
MiscCounter = 0;
}
break;
#endregion
}
}
int xFrame = 1;
int yFrame = 0;
const int MAX_COLUMNS = 8;
public override void FindFrame(int frameHeight)
{
NPC.spriteDirection = NPC.direction;
NPC.frame.Width = TextureAssets.Npc[NPC.type].Value.Width / MAX_COLUMNS;
int xFrameOffset = isNaked ? 0 : 4;
NPC.frame.X = NPC.frame.Width * (xFrame + xFrameOffset);
NPC.frame.Y = frameHeight * yFrame;
}
public override void OnHitByItem(Player player, Item item, int damage, float knockback, bool crit)
{
if (AIState == (int)AIStates.AngleShot || (AIState == (int)AIStates.LongShot))
{
Main.NewText("stun");
AIState = (int)AIStates.Stun;
AICounter = 0;
NPC.velocity = new Vector2(2 * -NPC.direction, -2);
}
}
private enum FrameType
{
Walk,
Jump,
LongShot,
AngleShot,
JumpShot,
Stun
}
float tempCounter = 0;
private bool FrameUpdate(FrameType type)
{
if (NPC.life <= NPC.lifeMax * 0.76f) isNaked = true;
switch (type)
{
#region Walk
case FrameType.Walk:
xFrame = 3;
if (NPC.velocity.X != 0)
{
NPC.direction = Math.Sign(NPC.velocity.X);
}
if (NPC.velocity.X == 0 && NPC.velocity.Y == 0) // Frame for when the NPC is standing still
{
yFrame = 0;
tempCounter = 0;
}
else if (NPC.velocity.Y != 0) // Frame for when the NPC is jumping or falling
{
yFrame = 1;
tempCounter = 0;
}
else // Frames for when the NPC is walking
{
if (yFrame == 14) yFrame = 0;
// Change the walking frame at a speed depending on the velocity
int walkRate = (int)Math.Round(Math.Abs(NPC.velocity.X));
tempCounter += walkRate;
if (tempCounter > 5)
{
yFrame++;
tempCounter = 0;
}
}
break;
#endregion
#region Jump
case FrameType.Jump:
if (NPC.velocity.X != 0)
{
NPC.direction = -Math.Sign(NPC.velocity.X);
}
xFrame = 0;
yFrame = 1;
break;
#endregion
#region LongShot
case FrameType.LongShot:
xFrame = 1;
if (tempCounter++ < 60) // NPC stands in the ready position prior to drawing back the bow
{
if (yFrame > 0) yFrame = 0;
}
else
{
if (yFrame == 5) // Holds the frame for half a second longer
{
if (tempCounter > 98)
{
yFrame++;
tempCounter = 60;
}
}
else
{
if (tempCounter > 68)
{
if (yFrame == 10)
{
yFrame = 0;
tempCounter = 0;
return false;
}
yFrame++;
tempCounter = 60;
}
}
}
break;
#endregion
#region AngleShot
case FrameType.AngleShot:
xFrame = 2;
//if (RepeatShots > 0 && tempCounter < 55) tempCounter = 65; // If the NPC has fired the first angled shot, make it take less time
if (tempCounter++ < 60) // NPC stands in the ready position prior to drawing back the bow
{
if (yFrame > 0) yFrame = 0;
}
else
{
if (yFrame == 5)
{
if (tempCounter > 98)
{
yFrame++;
tempCounter = 60;
}
}
else
{
if (tempCounter > 68)
{
if (yFrame == 10)
{
yFrame = 0;
tempCounter = 0;
return false;
}
yFrame++;
tempCounter = 60;
}
}
}
break;
#endregion
#region JumpShot
case FrameType.JumpShot:
xFrame = 0;
//Main.NewText("tempcounter " + tempCounter);
if (MiscCounter == 0)
{
yFrame = 1;
}
else
{
if (tempCounter++ == 0)
{
yFrame = 2;
}
if (tempCounter == 18)
{
yFrame = 3;
}
if (tempCounter == 26)
{
yFrame = 4;
}
if (tempCounter == 32)
{
yFrame = 1;
}
}
break;
#endregion
#region Stun
case FrameType.Stun:
xFrame = 0;
if (NPC.velocity.Y != 0)
{
yFrame = 1;
}
else if (NPC.collideY)
{
yFrame = 0;
}
break;
#endregion
}
return true;
}
public override bool PreDraw(SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor)
{
Texture2D texture = TextureAssets.Npc[NPC.type].Value;
var spriteEffects = NPC.direction == 1 ? SpriteEffects.None : SpriteEffects.FlipHorizontally;
float xOffset = NPC.direction == 1 ? 11 : -10;
Vector2 drawOffset = new Vector2(xOffset, -4);
if ((AIState == (int)AIStates.LongShot || AIState == (int)AIStates.AngleShot) && yFrame == 5)
{
PreDrawLongShot(spriteBatch, screenPos, drawColor);
}
else
{
spriteBatch.Draw(texture, NPC.Center + drawOffset - Main.screenPosition, NPC.frame, drawColor, NPC.rotation, NPC.frame.Size() / 2, NPC.scale, spriteEffects, 0);
}
return false;
}
public override void PostDraw(SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor)
{
if ((AIState == (int)AIStates.LongShot || AIState == (int)AIStates.AngleShot) && yFrame == 5)
{
PostDrawLongShot(spriteBatch, screenPos, drawColor);
}
else if (AIState == (int)AIStates.JumpShot && (yFrame == 2 || yFrame == 3))
{
PostDrawJumpShot(spriteBatch, screenPos, drawColor);
}
}
private void PostDrawJumpShot(SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor)
{
Texture2D texture = TextureAssets.Npc[NPC.type].Value;
var spriteEffects = NPC.direction == 1 ? SpriteEffects.None : SpriteEffects.FlipHorizontally;
float xOffset = NPC.direction == 1 ? 11 : -10;
Vector2 drawOffset = new Vector2(xOffset, -4);
Main.spriteBatch.Reload(BlendState.Additive);
Color frameColor = Color.Orange;
Texture2D flare = ModContent.Request<Texture2D>(AssetDirectory.Textures + "flare_01").Value;
float progress = Utils.Clamp(tempCounter, 0, 26) / 26f;
float scale = MathHelper.Lerp(0, 1, progress);
Vector2 flareOffset = new Vector2(26 * NPC.direction, 14);
float colorStrength = MathHelper.Lerp(0, 1.5f, progress);
Lighting.AddLight(NPC.Center + new Vector2(26 * NPC.direction, 14), colorStrength, colorStrength * 0.65f, 0);
spriteBatch.Draw(flare, NPC.Center - screenPos + flareOffset, null, frameColor, NPC.rotation, flare.Size() / 2, scale, spriteEffects, 0);
Main.spriteBatch.Reload(BlendState.AlphaBlend);
}
private void PreDrawLongShot(SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor)
{
Texture2D texture = TextureAssets.Npc[NPC.type].Value;
var spriteEffects = NPC.direction == 1 ? SpriteEffects.None : SpriteEffects.FlipHorizontally;
float xOffset = NPC.direction == 1 ? 11 : -10;
Vector2 drawOffset = new Vector2(xOffset, -4);
spriteBatch.Draw(texture, NPC.Center + drawOffset - Main.screenPosition, NPC.frame, drawColor, NPC.rotation, NPC.frame.Size() / 2, NPC.scale, spriteEffects, 0);
int frameOffset = xFrame == 1 ? 0 : 60;
Rectangle drawRectangle = new Rectangle(frameOffset, 0, 60, 60);
Vector2 bowOffset = new Vector2(NPC.direction == 1 ? 11 : -10, -4);
float progress = Utils.Clamp(tempCounter - 68, 0, 30) / 30f;
Main.spriteBatch.Reload(BlendState.Additive);
float colorStrength = MathHelper.Lerp(0, 1f, progress);
Color frameColor = xFrame == 1 ? Color.Orange : Color.Purple;
if (xFrame == 1)
{
Lighting.AddLight(NPC.Center + new Vector2(26, -28), colorStrength, colorStrength * 0.65f, 0);
}
else
{
Lighting.AddLight(NPC.Center + new Vector2(26, -28), colorStrength, 0, colorStrength);
}
Texture2D glowFrame = ModContent.Request<Texture2D>(AssetDirectory.Boss + "Bandits/ArcherBandit_ArrowGlow").Value;
spriteBatch.Draw(glowFrame, NPC.Center - screenPos + bowOffset, drawRectangle, frameColor * progress, NPC.rotation, drawRectangle.Size() / 2, NPC.scale, spriteEffects, 0);
Main.spriteBatch.Reload(BlendState.AlphaBlend);
}
private void PostDrawLongShot(SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor)
{
var spriteEffects = NPC.direction == 1 ? SpriteEffects.None : SpriteEffects.FlipHorizontally;
int frameOffset = xFrame == 1 ? 0 : 60;
Rectangle drawRectangle = new Rectangle(frameOffset, 0, 60, 60);
Vector2 bowOffset = new Vector2(NPC.direction == 1 ? 11 : -10, -4);
Texture2D bowFrame = ModContent.Request<Texture2D>(AssetDirectory.Boss + "Bandits/ArcherBandit_Bow").Value;
spriteBatch.Draw(bowFrame, NPC.Center - screenPos + bowOffset, drawRectangle, drawColor, NPC.rotation, drawRectangle.Size() / 2, NPC.scale, spriteEffects, 0);
Main.spriteBatch.Reload(SpriteSortMode.Immediate);
float progress = Utils.Clamp(tempCounter - 68, 0, 30) / 30f;
Effect effect = OvermorrowModFile.Instance.Whiteout.Value;
effect.Parameters["WhiteoutColor"].SetValue(Color.White.ToVector3());
effect.Parameters["WhiteoutProgress"].SetValue(progress);
effect.CurrentTechnique.Passes["Whiteout"].Apply();
Texture2D arrowFrame = ModContent.Request<Texture2D>(AssetDirectory.Boss + "Bandits/ArcherBandit_Arrow").Value;
spriteBatch.Draw(arrowFrame, NPC.Center - screenPos + bowOffset, drawRectangle, drawColor, NPC.rotation, drawRectangle.Size() / 2, NPC.scale, spriteEffects, 0);
Main.spriteBatch.Reload(SpriteSortMode.Deferred);
Main.spriteBatch.Reload(BlendState.Additive);
Color frameColor = xFrame == 1 ? Color.Orange : Color.Purple;
Texture2D flare = ModContent.Request<Texture2D>(AssetDirectory.Textures + "flare_01").Value;
float scale = MathHelper.Lerp(0, 1, progress);
Vector2 flareOffset = xFrame == 1 ? new Vector2(34 * NPC.direction, -3) : new Vector2(26 * NPC.direction, -28);
spriteBatch.Draw(flare, NPC.Center - screenPos + flareOffset, null, frameColor, NPC.rotation, flare.Size() / 2, scale, spriteEffects, 0);
Main.spriteBatch.Reload(BlendState.AlphaBlend);
}
}
}
*/ |
import 'package:audiorecord/screen/box.dart';
import 'package:audiorecord/widget/comment_tile.dart';
import 'package:flutter/material.dart';
class CommentScreen extends StatefulWidget {
@override
_CommentScreenState createState() => _CommentScreenState();
}
class _CommentScreenState extends State<CommentScreen> {
double _sheetHeight = 0.5; // Initial height of the sheet
// final recorder = FlutterSoundRecorder();
// @override
// void initState() {
// // TODO: implement initState
// super.initState();
// initRecorder();
// }
// @override
// void dispose() {
// // TODO: implement dispose
// super.dispose();
// recorder.closeRecorder();
// }
// Future initRecorder() async {
// try {
// final status = await Permission.microphone.request();
// if (status != PermissionStatus.granted) {
// throw "Microphone permission not granted";
// }
// await recorder.openRecorder();
// } catch (e) {
// print(e);
// }
// }
// Future record() async {
// await recorder.startRecorder(toFile: 'audio');
// }
// Future stop() async {
// await recorder.stopRecorder();
// }
@override
Widget build(BuildContext context) {
return GestureDetector(
onVerticalDragUpdate: (details) {
setState(() {
// Adjusting the height based on drag position
_sheetHeight -=
details.primaryDelta! / MediaQuery.of(context).size.height;
if (_sheetHeight < 0.25) _sheetHeight = 0.25; // Minimum height
if (_sheetHeight > 1.0) _sheetHeight = 1.0; // Maximum height
});
},
onVerticalDragEnd: (details) {
if (details.primaryVelocity! > 0) {
Navigator.pop(
context); // Pop the modal bottom sheet if dragged downward
}
},
child: FractionallySizedBox(
heightFactor: _sheetHeight,
child: Container(
padding: const EdgeInsets.all(10.0),
decoration: BoxDecoration(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(20),
topRight: Radius.circular(20),
),
color: Colors.grey.shade300,
),
child: Stack(
children: [
Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
// crossAxisAlignment: CrossAxisAlignment.start,
children: [
Column(
children: [
Container(
height: 5,
width: 50,
decoration: BoxDecoration(
color: Colors.grey,
borderRadius: BorderRadius.circular(10),
),
),
const SizedBox(
height: 5,
),
const Text(
"Comments",
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
),
),
const Divider(
thickness: 2,
)
],
),
Expanded(
child: ListView.builder(
itemCount: 6,
itemBuilder: (context, index) {
return CommentTile();
}),
),
const SizedBox(
height: 60,
),
// Add more comments as needed
],
),
Positioned(
left: 0,
right: 0,
bottom: 0,
child: SizedBox(
height: 60,
child: Row(
children: [
Expanded(
child: Container(
padding: const EdgeInsets.all(3),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(20),
),
child: TextFormField(
decoration: InputDecoration(
hintText: 'Add a comment...',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(20),
),
suffixIcon: IconButton(
icon: const Icon(Icons.mic),
onPressed: () {
_showDialogFromBottom(context);
},
),
),
),
),
),
],
),
),
),
],
),
),
),
);
}
void _showDialogFromBottom(BuildContext context) {
showGeneralDialog(
context: context,
barrierDismissible: true,
barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
transitionDuration: const Duration(milliseconds: 400),
pageBuilder: (BuildContext buildContext, Animation<double> animation,
Animation<double> secondaryAnimation) {
return Center(
child: Material(
type: MaterialType.transparency,
child: ScaleTransition(
scale: CurvedAnimation(
parent: animation,
curve: Curves.fastOutSlowIn,
),
child: const Box(),
),
),
);
},
);
}
} |
import 'package:flutter/material.dart';
import 'package:smart_rent/core/values/app_colors.dart';
import 'package:get/get.dart';
class RecentlyDialogWidget extends StatelessWidget {
const RecentlyDialogWidget({
super.key,
required this.onPressed,
});
final Future<void> onPressed;
@override
Widget build(BuildContext context) {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
backgroundColor: Colors.transparent,
child: Card(
elevation: 0,
color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
Expanded(
child: Container(
decoration: BoxDecoration(
color: primary95,
border: Border.all(
width: 5,
color: Colors.transparent,
),
borderRadius: const BorderRadius.only(
topRight: Radius.circular(10),
topLeft: Radius.circular(10),
),
),
child: const Text(
'Cảnh báo xóa',
style: TextStyle(
color: primary40,
fontSize: 24,
fontWeight: FontWeight.w500,
),
textAlign: TextAlign.center,
),
),
),
],
),
const Text(
'Bạn có muốn xóa hết lịch sử phòng gần đấy không?',
style: TextStyle(
color: Colors.black,
fontSize: 16,
),
textAlign: TextAlign.center,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
OutlinedButton(
onPressed: () {
Get.back();
},
child: const Text('Không, đừng xóa'),
),
const Spacer(),
OutlinedButton(
onPressed: () {
onPressed;
Get.back(closeOverlays: true);
},
style: OutlinedButton.styleFrom(
foregroundColor: Colors.white,
backgroundColor: secondary40,
),
child: const Text('Có, xóa ngay'),
),
],
),
)
],
),
),
);
}
} |
<template>
<section id="search-section">
<Filters v-model="filters" id="filters" />
<div class="d-flex flex-column" id="search-results">
<div v-if="searchResults.length !== 0">
<FlightCard
v-for="result in searchResults"
:key="result.id"
:details="result"
class="mb-3"
/>
</div>
<div v-else>
<span class="search-results-empty"> По таким параметрам не удалось ничего найти</span>
</div>
</div>
</section>
</template>
<script>
import { mapActions } from "vuex";
import Filters from "@/components/Filters.vue";
import FlightCard from "@/components/FlightCard.vue";
export default {
name: "App",
components: {
Filters,
FlightCard,
},
async created() {
this.searchResults = await this.$store.dispatch("getFlights");
},
data() {
return {
searchResults: [],
filters: {},
};
},
watch: {
filters: {
deep: true,
handler(val) {
this.searchFlights(val);
},
}
},
methods: {
...mapActions(["getFlights", "filterFlights"]),
async searchFlights(filters = null) {
this.searchResults = await this.filterFlights(filters ?? null);
// await new Promise((res) => setTimeout(res, 100));
},
},
};
</script>
<style lang="scss" scoped>
#search-section {
display: flex;
flex-direction: row;
align-items: flex-start;
width: 100%;
max-width: 1200px;
margin: 100px auto 0;
// padding: 0 16px;
#filters {
position: -webkit-sticky;
position: sticky;
top: 20px;
width: 30%;
min-width: 10rem;
}
@media (max-width: 840px) {
flex-direction: column;
#filters {
position: relative;
top: 0;
width: 100%;
}
}
#search-results {
width: 100%;
margin-left: 20px;
@media (max-width: 840px) {
margin-top: 1.5rem;
margin-left: 0;
}
}
.search-results-empty {
font-size: 16px;
font-weight: 600;
}
}
</style> |
package cache
import (
"context"
"errors"
"github.com/go-redis/cache/v9"
"time"
)
type Cache interface {
Set(ctx context.Context, key string, value interface{}) error
Get(ctx context.Context, key string, dest interface{}) error
}
type Adapter struct {
cache *cache.Cache
ttl time.Duration
}
func NewCacheAdapter(ttl time.Duration, cache *cache.Cache) Cache {
return &Adapter{ttl: ttl, cache: cache}
}
func (adapter *Adapter) Set(ctx context.Context, key string, value interface{}) error {
return adapter.cache.Set(&cache.Item{
Ctx: ctx,
Key: key,
Value: value,
TTL: adapter.ttl,
})
}
func (adapter *Adapter) Get(ctx context.Context, key string, dest interface{}) error {
err := adapter.cache.Get(ctx, key, dest)
if errors.Is(err, cache.ErrCacheMiss) {
return nil
}
if err != nil {
return err
}
return nil
}
type Stub struct {
SetStub func(ctx context.Context, key string, value interface{}) error
GetStub func(ctx context.Context, key string, dest interface{}) error
RealAdapter Cache
}
func (cs Stub) Set(ctx context.Context, key string, value interface{}) error {
if cs.SetStub != nil {
return cs.SetStub(ctx, key, value)
}
if cs.RealAdapter != nil {
return cs.RealAdapter.Set(ctx, key, value)
}
panic("No real adapter or stub defined for Set")
}
func (cs Stub) Get(ctx context.Context, key string, dest interface{}) error {
if cs.GetStub != nil {
return cs.GetStub(ctx, key, dest)
}
if cs.RealAdapter != nil {
return cs.RealAdapter.Get(ctx, key, dest)
}
panic("No real adapter or stub defined for Get")
} |
@inject SweetAlertService swal
<NavigationLock OnBeforeInternalNavigation="OnBeforeInternalNavigation"></NavigationLock>
<EditForm Model="asignacionMateriales" OnValidSubmit="OnValidSubmit" ReturnAction="Return">
<DataAnnotationsValidator />
<div class="mb-3">
<label>Id: Materiales:</label>
<div>
<InputNumber @bind-Value="asignacionMateriales.IdMateriales" />
<ValidationMessage For="@(()=>asignacionMateriales.IdMateriales)" />
</div>
</div>
<div class="mb-3">
<label>Id: Tareas:</label>
<div>
<InputNumber @bind-Value="asignacionMateriales.IdTarea" />
<ValidationMessage For="@(()=>asignacionMateriales.IdTarea)" />
</div>
</div>
<button class="btn btn-primary" type="submit">Guardar</button>
<button class="btn btn-info" type="reset">Limpiar</button>
<button class="btn btn-success" @onclick="ReturnAction">Regresar</button>
</EditForm>
@code {
private EditContext editContext = null!;
protected override void OnInitialized()
{
editContext = new(asignacionMateriales);
}
[EditorRequired]
[Parameter]
public AsignacionMaterial asignacionMateriales { get; set; }
[EditorRequired]
[Parameter]
public EventCallback OnValidSubmit { get; set; }
[EditorRequired]
[Parameter]
public EventCallback ReturnAction { get; set; }
public bool FormularioPosteadoConExito { get; set; } = false;
private async Task OnBeforeInternalNavigation(LocationChangingContext context)
{
var formularioFueEditado = editContext.IsModified();
if (!formularioFueEditado)
{
return;
}
if (FormularioPosteadoConExito)
{
return;
}
var resultado = await swal.FireAsync(new SweetAlertOptions
{
Title = "Confirmación",
Text = "¿Deseas abandonar la página y perder los cambios?",
Icon = SweetAlertIcon.Warning,
ShowCancelButton = true
});
var confirmado = !string.IsNullOrEmpty(resultado.Value);
if (confirmado)
{
return;
}
context.PreventNavigation();
}
} |
import { CurveFactory, CurveFactoryLineOnly, NumberValue } from "d3";
import { Word } from "d3-cloud";
export type MapDataProps = {
x: string | number | Date;
y: number;
key: string;
stackedY: number;
defined: any;
};
type D3Function = (value: any, index: number, iterable: Iterable<any>) => any;
type BaseType = {
width: number;
height: number;
title: string;
color: Iterable<string> | string[];
};
type MapProps = {
getX: D3Function;
getY: D3Function;
getR: D3Function;
keys: Array<string>;
getGroup: D3Function;
getDes: D3Function;
};
type MarginProps = {
top: number;
bottom: number;
left: number;
right: number;
};
type AnimationProps = {
duration: number;
enabled: boolean;
};
type LegendProps = {
title: string;
enabled: boolean;
};
type XAxisProps = {
title: string;
domain:
| [undefined, undefined]
| [string, string]
| string[]
| Iterable<string>
| [number, number];
range: Array<number>;
type: any;
enabled: boolean;
tickRotation: number;
tickXOffset: number;
tickYOffset: number;
padding: number;
};
type YAxisProps = {
title: string;
domain:
| [undefined, undefined]
| [string, string]
| [number, number]
| Iterable<NumberValue>;
range: Array<number>;
type: any;
enabled: boolean;
};
type ZAxisProps = {
domain:
| [undefined, undefined]
| [string, string]
| [number, number]
| Iterable<NumberValue>;
range: Array<number>;
zMax: number;
};
type StrokeProps = {
color: Iterable<string>;
opacity: number;
width: number;
linecap: string;
linejoin: string;
enabled: boolean;
type: CurveFactory | CurveFactoryLineOnly;
};
type NodeProps = {
color: Iterable<string>;
radius: number;
enabled: boolean;
};
type ParserProps = {
time: string;
};
type FillProps = {
color: Iterable<string>;
nullColor: string;
opacity: number;
type: CurveFactory;
value: {
color: string;
enabled: boolean;
};
radius: {
x: number;
y: number;
};
};
type TooltipProps = {
mapper: Function;
enabled: boolean;
};
type TimeProps = {
type: Function;
};
type FontProps = {
family: string;
size: string;
};
export interface PieProps {
pie: {
radius: {
outer: number;
inner: number;
corner: number;
label: number;
};
value: {
color: string;
enabled: boolean;
};
padAngle: number;
enableLabel: boolean;
};
}
export type HeatmapProps = {
heatmap: {
cellSize: number;
utcParse: string;
monthParse: string;
formatUTCTip: string;
formatDay: any;
formatTick: string;
weekday: string;
};
};
export type WordProps = {
wordData: string;
word: {
size: {
range: [number, number];
domain: [number, number];
};
color: {
range: [string, string];
domain: [number, number];
};
padding: number;
mapper: {
getWord: Function;
getSize: Function;
rotation: (datum: Word, index: number) => number;
};
};
};
type EventHandler = {
onClick: (event: Event) => void;
};
export interface ChartStyle {
data: Array<object>;
base: BaseType;
mapper: MapProps;
margin: MarginProps;
colors: any;
animation: AnimationProps;
legend: LegendProps;
xAxis: XAxisProps;
yAxis: YAxisProps;
zAxis: ZAxisProps;
stroke: StrokeProps;
node: NodeProps;
parser: ParserProps;
fill: FillProps;
tooltip: TooltipProps;
time: TimeProps;
font: FontProps;
event: EventHandler;
ref?: React.MutableRefObject<SVGSVGElement | null>;
} |
package org.k8loud.executor.openstack.cinder;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.k8loud.executor.exception.OpenstackException;
import org.k8loud.executor.openstack.OpenstackCinderServiceImpl;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.openstack4j.api.storage.BlockVolumeSnapshotService;
import org.openstack4j.model.common.ActionResponse;
import org.openstack4j.model.storage.block.VolumeSnapshot;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.k8loud.executor.exception.code.OpenstackExceptionCode.DELETE_VOLUME_SNAPSHOT_FAILED;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
public class DeleteVolumeSnapshotTest extends OpenstackCinderBaseTest {
private static final String OLDEST_SNAPSHOT_NAME = "oldest";
private static final String OLDEST_SNAPSHOT_ID = "oldestId";
@Mock
BlockVolumeSnapshotService blockVolumeSnapshotServiceMock;
ArgumentCaptor<VolumeSnapshot> volumeSnapshotArgumentCaptor;
@Override
public void setUp() {
openstackCinderService = new OpenstackCinderServiceImpl();
when(volumeMock.getName()).thenReturn(VOLUME_NAME);
when(volumeMock.getId()).thenReturn(VOLUME_ID);
when(clientV3Mock.blockStorage()).thenReturn(blockStorageServiceMock);
when(blockStorageServiceMock.snapshots()).thenReturn(blockVolumeSnapshotServiceMock);
volumeSnapshotArgumentCaptor = ArgumentCaptor.forClass(VolumeSnapshot.class);
}
@ParameterizedTest
@MethodSource("goodParameters")
void testSuccess(List<VolumeSnapshot> snapshots, boolean keepOneSnapshot) throws OpenstackException {
// given
doReturn(snapshots).when(blockVolumeSnapshotServiceMock).list();
doReturn(ActionResponse.actionSuccess()).when(blockVolumeSnapshotServiceMock).delete(anyString());
// when
openstackCinderService.deleteTheOldestVolumeSnapshot(volumeMock, keepOneSnapshot, clientV3Mock);
// then
verify(blockVolumeSnapshotServiceMock).list();
verify(volumeMock).getName();
verify(volumeMock, times(snapshots.size())).getId();
verify(blockVolumeSnapshotServiceMock).delete(OLDEST_SNAPSHOT_ID);
}
@ParameterizedTest
@MethodSource("goodParameters")
void testResponseFailed(List<VolumeSnapshot> snapshots, boolean keepOneSnapshot) throws OpenstackException {
// given
doReturn(snapshots).when(blockVolumeSnapshotServiceMock).list();
doReturn(ActionResponse.actionFailed(EXCEPTION_MESSAGE, 123)).when(blockVolumeSnapshotServiceMock).delete(anyString());
// when
Throwable throwable = catchThrowable(() ->
openstackCinderService.deleteTheOldestVolumeSnapshot(volumeMock, keepOneSnapshot, clientV3Mock));
// then
verify(blockVolumeSnapshotServiceMock).list();
verify(volumeMock, times(2)).getName();
verify(volumeMock, times(snapshots.size())).getId();
}
private static Stream<Arguments> goodParameters(){
return Stream.of(
// keepOne=false and one snapshots to delete
Arguments.of(
List.of(
createMockSnapshot(null, randomLowerDate()),
createMockSnapshot("somethingElse", randomLowerDate()),
createTheOldestSnapshot()),
false
),
// keepOne=false and more than snapshots to delete
Arguments.of(
List.of(
createMockSnapshot("somethingElse", randomLowerDate()),
createMockSnapshot(null, randomLowerDate()),
createTheOldestSnapshot(),
createMockSnapshot(VOLUME_ID, randomBiggerDate()),
createMockSnapshot(VOLUME_ID, randomBiggerDate())),
false
),
// keepOne=true and more than one than snapshots to delete
Arguments.of(
List.of(
createMockSnapshot("somethingElse", randomLowerDate()),
createMockSnapshot(null, randomLowerDate()),
createTheOldestSnapshot(),
createMockSnapshot(VOLUME_ID, randomBiggerDate()),
createMockSnapshot(VOLUME_ID, randomBiggerDate())),
true
)
);
}
@ParameterizedTest
@MethodSource("badParameters")
void testFailed(List<VolumeSnapshot> snapshots, boolean keepOneSnapshot, String errorMessage) {
// given
doReturn(snapshots).when(blockVolumeSnapshotServiceMock).list();
// when
Throwable throwable = catchThrowable(() ->
openstackCinderService.deleteTheOldestVolumeSnapshot(volumeMock, keepOneSnapshot, clientV3Mock));
// then
verify(blockVolumeSnapshotServiceMock).list();
verify(volumeMock, times(2)).getName();
verify(volumeMock, times(snapshots.size())).getId();
verify(blockVolumeSnapshotServiceMock, never()).delete(anyString());
assertThat(throwable).isExactlyInstanceOf(OpenstackException.class)
.hasMessage(errorMessage);
assertThat(((OpenstackException) throwable).getExceptionCode()).isSameAs(DELETE_VOLUME_SNAPSHOT_FAILED);
}
private static Stream<Arguments> badParameters(){
return Stream.of(
// keepOne=true and one snapshots to delete
Arguments.of(
List.of(
createMockSnapshot("somethingElse", randomBiggerDate()),
createMockSnapshot(null, randomLowerDate()),
createTheOldestSnapshot()),
true,
String.format("Volume %s has 1 snapshot, and keepOneSnapshot was set on true", VOLUME_NAME)
),
// keepOne=true and zero snapshots to delete
Arguments.of(
List.of(
createMockSnapshot("somethingElse", randomLowerDate()),
createMockSnapshot(null, randomLowerDate())),
true,
String.format("Volume %s does not have any snapshots", VOLUME_NAME)
),
// keepOne=false and zero snapshots to delete
Arguments.of(
List.of(
createMockSnapshot("somethingElse", randomLowerDate()),
createMockSnapshot(null, randomLowerDate())),
false,
String.format("Volume %s does not have any snapshots", VOLUME_NAME)
)
);
}
private static VolumeSnapshot createTheOldestSnapshot(){
VolumeSnapshot snapshot = createMockSnapshot(VOLUME_ID, Date.from(Instant.now()));
lenient().when(snapshot.getId()).thenReturn(OLDEST_SNAPSHOT_ID);
lenient().when(snapshot.getName()).thenReturn(OLDEST_SNAPSHOT_NAME);
return snapshot;
}
private static VolumeSnapshot createMockSnapshot(String volumeId, Date createdAt) {
VolumeSnapshot snapshot = Mockito.mock(VolumeSnapshot.class);
when(snapshot.getVolumeId()).thenReturn(volumeId);
when(snapshot.getCreated()).thenReturn(createdAt);
return snapshot;
}
private static Date randomBiggerDate(){
return Date.from(Instant.now().plus(ThreadLocalRandom.current().nextInt(1, 11), ChronoUnit.DAYS));
}
private static Date randomLowerDate(){
return Date.from(Instant.now().minus(ThreadLocalRandom.current().nextInt(1, 11), ChronoUnit.DAYS));
}
} |
/*
* @Copyright 2018-2023 HardBackNutter
* @License GNU General Public License
*
* This file is part of NeverTooManyBooks.
*
* NeverTooManyBooks is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NeverTooManyBooks is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NeverTooManyBooks. If not, see <http://www.gnu.org/licenses/>.
*/
package com.hardbacknutter.nevertoomanybooks.dialogs;
import android.os.Bundle;
import android.os.Parcelable;
import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import java.util.Objects;
import java.util.function.Supplier;
/**
* Launcher to edit an in-place Parcelable object.
* <ul>
* <li>used for direct/in-place editing of an existing item</li>
* <li>modifications ARE STORED in the database</li>
* <li>returns the modified item.</li>
* </ul>
*
* @param <T> type of editable object
*/
public class EditInPlaceParcelableLauncher<T extends Parcelable>
extends EditLauncher {
@NonNull
private final OnModifiedCallback<T> onModifiedCallback;
public EditInPlaceParcelableLauncher(@NonNull final String requestKey,
@NonNull final Supplier<DialogFragment> dialogSupplier,
@NonNull final OnModifiedCallback<T> onModifiedCallback) {
super(requestKey, dialogSupplier);
this.onModifiedCallback = onModifiedCallback;
}
/**
* Set the result.
*
* @param fragment the fragment returning a result
* @param requestKey as received in the constructor
* @param item which was added
* @param <T> type of the item
*/
public static <T extends Parcelable> void setResult(@NonNull final Fragment fragment,
@NonNull final String requestKey,
@NonNull final T item) {
final Bundle result = new Bundle(1);
result.putParcelable(MODIFIED, item);
fragment.getParentFragmentManager().setFragmentResult(requestKey, result);
}
/**
* Launch the dialog.
*
* @param item to edit
*/
public void launch(@NonNull final T item) {
Objects.requireNonNull(fragmentManager, "fragmentManager");
final Bundle args = new Bundle(2);
args.putString(BKEY_REQUEST_KEY, requestKey);
args.putParcelable(BKEY_ITEM, item);
final DialogFragment dialogFragment = dialogFragmentSupplier.get();
dialogFragment.setArguments(args);
dialogFragment.show(fragmentManager, TAG);
}
@Override
public void onFragmentResult(@NonNull final String requestKey,
@NonNull final Bundle result) {
onModifiedCallback.onModified(requestKey,
Objects.requireNonNull(result.getParcelable(MODIFIED),
MODIFIED));
}
@FunctionalInterface
public interface OnModifiedCallback<T> {
/**
* Callback handler.
*
* @param requestKey the key as passed in
* @param modified the modified item
*/
void onModified(@NonNull String requestKey,
@NonNull T modified);
}
} |
#include "lists.h"
/**
* add_node - adds a new node at the beginning of linked list
* @head: A pointer point to the head
* @str: the new string
*
* Return: address of the new element, or NULL if it failed
*/
list_t *add_node(list_t **head, const char *str)
{
list_t *ptr;
ptr = malloc(sizeof(list_t));
if (ptr == NULL)
return (NULL);
ptr->str = strdup(str);
if (ptr->str == NULL)
{
free(ptr);
return (NULL);
}
ptr->len = strlen(str);
ptr->next = (*head);
*head = ptr;
return (ptr);
} |
import { useEffect, useState } from 'react';
import axios from 'axios';
import React from 'react'
// Import Swiper React components
import { Swiper, SwiperSlide } from 'swiper/react';
import SwiperCore, { Navigation } from 'swiper';
SwiperCore.use([Navigation]);
// Import Swiper styles
import 'swiper/css';import Header from 'components/header';
import Footer from 'components/footer';
import Link from 'next/link';
const Home = () => {
const [user, setUser] = useState(null);
const [seminarDataUpcoming, setseminarDataUpcoming] = useState(null);
const [seminarDataPast, setseminarDataPast] = useState(null);
useEffect(() => {
const token = localStorage.getItem('access_token');
axios
.get('https://walrus-app-elpr8.ondigitalocean.app/api/user', {
headers: { Authorization: `${token}` },
})
.then((response) => {
setUser(response.data);
console.log(response);
localStorage.setItem('user_name', `${response.data.name}`);
localStorage.setItem('user_email', `${response.data.email}`);
})
.catch((error) => {
console.log(error);
console.log(token);
});
}, []);
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get('https://walrus-app-elpr8.ondigitalocean.app/api/seminars/upcoming');
if (response) {
setseminarDataUpcoming(response.data); // Assuming the actual data is stored in response.data
}
} catch (error) {
console.log(error);
}
};
fetchData();
}, []);
useEffect(() => {
if (seminarDataUpcoming !== null) {
console.log(seminarDataUpcoming);
// Perform any other operations that depend on seminarDataUpcoming
}
}, [seminarDataUpcoming]);
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get('https://walrus-app-elpr8.ondigitalocean.app/api/seminars/past');
if (response) {
setseminarDataPast(response.data); // Assuming the actual data is stored in response.data
}
} catch (error) {
console.log(error);
}
};
fetchData();
}, []);
useEffect(() => {
if (seminarDataPast !== null) {
console.log(seminarDataPast);
// Perform any other operations that depend on seminarDataPast
}
}, [seminarDataPast]);
return (
<>
<Header user={user} />
{/* TOP Part */}
<div className="bg-primary-500 p-28">
<div className="container flex flex-row justify-between mx-auto gap-60">
{/* Left Side */}
<div className="flex-1">
<h1 className="text-5xl text-white font-semibold">Tingkatkan pengetahuanmu melalui seminar UNDIP</h1>
<h2 className="mt-4 text-lg text-white font-normal">
Bergabunglah dengan Seminar UNDIP, di mana kamu akan mendapat kesempatan untuk belajar dari para ahli industri dan pemikir terkemuka di bidangmu.
</h2>
{user ? (
<button className="mt-4 px-5 py-3 text-white rounded-lg bg-primary-300 hover:bg-primary-600 focus:bg-primary-600">
Hai {user && user.name}
</button>
) : (
<Link href="/Login">
<button className="mt-4 px-5 py-3 text-white rounded-lg bg-primary-300 hover:bg-primary-600 focus:bg-primary-600">Sign In</button>
</Link>
)}
</div>
{/* Right Side */}
<img className="hidden xl:block mt-12 xl:mt-0" src="/homeasset.svg" alt="" />
</div>
</div>
{/* Bottom Part */}
{/* Upcoming Seminar */}
<div className="bg-white px-28 py-24 flex flex-col justify-center gap-16">
<div className="gap-16">
<h1 className="text-4xl font-semibold flex justify-center">Upcoming Seminar</h1>
<h2 className="flex justify-center mt-7 text-lg font-normal">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text</h2>
</div>
<div className="container mx-auto relative h-full">
{/* Navigation buttons */}
<button className="swiper-button-prev-upcoming absolute left-0 top-1/2 transform -translate-y-1/2 bg-white p-3 rounded-full shadow-md z-10">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" className="w-8 h-8">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
</svg>
</button>
<button className="swiper-button-next-upcoming absolute right-0 top-1/2 transform -translate-y-1/2 bg-white p-3 rounded-full shadow-md z-10">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" className="w-8 h-8">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
</button>
<Swiper
spaceBetween={20}
slidesPerView={1}
breakpoints={{
640: {
slidesPerView: 2,
},
768: {
slidesPerView: 3,
},
1024: {
slidesPerView: 4,
},
}}
pagination={{ clickable: true }}
navigation={{ prevEl: '.swiper-button-prev-upcoming', nextEl: '.swiper-button-next-upcoming' }}
>
{seminarDataUpcoming &&
seminarDataUpcoming.map((seminar) => (
<SwiperSlide key={seminar.id}>
<div className="bg-white border border-transparent rounded-lg shadow overflow-hidden flex flex-col justify-between">
<a href="#">
<img className="rounded-t-lg object-cover" src="/homecard.svg" alt="" />
</a>
<div className="flex-grow p-5">
<a href="#">
<h5 className="mb-2 text-2xl font-bold tracking-tight text-black truncate">{seminar.name}</h5>
</a>
<p className="mb-3 font-normal text-black truncate">{seminar.short_description}.</p>
</div>
</div>
</SwiperSlide>
))}
</Swiper>
</div>
</div>
{/* Bottom Part */}
{/* Past Seminar*/}
<div className="bg-white px-28 py-24 flex flex-col justify-center gap-16">
<div className="gap-16">
<h1 className="text-4xl font-semibold flex justify-center">Past Seminar</h1>
<h2 className="flex justify-center mt-7 text-lg font-normal">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text</h2>
</div>
<div className="container mx-auto relative">
{/* Navigation buttons */}
<button className="swiper-button-prev-past absolute left-0 top-1/2 transform -translate-y-1/2 bg-white p-3 rounded-full shadow-md z-10">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" className="w-8 h-8">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
</svg>
</button>
<button className="swiper-button-next-past absolute right-0 top-1/2 transform -translate-y-1/2 bg-white p-3 rounded-full shadow-md z-10">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" className="w-8 h-8">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
</button>
<Swiper
spaceBetween={20}
slidesPerView={1}
breakpoints={{
640: {
slidesPerView: 2,
},
768: {
slidesPerView: 3,
},
1024: {
slidesPerView: 4,
},
}}
pagination={{ clickable: true }}
navigation={{ prevEl: '.swiper-button-prev-past', nextEl: '.swiper-button-next-past' }}
>
{seminarDataPast &&
seminarDataPast.map((seminar) => (
<SwiperSlide key={seminar.id}>
<div className="bg-white border border-transparent rounded-lg shadow">
<a href="#">
<img className="rounded-t-lg object-cover" src="/homecard.svg" alt="" />
</a>
<div className="p-5">
<a href="#">
<h5 className="mb-2 text-2xl font-bold tracking-tight text-black truncate">{seminar.name}</h5>
</a>
<p className="mb-3 font-normal text-black truncate">{seminar.short_description}.</p>
</div>
</div>
</SwiperSlide>
))}
</Swiper>
</div>
</div>
<Footer />
</>
);
};
export default Home; |
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<link rel="apple-touch-icon" type="image/png" href="https://cpwebassets.codepen.io/assets/favicon/apple-touch-icon-5ae1a0698dcc2402e9712f7d01ed509a57814f994c660df9f7a952f3060705ee.png" />
<meta name="apple-mobile-web-app-title" content="CodePen">
<link rel="shortcut icon" type="image/x-icon" href="https://cpwebassets.codepen.io/assets/favicon/favicon-aec34940fbc1a6e787974dcd360f2c6b63348d4b1f4e06c77743096d55480f33.ico" />
<link rel="mask-icon" type="" href="https://cpwebassets.codepen.io/assets/favicon/logo-pin-8f3771b1072e3c38bd662872f6b673a722f4b3ca2421637d5596661b4e2132cc.svg" color="#111" />
<title>CodePen - Pomodoro Clock</title>
<style>
* {
box-sizing: border-box;
}
body {
margin: 0px;
font-family: 'Arial', sans-serif;
background-color: #fff;
color: #fffff;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.pomodoro-container {
display: flex;
flex-flow: row wrap;
box-shadow: 0px 0px 1px 1px rgba(0,0,0,0.5);
border: 1px thin black;
border-radius: 1.5rem;
padding: 20px;
width: 225px;
}
.pomodoro-item {
width: 100%;
}
.label {
font-size: 0.8rem;
text-transform: uppercase;
color: #037ef3;
}
.row-pomodoro {
margin: 8px 0 16px 0;
text-align: center;
}
.playerButton {
border-top: solid 3px #ffd800;
padding-top: 12px;
}
.buttonRow {
display: flex;
justify-content: space-around;
}
.lengthTime {
display: inline-block;
padding: 0 20px 0 20px;
font-size: 35px;
}
.btn-updown {
font-size: 1.5rem;
width: 30px;
border: none;
border-radius: 50%;
cursor: pointer;
color: #fffff;
background: transparent;
box-shadow: 0px 0px 0px 0px rgba(0,0,0,0.0);
}
.btn-controller {
display: flex;
flex-flow: row wrap;
border: none;
cursor: pointer;
font-size: 1.5rem;
background-color: transparent;
color: #037ef3;
}
/* Pomodoro item row */
#timeLeft {
font-size: 3rem;
font-weight: 700;
}
</style>
<script>
window.console = window.console || function(t) {};
</script>
<script>
if (document.location.search.match(/type=embed/gi)) {
window.parent.postMessage("resize", "*");
}
</script>
</head>
<body translate="no" >
<!-- Pomodoro Container -->
<div class="pomodoro-container">
<!-- Session -->
<div class="pomodoro-item">
<div id="labelSessionBreak" class="label">Session</div>
<div class="row-pomodoro">
<div id="timeLeft">25:00</div>
</div>
</div>
<!-- Session Length -->
<div class="pomodoro-item">
<div class="label">Session Length</div>
<div class="row-pomodoro">
<button id="sessionDecrement" class="btn-updown">-</button>
<div id="sessionLength" class="row-pomodoro lengthTime">25</div>
<button id="sessionIncrement" class="btn-updown">+</button>
</div>
</div>
<!-- Break Length -->
<div class="pomodoro-item">
<div class="label">Break Length</div>
<div class="row-pomodoro">
<button id="breakDecrement" class="btn-updown">-</button>
<div id="breakLength" class="row-pomodoro lengthTime">5</div>
<button id="breakIncrement" class="btn-updown">+</button>
</div>
</div>
<!-- Play/Pause/Reset -->
<div class="pomodoro-item playerButton">
<div class="row-pomodoro buttonRow">
<button id="buttonPlay" class="btn-controller">
<i id="playIcon" class="fas fa-play" aria-hidden="true"></i>
</button>
<button id="buttonReset" class="btn-controller">
<i class="fas fa-sync" aria-hidden="true"></i>
</button>
</div>
</div>
</div>
<!-- Sound -->
<audio id="beep" src="https://www.soundjay.com/misc/sounds/bell-ringing-05.mp3"></audio>
<script src="https://cpwebassets.codepen.io/assets/common/stopExecutionOnTimeout-157cd5b220a5c80d4ff8e0e70ac069bffd87a61252088146915e8726e5d9f147.js"></script>
<script src='https://kit.fontawesome.com/ed4e9fbefd.js'></script>
<script id="rendered-js" >
/* Variables DOM */
const buttonPlay = document.getElementById('buttonPlay');
const playIcon = document.getElementById('playIcon');
const buttonReset = document.getElementById('buttonReset');
const timeLeftDOM = document.getElementById('timeLeft');
const labelSessionBreak = document.getElementById('labelSessionBreak');
const sessionLengthDOM = document.getElementById('sessionLength');
const breakLengthDOM = document.getElementById('breakLength');
const sessionDecrement = document.getElementById('sessionDecrement');
const sessionIncrement = document.getElementById('sessionIncrement');
const breakDecrement = document.getElementById('breakDecrement');
const breakIncrement = document.getElementById('breakIncrement');
/* Variables */
const arrayTime = timeLeftDOM.innerText.split(":");
let timeLeft = parseInt(arrayTime[0] * 60) + parseInt(arrayTime[1]); // timeLeft en secondes
let playIsClicked = true;
let isSession = false;
let breakLength = 5 * 60;
let timeLength = 25 * 60;
function convertSeconds(seconds) {
return {
minutes: Math.floor(seconds / 60), // nombre de minutes
seconds: seconds % 60 // nombre de secondes
};
}
let interval;
/* Handle play/pause Button */
buttonPlay.addEventListener('click', () => {
// Chrono start (play)
if (playIsClicked) {
if (interval) {
clearInterval(interval);
}
interval = setInterval(handleTime, 1000);
// Affichage icône pause
playIcon.classList.remove('fa-play');
playIcon.classList.add('fa-pause');
function handleTime() {
// Chrono finit
if (timeLeft <= 0) {
// Session
if (isSession) {
labelSessionBreak.innerText = "Session";
timeLeft = timeLength;
}
// Break
else {
labelSessionBreak.innerText = "Break";
timeLeft = breakLength;
document.getElementById('beep').currentTime = 0;
document.getElementById('beep').play();
}
isSession = !isSession;
}
// Arrêt du chrono
else if (playIsClicked) {
clearInterval(interval);
}
// Chrono en cours
else {
timeLeft--;
const minutesAndSeconds = convertSeconds(timeLeft);
timeLeftDOM.innerText = `${('0' + minutesAndSeconds.minutes).slice(-2)}:${('0' + minutesAndSeconds.seconds).slice(-2)}`;
}
}
}
// Chrono mis en pause
else {
// Affichage icône play
playIcon.classList.add('fa-play');
playIcon.classList.remove('fa-pause');
}
playIsClicked = !playIsClicked;
});
/* Handle reset button */
buttonReset.addEventListener('click', () => {
breakLength = 5 * 60;
timeLength = 25 * 60;
timeLeft = timeLength;
breakLengthDOM.innerText = "5";
sessionLengthDOM.innerText = "25";
timeLeftDOM.innerText = "25:00";
if (!playIsClicked) {
buttonPlay.click();
}
});
/* Handle length button */
function handleLengthButton(lengthValue, htmlElement, isAddition, isBreakLength) {
let result = 1;
if (isAddition) {
result = ++lengthValue;
htmlElement.innerText = result;
} else {
if (lengthValue != 1) {
result = --lengthValue;
htmlElement.innerText = result;
}
}
if (!playIsClicked) {
buttonPlay.click();
}
let resultSeconds = result * 60;
if (!isBreakLength) {
timeLength = resultSeconds;
if (labelSessionBreak.innerText === 'SESSION') {
timeLeftDOM.innerText = ('0' + result).slice(-2) + ":00";
timeLeft = resultSeconds;
}
} else {
breakLength = resultSeconds;
if (labelSessionBreak.innerText === 'BREAK') {
timeLeftDOM.innerText = ('0' + result).slice(-2) + ":00";
timeLeft = resultSeconds;
}
}
return resultSeconds;
}
sessionDecrement.addEventListener('click', () => {
handleLengthButton(parseInt(sessionLengthDOM.innerText), sessionLengthDOM, false, false);
});
sessionIncrement.addEventListener('click', () => {
handleLengthButton(parseInt(sessionLengthDOM.innerText), sessionLengthDOM, true, false);
});
breakDecrement.addEventListener('click', () => {
breakLength = handleLengthButton(parseInt(breakLengthDOM.innerText), breakLengthDOM, false, true);
});
breakIncrement.addEventListener('click', () => {
breakLength = handleLengthButton(parseInt(breakLengthDOM.innerText), breakLengthDOM, true, true);
});
//# sourceURL=pen.js
</script>
</body>
</html> |
import React, { useEffect, useState } from 'react'
import { Link } from 'react-router-dom';
import { YOUTUBE_VIDEOS_API } from '../utils/constant';
import Shimmer from './Shimmer';
import VideoCard, { AdVideoCard } from './VideoCard';
const VideoContainer = () => {
const [videos , setVideos] = useState([])
useEffect(()=>{
getVideos();
},[])
const getVideos = async () => {
const data = await fetch(YOUTUBE_VIDEOS_API)
const json = await data.json()
// console.log(json.items)
setVideos(json.items)
}
return (videos.length===0)? <Shimmer /> : (
<div className='flex flex-wrap'>
{/* AdVideoCard */}
{ videos[0] && <AdVideoCard info={videos[0]} />}
{
videos.map((video)=>
<Link key={video.id} to={"/watch/?v=" + video.id}>
<VideoCard info={video} />
</Link>
)
}
</div>
)
}
export default VideoContainer |
import 'package:flutter/material.dart';
import 'package:fl_components/theme/app_theme.dart';
import 'package:fl_components/router/app_routes.dart';
class HomeScreen extends StatelessWidget {
const HomeScreen({Key? key}) : super(key: key);
// ignore: annotate_overrides
Widget build(BuildContext context) {
final menuOptions = AppRoutes.menuOptions;
return Scaffold( // Scaffold no puede ser const
// el appBar depende del espacio de la pantalla, no const
appBar: AppBar(
centerTitle: true,
title: const Text('HOME'),
),
body:
ListView.separated(
//Lo que va a constuir
itemBuilder: (context, i) => ListTile(
//Cuanto estas iterando, se debe de poner el i, por la posicion donde esta
leading: Icon(menuOptions[i].icon, color: AppTheme.primary,),
// Nombre de las rutas
title: Text(AppRoutes.menuOptions[i].name),
onTap: () {
// ignore: unnecessary_string_interpolations
Navigator.pushNamed(context, '${menuOptions[i].route}');
},
),
separatorBuilder:(BuildContext context,i) => const Divider (),
//Numero de las rutas
itemCount: menuOptions.length)
);
}
} |
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateLedgerTransactionsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('ledger_transactions', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('ledger_id');
$table->unsignedBigInteger('ledgerTransaction_id');
$table->string('transaction_type');
$table->float('amount',10,2);
$table->text('transaction_note');
// $table->unsignedBigInteger('transaction_by_id')->nullable();
$table->string('ledgerTransaction_type');
$table->float('balance_after_transaction',10,2);
$table->foreign('ledger_id')->references('id')->on('ledgers')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('ledger_transactions');
}
} |
// Global scope is different in node and browser window
// let a = 10
// const b = 20
// var c = 30 // FYI doesn't work in block scope
// console.log(a); // 10
// console.log(b); // 20
// console.log(c); // 30
// var c = 300
if (true) {
let a = 10
const b = 20
// var c = 30
// we have problem of modifing c even we write it as
// c = 30
}
// console.log(a); // -> Error
// console.log(b); // -> Error
// console.log(c); // -> 30 , we can print value which is problematic
// though we have c as 300 before we still get 30 as the value
function one() {
const username = "adarsh";
function two() {
const website = "youtube"
console.log(username);
}
// console.log(website); // -> Error
two();
}
// one();
if (true) {
const username = "adarsh";
if (username === "adarsh") {
const website = " youtube"
// console.log(username + website);
}
// console.log(website);
}
// console.log(username);
// +++++++++++++++++++++++++++++++++++++++ INTERESTING ++++++++++++++++++++++++++++++++++++++++++++++++
console.log(addone(5)); // does work even called before declaration
function addone(num) {
return num + 1;
}
// addone(5); // doesn't print as there is no console
// addTwo(5); // error can't access before declaring
const addTwo = function(num) {
return num + 2;
}
// addTwo(5); |
//SourceUnit: NewShrimp.sol
pragma solidity 0.4.25;
contract TRC20 {
function totalSupply() public view returns(uint supply);
function balanceOf(address _owner) public view returns(uint balance);
function transfer(address _to, uint _value) public returns(bool success);
function transferFrom(address _from, address _to, uint _value) public returns(bool success);
function approve(address _spender, uint _value) public returns(bool success);
function allowance(address _owner, address _spender) public view returns(uint remaining);
function decimals() public view returns(uint digits);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
contract JustShrimp {
//uint256 EGGS_PER_SHRIMP_PER_SECOND=1;
uint256 public EGGS_TO_HATCH_1SHRIMP = 86400; //for final version should be seconds in a day
uint256 public STARTING_SHRIMP = 5; //reduced from 300
uint256 PSN = 10000;
uint256 PSNH = 5000;
bool public initialized = false;
address public ceoAddress;
mapping(address => uint256) public hatcheryShrimp;
mapping(address => uint256) public claimedEggs;
mapping(address => uint256) public lastHatch;
mapping(address => address) public referrals;
address public jst_address;
uint256 public marketEggs;
constructor(address _addr) public {
ceoAddress = msg.sender;
jst_address = _addr;
// seedMarket();
}
function hatchEggs(address ref) public {
require(initialized);
if (ref == msg.sender) {
ref = 0;
}
if (referrals[msg.sender] == 0 && referrals[msg.sender] != msg.sender) {
referrals[msg.sender] = ref;
}
uint256 eggsUsed = getMyEggs();
uint256 newShrimp = SafeMath.div(eggsUsed, EGGS_TO_HATCH_1SHRIMP);
hatcheryShrimp[msg.sender] = SafeMath.add(hatcheryShrimp[msg.sender], newShrimp);
claimedEggs[msg.sender] = 0;
lastHatch[msg.sender] = now;
//send referral eggs
claimedEggs[referrals[msg.sender]] = SafeMath.add(claimedEggs[referrals[msg.sender]], SafeMath.div(eggsUsed, 10));
//boost market to nerf shrimp hoarding
marketEggs = SafeMath.add(marketEggs, SafeMath.div(eggsUsed, 10));
}
function sellEggs() public {
require(initialized);
TRC20 tokenContract = TRC20(jst_address);
uint256 hasEggs = getMyEggs();
uint256 eggValue = calculateEggSell(hasEggs);
require(eggValue >= 1e6);
uint ConvertToJst = (eggValue* 1e18)/1e6;
uint256 fee = devFee(ConvertToJst);
claimedEggs[msg.sender] = 0;
lastHatch[msg.sender] = now;
marketEggs = SafeMath.add(marketEggs, hasEggs);
tokenContract.transfer(ceoAddress,fee);
uint _tran = SafeMath.sub(ConvertToJst, fee);
tokenContract.transfer(msg.sender, _tran);
}
function buyEggs(uint _amount) public payable {
require(initialized);
uint tokenAmount = _amount * 1e18;
TRC20 tokenContract = TRC20(jst_address);
require(tokenContract.allowance(msg.sender, address(this)) > 0);
tokenContract.transferFrom(msg.sender, address(this), tokenAmount);
uint256 eggsBought = calculateEggBuy(_amount * 1e6, SafeMath.sub(getBalance(), _amount * 1e6));
eggsBought = SafeMath.sub(eggsBought, devFee(eggsBought));
uint feedev = devFee(tokenAmount);
tokenContract.transfer(ceoAddress,feedev);
claimedEggs[msg.sender] = SafeMath.add(claimedEggs[msg.sender], eggsBought);
}
//magic trade balancing algorithm
function calculateTrade(uint256 rt, uint256 rs, uint256 bs) public view returns(uint256) {
//(PSN*bs)/(PSNH+((PSN*rs+PSNH*rt)/rt));
return SafeMath.div(SafeMath.mul(PSN, bs), SafeMath.add(PSNH, SafeMath.div(SafeMath.add(SafeMath.mul(PSN, rs), SafeMath.mul(PSNH, rt)), rt)));
}
function calculateEggSell(uint256 eggs) public view returns(uint256) {
TRC20 tokenContract = TRC20(jst_address);
return calculateTrade(eggs, marketEggs, getBalance());
}
function calculateEggBuy(uint256 eth, uint256 contractBalance) public view returns(uint256) {
return calculateTrade(eth, contractBalance, marketEggs);
}
function calculateEggBuySimple(uint256 eth) public view returns(uint256) {
TRC20 tokenContract = TRC20(jst_address);
return calculateEggBuy(eth, ((tokenContract.balanceOf(this)) / 1e18) * 1e6);
}
function devFee(uint256 amount) public view returns(uint256) {
return SafeMath.div(SafeMath.mul(amount, 10), 100);
}
function seedMarket() public payable {
require(marketEggs == 0);
initialized = true;
marketEggs = 864000000;
}
function getFreeShrimp() public {
require(initialized);
require(hatcheryShrimp[msg.sender] == 0);
lastHatch[msg.sender] = now;
hatcheryShrimp[msg.sender] = STARTING_SHRIMP;
}
function getBalance() public view returns(uint256) {
TRC20 tokenContract = TRC20(jst_address);
return ((tokenContract.balanceOf(this)) / 1e18) * 1e6; //convert to tron decimal
}
function getMyShrimp() public view returns(uint256) {
return hatcheryShrimp[msg.sender];
}
function getMyEggs() public view returns(uint256) {
return SafeMath.add(claimedEggs[msg.sender], getEggsSinceLastHatch(msg.sender));
}
function getEggsSinceLastHatch(address adr) public view returns(uint256) {
uint256 secondsPassed = min(EGGS_TO_HATCH_1SHRIMP, SafeMath.sub(now, lastHatch[adr]));
return SafeMath.mul(secondsPassed, hatcheryShrimp[adr]);
}
function min(uint256 a, uint256 b) private pure returns(uint256) {
return a < b ? a : b;
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns(uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns(uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns(uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns(uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} |
const std = @import("std");
const zglfw = @import("zglfw");
const zgpu = @import("zgpu");
const zgui = @import("zgui");
const assets_dir = @import("build-options").assets_dir;
const window_title = "Free Away Forum Admin";
const State = struct {
showDemo: bool,
user_window_size: [2]f32,
users: []const User,
};
const User = struct {
id: u64,
username: []const u8,
avatar_template: []const u8,
email: []const u8,
is_frozen: bool,
is_blocked: bool,
has_free_access: bool,
end_date: i64,
};
var state = State{
.showDemo = false,
.user_window_size = [2]f32{ 400.0, 0.0 },
.users = &.{
.{
.id = 1,
.username = "Dima",
.avatar_template = "",
.email = "mail@dimsuz.ru",
.is_frozen = false,
.is_blocked = false,
.has_free_access = true,
.end_date = 0,
},
.{
.id = 2,
.username = "Mint",
.avatar_template = "",
.email = "mail1@dimsuz.ru",
.is_frozen = false,
.is_blocked = false,
.has_free_access = true,
.end_date = 0,
},
},
};
fn ui_users(window_w: i32) void {
zgui.setNextWindowPos(.{ .x = 0.0, .y = 0.0, .cond = .first_use_ever });
state.user_window_size[1] = @floatFromInt(window_w);
zgui.setNextWindowSize(.{ .w = state.user_window_size[0], .h = state.user_window_size[1] });
if (zgui.begin("Users", .{ .flags = .{ .no_move = true } })) {
for (state.users) |u| {
ui_user_list_item(u);
}
if (zgui.button("Press me!", .{})) {
state.showDemo = true;
}
}
state.user_window_size[0] = zgui.getWindowSize()[0];
zgui.end();
if (state.showDemo) {
zgui.showDemoWindow(&state.showDemo);
}
}
fn ui_user_list_item(user: User) void {
if (zgui.beginChildId(zgui.getStrId(user.email), .{ .border = true, .h = 80.0 })) {
zgui.text("{s}", .{user.username});
zgui.text("{s}", .{user.email});
}
zgui.endChild();
}
pub fn main() !void {
zglfw.init() catch {
std.log.err("Failed to initialize GLFW library.", .{});
return;
};
defer zglfw.terminate();
// Change current working directory to where the executable is located.
{
var buffer: [1024]u8 = undefined;
const path = std.fs.selfExeDirPath(buffer[0..]) catch ".";
std.os.chdir(path) catch {};
}
const window = zglfw.Window.create(1200, 800, window_title, null) catch {
std.log.err("Failed to create window.", .{});
return;
};
defer window.destroy();
window.setSizeLimits(400, 400, -1, -1);
var gpa_state = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa_state.deinit();
const gpa = gpa_state.allocator();
const gctx = try zgpu.GraphicsContext.create(gpa, window, .{});
defer gctx.destroy(gpa);
const scale_factor = scale_factor: {
const scale = window.getContentScale();
break :scale_factor @max(scale[0], scale[1]);
};
zgui.init(gpa);
defer zgui.deinit();
_ = zgui.io.addFontFromFile(
assets_dir ++ "Roboto-Medium.ttf",
std.math.floor(16.0 * scale_factor),
);
zgui.backend.init(
window,
gctx.device,
@intFromEnum(zgpu.GraphicsContext.swapchain_format),
);
defer zgui.backend.deinit();
zgui.getStyle().scaleAllSizes(scale_factor);
while (!window.shouldClose() and window.getKey(.escape) != .press) {
zglfw.pollEvents();
zgui.backend.newFrame(
gctx.swapchain_descriptor.width,
gctx.swapchain_descriptor.height,
);
ui_users(window.getSize()[0]);
const swapchain_texv = gctx.swapchain.getCurrentTextureView();
defer swapchain_texv.release();
const commands = commands: {
const encoder = gctx.device.createCommandEncoder(null);
defer encoder.release();
// GUI pass
{
const pass = zgpu.beginRenderPassSimple(encoder, .load, swapchain_texv, null, null, null);
defer zgpu.endReleasePass(pass);
zgui.backend.draw(pass);
}
break :commands encoder.finish(null);
};
defer commands.release();
gctx.submit(&.{commands});
_ = gctx.present();
}
} |
/**
* @file backend.h This file contains the functionality to switch between math backends
*
* @author TPOC: palisade@njit.edu
*
* @copyright Copyright (c) 2017, New Jersey Institute of Technology (NJIT)
* All rights reserved.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef LBCRYPTO_MATH_BACKEND_H
#define LBCRYPTO_MATH_BACKEND_H
#include "utils/inttypes.h"
// use of MS VC is not permitted because of various incompatibilities
#ifdef _MSC_VER
#error "MSVC COMPILER IS NOT SUPPORTED"
#endif
////////// definitions for native integer and native vector
#include "native_int/binint.h"
#include "native_int/binvect.h"
#include <initializer_list>
typedef native_int::NativeInteger<uint64_t> NativeInteger;
typedef native_int::NativeVector<NativeInteger> NativeVector;
/*! Define the underlying default math implementation being used by defining MATHBACKEND */
// Each math backend is defined in its own namespace, and can be used at any time by referencing
// the objects in its namespace
// Selecting a math backend by defining MATHBACKEND means defining which underlying implementation
// is the default BigInteger and BigVector
// note that we #define how many bits the underlying integer can store as a guide for users of the backends
// MATHBACKEND 2
// Uses cpu_int:: definition as default
// Implemented as a vector of integers
// Configurable maximum bit length and type of underlying integer
// MATHBACKEND 4
// This uses exp_int:: definition as default
// This backend supports arbitrary bitwidths; no memory pool is used; can grow up to RAM limitation
// Configurable type of underlying integer (either 32 or 64 bit)
// passes all tests with UBINT_32
// fails tests with UBINT_64
// there is a bug in the way modulus is computed. do not use.
// MATHBACKEND 6
// This uses gmp_int:: definition as default
// GMP 6.1.2 / NTL 10.3.0 backend
//To select backend, please UNCOMMENT the appropriate line rather than changing the number on the
//uncommented line (and breaking the documentation of the line)
#ifndef MATHBACKEND
#define MATHBACKEND 2
//#define MATHBACKEND 4
//#define MATHBACKEND 6
#endif
#if MATHBACKEND != 2 && MATHBACKEND != 4 && MATHBACKEND != 6
#error "MATHBACKEND value is not valid"
#endif
////////// cpu_int code
typedef uint32_t integral_dtype;
/** Define the mapping for BigInteger
1500 is the maximum bit width supported by BigIntegeregers, large enough for most use cases
The bitwidth can be decreased to the least value still supporting BigInteger operations for a specific application -
to achieve smaller runtimes
**/
#ifndef BigIntegerBitLength
#define BigIntegerBitLength 1500 //for documentation on tests
#endif
#if BigIntegerBitLength < 600
#error "BigIntegerBitLength is too small"
#endif
inline const std::string& GetMathBackendParameters() {
static std::string id = "Backend " + std::to_string(MATHBACKEND) +
(MATHBACKEND == 2 ? " internal int size " + std::to_string(sizeof(integral_dtype)*8) + " BitLength " + std::to_string(BigIntegerBitLength) : "");
return id;
}
#include "cpu_int/binint.h"
#include "cpu_int/binvect.h"
static_assert(cpu_int::DataTypeChecker<integral_dtype>::value,"Data type provided is not supported in BigInteger");
////////// for exp_int, decide if you want 32 bit or 64 bit underlying integers in the implementation
#define UBINT_32
//#define UBINT_64
#ifdef UBINT_32
#define MATH_UBBITS 32
typedef uint32_t expdtype;
#undef UBINT_64 //cant have both accidentally
#endif
#ifdef UBINT_64
#define MATH_UBBITS 64
typedef uint64_t expdtype;
#undef UBINT_32 //cant have both accidentally
#endif
#include "exp_int/ubint.h" //dynamically sized unsigned big integers or ubints
#include "exp_int/mubintvec.h" //rings of ubints
namespace exp_int {
/** Define the mapping for ExpBigInteger (experimental) */
typedef ubint<expdtype> xubint;
/** Define the mapping for modulo Big Integer Vector */
typedef mubintvec<xubint> xmubintvec;
}
#include "gmp_int/gmpint.h" //experimental gmp unsigned big ints
//#include "gmp_int/mgmpint.h" //experimental gmp modulo unsigned big ints
//#include "gmp_int/gmpintvec.h" //vectors of such
#include "gmp_int/mgmpintvec.h" //rings of such
namespace gmp_int {
typedef NTL::myZZ ubint;
}
/**
* @namespace lbcrypto
* The namespace of lbcrypto
*/
namespace lbcrypto {
#if MATHBACKEND == 2
typedef cpu_int::BigInteger<integral_dtype,BigIntegerBitLength> BigInteger;
typedef cpu_int::BigVectorImpl<BigInteger> BigVector;
#endif
#if MATHBACKEND == 4
#ifdef UBINT_64
#error MATHBACKEND 4 with UBINT_64 currently does not work do not use.
#endif
typedef exp_int::xubint BigInteger;
typedef exp_int::xmubintvec BigVector;
#endif
#if MATHBACKEND == 6
/** Define the mapping for BigInteger */
typedef NTL::myZZ BigInteger;
/** Define the mapping for BigVector */
typedef NTL::myVecP<NTL::myZZ> BigVector;
#endif
template<typename IntType> class ILParamsImpl;
template<typename ModType, typename IntType, typename VecType, typename ParmType> class PolyImpl;
typedef ILParamsImpl<BigInteger> ILParams;
typedef ILParamsImpl<NativeInteger> ILNativeParams;
typedef PolyImpl<BigInteger, BigInteger, BigVector, ILParams> Poly;
typedef PolyImpl<NativeInteger, NativeInteger, NativeVector, ILNativeParams> NativePoly;
} // namespace lbcrypto ends
#endif |
<?php declare(strict_types=1);
namespace Shopware\Core\Content\Product;
use Shopware\Core\Framework\HttpException;
use Shopware\Core\Framework\Log\Package;
use Symfony\Component\HttpFoundation\Response;
#[Package('inventory')]
class ProductException extends HttpException
{
public const PRODUCT_INVALID_CHEAPEST_PRICE_FACADE = 'PRODUCT_INVALID_CHEAPEST_PRICE_FACADE';
public const PRODUCT_PROXY_MANIPULATION_NOT_ALLOWED_CODE = 'PRODUCT_PROXY_MANIPULATION_NOT_ALLOWED';
public const PRODUCT_INVALID_PRICE_DEFINITION_CODE = 'PRODUCT_INVALID_PRICE_DEFINITION';
public const CATEGORY_NOT_FOUND = 'PRODUCT__CATEGORY_NOT_FOUND';
public const SORTING_NOT_FOUND = 'PRODUCT_SORTING_NOT_FOUND';
public const PRODUCT_CONFIGURATION_OPTION_ALREADY_EXISTS = 'PRODUCT_CONFIGURATION_OPTION_EXISTS_ALREADY';
public static function invalidCheapestPriceFacade(string $id): self
{
return new self(
Response::HTTP_INTERNAL_SERVER_ERROR,
self::PRODUCT_INVALID_CHEAPEST_PRICE_FACADE,
'Cheapest price facade for product {{ id }} is invalid',
['id' => $id]
);
}
public static function sortingNotFoundException(string $key): self
{
return new self(
Response::HTTP_NOT_FOUND,
self::SORTING_NOT_FOUND,
self::$couldNotFindMessage,
['entity' => 'sorting', 'field' => 'key', 'value' => $key]
);
}
public static function invalidPriceDefinition(): self
{
return new self(
Response::HTTP_CONFLICT,
self::PRODUCT_INVALID_PRICE_DEFINITION_CODE,
'Provided price definition is invalid.'
);
}
public static function proxyManipulationNotAllowed(mixed $property): self
{
return new self(
Response::HTTP_INTERNAL_SERVER_ERROR,
self::PRODUCT_PROXY_MANIPULATION_NOT_ALLOWED_CODE,
'Manipulation of pricing proxy field {{ property }} is not allowed',
['property' => (string) $property]
);
}
public static function categoryNotFound(string $categoryId): self
{
return new self(
Response::HTTP_NOT_FOUND,
self::CATEGORY_NOT_FOUND,
self::$couldNotFindMessage,
['entity' => 'category', 'field' => 'id', 'value' => $categoryId]
);
}
public static function configurationOptionAlreadyExists(): self
{
return new self(
Response::HTTP_BAD_REQUEST,
self::PRODUCT_CONFIGURATION_OPTION_ALREADY_EXISTS,
'Configuration option already exists'
);
}
} |
import { useSharedState } from "@microsoft/live-share-react";
import { FC } from "react";
export const ExampleSharedState: FC = () => {
const [counterValue, setCounterValue] = useSharedState<number>(
"counter-id",
0
);
const [checkboxValue, setCheckboxValue] = useSharedState<boolean>(
"checkbox-id",
false
);
return (
<>
<div style={{ padding: "12px 8px" }}>
<h2>{"Click the button to iterate the counter"}</h2>
<button
onClick={() => {
setCounterValue(counterValue + 1);
}}
>
{"+1"}
</button>
<h1 style={{ color: "red" }}>{counterValue}</h1>
<input
type="checkbox"
id="accept"
name="accept"
checked={checkboxValue}
onChange={() => {
setCheckboxValue(!checkboxValue);
}}
/>
<label htmlFor="accept">{"Checked"}</label>
</div>
</>
);
}; |
###############################
# #
# Financial Analytics: #
# Scorecard Creation & #
# Reject Inference #
# #
# Dr Aric LaBarr #
# #
###############################
# Needed Libraries for Analysis #
install.packages("gmodels")
install.packages("vcd")
install.packages("smbinning")
install.packages("dplyr")
install.packages("stringr")
install.packages("shades")
install.packages("latticeExtra")
install.packages("plotly")
library(gmodels)
library(vcd)
library(smbinning)
library(dplyr)
library(stringr)
library(shades)
library(latticeExtra)
library(plotly)
# Load Needed Data Sets #
# Replace the ... below with the file location of the data sets #
setwd("...")
accepts <- read.csv(file = "accepts.csv", header = TRUE)
rejects <- read.csv(file = "rejects.csv", header = TRUE)
# Understand Target Variable #
table(accepts$bad)
accepts$good <- abs(accepts$bad - 1)
table(accepts$good)
# Setting Categorical Variables as Factors #
accepts$bankruptcy <- as.factor(accepts$bankruptcy)
accepts$used_ind <- as.factor(accepts$used_ind)
accepts$purpose <- as.factor(accepts$purpose)
# Create Training and Validation #
set.seed(12345)
train_id <- sample(seq_len(nrow(accepts)), size = floor(0.75*nrow(accepts)))
train <- accepts[train_id, ]
test <- accepts[-train_id, ]
table(train$good)
table(test$good)
# Information Value for Each Variable #
iv_summary <- smbinning.sumiv(df = train, y = "good")
smbinning.sumiv.plot(iv_summary)
iv_summary # Only Continuous Variables >= 0.1 IV #
# Binning of Continuous Variables - IV >= 0.1 #
num_names <- names(train)[sapply(train, is.numeric)] # Gathering the names of numeric variables in data #
result_all_sig <- list() # Creating empty list to store all results #
for(i in 1:length(num_names)){
check_res <- smbinning(df = train, y = "good", x = num_names[i])
if(check_res == "Uniques values < 5") {
next
}
else if(check_res == "No significant splits") {
next
}
else if(check_res$iv < 0.1) {
next
}
else {
result_all_sig[[num_names[i]]] <- check_res
}
}
# Generating Variables of Bins and WOE Values #
for(i in 1:length(result_all_sig)) {
train <- smbinning.gen(df = train, ivout = result_all_sig[[i]], chrname = paste(result_all_sig[[i]]$x, "_bin", sep = ""))
}
for (j in 1:length(result_all_sig)) {
for (i in 1:nrow(train)) {
bin_name <- paste(result_all_sig[[j]]$x, "_bin", sep = "")
bin <- substr(train[[bin_name]][i], 2, 2)
woe_name <- paste(result_all_sig[[j]]$x, "_WOE", sep = "")
if(bin == 0) {
bin <- dim(result_all_sig[[j]]$ivtable)[1] - 1
train[[woe_name]][i] <- result_all_sig[[j]]$ivtable[bin, "WoE"]
} else {
train[[woe_name]][i] <- result_all_sig[[j]]$ivtable[bin, "WoE"]
}
}
}
# Build Initial Logistic Regression #
initial_score <- glm(data = train, bad ~ tot_derog_WOE +
tot_tr_WOE +
age_oldest_tr_WOE +
tot_rev_line_WOE +
rev_util_WOE +
bureau_score_WOE +
#down_pyt_WOE +
ltv_WOE,
weights = train$weight, family = "binomial")
summary(initial_score)
# Variable Selected Logistic Regression #
initial_score_red <- glm(data = train, bad ~ #tot_derog_WOE +
#tot_tr_WOE +
age_oldest_tr_WOE +
tot_rev_line_WOE +
rev_util_WOE +
bureau_score_WOE +
#down_pyt_WOE +
ltv_WOE,
weights = train$weight, family = "binomial")
summary(initial_score_red)
# Evaluate the Initial Model - Training Data #
train$pred <- initial_score$fitted.values
smbinning.metrics(dataset = train, prediction = "pred", actualclass = "bad", report = 1)
smbinning.metrics(dataset = train, prediction = "pred", actualclass = "bad", report = 0, plot = "ks")
smbinning.metrics(dataset = train, prediction = "pred", actualclass = "bad", report = 0, plot = "auc")
#Evaluate the Initial Model - Testing Data #
for(i in 1:length(result_all_sig)) {
test <- smbinning.gen(df = test, ivout = result_all_sig[[i]], chrname = paste(result_all_sig[[i]]$x, "_bin", sep = ""))
}
for (j in 1:length(result_all_sig)) {
for (i in 1:nrow(test)) {
bin_name <- paste(result_all_sig[[j]]$x, "_bin", sep = "")
bin <- substr(test[[bin_name]][i], 2, 2)
woe_name <- paste(result_all_sig[[j]]$x, "_WOE", sep = "")
if(bin == 0) {
bin <- dim(result_all_sig[[j]]$ivtable)[1] - 1
test[[woe_name]][i] <- result_all_sig[[j]]$ivtable[bin, "WoE"]
} else {
test[[woe_name]][i] <- result_all_sig[[j]]$ivtable[bin, "WoE"]
}
}
}
test$pred <- predict(initial_score, newdata=test, type='response')
smbinning.metrics(dataset = test, prediction = "pred", actualclass = "bad", report = 1)
smbinning.metrics(dataset = test, prediction = "pred", actualclass = "bad", report = 0, plot = "ks")
smbinning.metrics(dataset = test, prediction = "pred", actualclass = "bad", report = 0, plot = "auc")
# Add Scores to Initial Model #
pdo <- 20
score <- 600
odds <- 50
fact <- pdo/log(2)
os <- score - fact*log(odds)
var_names <- names(initial_score$coefficients[-1])
for(i in var_names) {
beta <- initial_score$coefficients[i]
beta0 <- initial_score$coefficients["(Intercept)"]
nvar <- length(var_names)
WOE_var <- train[[i]]
points_name <- paste(str_sub(i, end = -4), "points", sep="")
train[[points_name]] <- -(WOE_var*(beta) + (beta0/nvar))*fact + os/nvar
}
colini <- (ncol(train)-nvar + 1)
colend <- ncol(train)
train$Score <- rowSums(train[, colini:colend])
hist(train$Score, breaks = 50, xlim = c(475,725), main = "Distribution of Train Scores", xlab = "Score")
for(i in var_names) {
beta <- initial_score$coefficients[i]
beta0 <- initial_score$coefficients["(Intercept)"]
nvar <- length(var_names)
WOE_var <- test[[i]]
points_name <- paste(str_sub(i, end = -4), "points", sep="")
test[[points_name]] <- -(WOE_var*(beta) + (beta0/nvar))*fact + os/nvar
}
colini <- (ncol(test)-nvar + 1)
colend <- ncol(test)
test$Score <- rowSums(test[, colini:colend])
hist(test$Score, breaks = 50, xlim = c(475,725), main = "Distribution of Test Scores", xlab = "Score")
accepts_scored <- rbind(train, test)
hist(accepts_scored$Score, breaks = 50, xlim = c(475,725), main = "Distribution of Scores", xlab = "Score")
# Plotting Default by Score in Train Data #
cutpoints <- quantile(train$Score, probs = seq(0,1,0.10))
train$Score.QBin <- cut(train$Score, breaks=cutpoints, include.lowest=TRUE)
Default.QBin.train <- round(table(train$Score.QBin, train$bad)[,2]/rowSums(table(train$Score.QBin, train$bad))*100,2)
print(Default.QBin.train)
Default.QBin.train.pop <- round(table(train$Score.QBin, train$bad)[,2]/(table(train$Score.QBin, train$bad)[,2] + table(train$Score.QBin, train$bad)[,1]*4.75)*100,2)
print(Default.QBin.train.pop)
# Plotting Default by Score in Test Data #
cutpoints <- quantile(test$Score, probs = seq(0,1,0.10))
test$Score.QBin <- cut(test$Score, breaks=cutpoints, include.lowest=TRUE)
Default.QBin.test <- round(table(test$Score.QBin, test$bad)[,2]/rowSums(table(test$Score.QBin, test$bad))*100,2)
print(Default.QBin.test)
barplot(Default.QBin.test,
main = "Default Decile Plot",
xlab = "Deciles of Scorecard",
ylab = "Default Rate (%)", ylim = c(0,60),
col = saturation(heat.colors, scalefac(0.8))(10))
abline(h = 20.5, lwd = 2, lty = "dashed")
text(11.5, 23, "Current = 20.5%")
Default.QBin.test.pop <- round(table(test$Score.QBin, test$bad)[,2]/(table(test$Score.QBin, test$bad)[,2] + table(test$Score.QBin, test$bad)[,1]*4.75)*100,2)
print(Default.QBin.test.pop)
barplot(Default.QBin.test.pop,
main = "Default Decile Plot",
xlab = "Deciles of Scorecard",
ylab = "Default Rate (%)", ylim = c(0,20),
col = saturation(heat.colors, scalefac(0.8))(10))
abline(h = 5.00, lwd = 2, lty = "dashed")
text(11.5, 6, "Current = 5.00%")
# Plotting Default, Acceptance, & Profit By Score #
def <- NULL
acc <- NULL
prof <- NULL
score <- NULL
cost <- 50000
profit <- 1200
for(i in min(floor(train$Score)):max(floor(train$Score))){
score[i - min(floor(train$Score)) + 1] <- i
def[i - min(floor(train$Score)) + 1] <- 100*sum(train$bad[which(train$Score >= i)])/(length(train$bad[which(train$Score >= i & train$bad == 1)]) + 4.75*length(train$bad[which(train$Score >= i & train$bad == 0)]))
acc[i - min(floor(train$Score)) + 1] <- 100*(length(train$bad[which(train$Score >= i & train$bad == 1)]) + 4.75*length(train$bad[which(train$Score >= i & train$bad == 0)]))/(length(train$bad[which(train$bad == 1)]) + 4.75*length(train$bad[which(train$bad == 0)]))
prof[i - min(floor(train$Score)) + 1] <- length(train$bad[which(train$Score >= i & train$bad == 1)])*(-cost) + 4.75*length(train$bad[which(train$Score >= i & train$bad == 0)])*profit
}
plot_data <- data.frame(def, acc, prof, score)
def_plot <- xyplot(def ~ score, plot_data,
type = "l" , lwd=2, col="red",
ylab = "Default Rate (%)",
xlab = "Score",
main = "Default Rate by Acceptance Across Score",
panel = function(x, y,...) {
panel.xyplot(x, y, ...)
panel.abline(h = 5.00, col = "red")
})
acc_plot <- xyplot(acc ~ score, plot_data,
type = "l", lwd=2, col="blue",
ylab = "Acceptance Rate (%)",
panel = function(x, y,...) {
panel.xyplot(x, y, ...)
panel.abline(h = 70, col = "blue")
})
prof_plot <- xyplot(prof/1000 ~ score, plot_data,
type = "l" , lwd=2, col="green",
ylab = "Profit (Thousands $)",
xlab = "Score",
main = "Profit by Acceptance Across Score"
)
doubleYScale(def_plot, acc_plot, add.ylab2 = TRUE, use.style=FALSE)
doubleYScale(prof_plot, acc_plot, add.ylab2 = TRUE, use.style=FALSE)
ay1 <- list(
title = "Default Rate (%)",
range = c(0, 5)
)
ay2 <- list(
tickfont = list(),
range = c(0, 100),
overlaying = "y",
side = "right",
title = "Acceptance Rate (%)"
)
fig <- plot_ly()
fig <- fig %>% add_lines(x = ~score, y = ~def, name = "Default Rate (%)")
fig <- fig %>% add_lines(x = ~score, y = ~acc, name = "Acceptance Rate (%)", yaxis = "y2")
fig <- fig %>% layout(
title = "Default Rate by Acceptance Across Score", yaxis = ay1, yaxis2 = ay2,
xaxis = list(title="Scorecard Value"),
legend = list(x = 1.2, y = 0.8)
)
fig
ay1 <- list(
title = "Profit ($)",
showline = FALSE,
showgrid = FALSE
)
ay2 <- list(
tickfont = list(),
range = c(0, 100),
overlaying = "y",
side = "right",
title = "Acceptance Rate (%)"
)
fig <- plot_ly()
fig <- fig %>% add_lines(x = ~score, y = ~prof, name = "Profit ($)")
fig <- fig %>% add_lines(x = ~score, y = ~acc, name = "Acceptance Rate (%)", yaxis = "y2")
fig <- fig %>% layout(
title = "Profit by Acceptance Across Score", yaxis = ay1, yaxis2 = ay2,
xaxis = list(title="Scorecard Value"),
legend = list(x = 1.2, y = 0.8)
)
fig
# Reject Inference - Clean & Prepare Reject Data #
for(i in names(result_all_sig)) {
result_all_sig[[i]]$bands[1] <- min(c(accepts[[i]], rejects[[i]]), na.rm = TRUE)
result_all_sig[[i]]$bands[length(result_all_sig[[i]]$bands)] <- max(c(accepts[[i]], rejects[[i]]), na.rm = TRUE)
}
for(i in 1:length(rejects[["ltv"]])){
rejects[["ltv"]][is.na(rejects[["ltv"]])] <- floor(mean(rejects[["ltv"]], na.rm = TRUE))
}
rejects_scored <- rejects
for(i in 1:length(result_all_sig)) {
rejects_scored <- smbinning.gen(df = rejects_scored, ivout = result_all_sig[[i]], chrname = paste(result_all_sig[[i]]$x, "_bin", sep = ""))
}
for (j in 1:length(result_all_sig)) {
for (i in 1:nrow(rejects_scored)) {
bin_name <- paste(result_all_sig[[j]]$x, "_bin", sep = "")
bin <- substr(rejects_scored[[bin_name]][i], 2, 2)
woe_name <- paste(result_all_sig[[j]]$x, "_WOE", sep = "")
if(bin == 0) {
bin <- dim(result_all_sig[[j]]$ivtable)[1] - 1
rejects_scored[[woe_name]][i] <- result_all_sig[[j]]$ivtable[bin, "WoE"]
} else {
rejects_scored[[woe_name]][i] <- result_all_sig[[j]]$ivtable[bin, "WoE"]
}
}
}
pdo <- 20
score <- 600
odds <- 50
fact <- pdo/log(2)
os <- score - fact*log(odds)
var_names <- names(initial_score$coefficients[-1])
for(i in var_names) {
beta <- initial_score$coefficients[i]
beta0 <- initial_score$coefficients["(Intercept)"]
nvar <- length(var_names)
WOE_var <- rejects_scored[[i]]
points_name <- paste(str_sub(i, end = -4), "points", sep="")
rejects_scored[[points_name]] <- -(WOE_var*(beta) + (beta0/nvar))*fact + os/nvar
}
colini <- (ncol(rejects_scored)-nvar + 1)
colend <- ncol(rejects_scored)
rejects_scored$Score <- rowSums(rejects_scored[, colini:colend])
# Reject Inference - Hard Cut-off #
rejects_scored$pred <- predict(initial_score, newdata=rejects_scored, type='response')
rejects$bad <- as.numeric(rejects_scored$pred > 0.0617)
rejects$good <- abs(rejects$bad - 1)
pop_g <- 22045
pop_b <- 1196
sam_g <- 4641
sam_b <- 1196
pop_sam_gb_ratio <- (pop_g/pop_b)/(sam_g/sam_b)
pop_a <- 0.7
pop_r <- 0.3
sam_a <- 5837
sam_r <- 4233
pop_sam_ar_ratio <- (pop_a/pop_r)/(sam_a/sam_r)
weight_rb <- 1
weight_rg <- pop_sam_gb_ratio
weight_ab <- pop_sam_ar_ratio
weight_ag <- pop_sam_ar_ratio*pop_sam_gb_ratio
accepts$weight_ar <- ifelse(accepts$bad == 1, weight_ab, weight_ag)
rejects$weight_ar <- ifelse(rejects$bad == 1, weight_rb, weight_rg)
comb_hard <- rbind(accepts[, !(names(accepts) == 'weight')], rejects) # New Combined Data Set #
# Reject Inference - Parcelling #
parc <- seq(500, 725, 25)
accepts_scored$Score_parc <- cut(accepts_scored$Score, breaks = parc)
rejects_scored$Score_parc <- cut(rejects_scored$Score, breaks = parc)
table(accepts_scored$Score_parc, accepts_scored$bad)
parc_perc <- table(accepts_scored$Score_parc, accepts_scored$bad)[,2]/rowSums(table(accepts_scored$Score_parc, accepts_scored$bad))
rejects$bad <- 0
rej_bump <- 1.25
for(i in 1:(length(parc)-1)) {
for(j in 1:length(rejects_scored$Score)) {
if((rejects_scored$Score[j] > parc[i]) &
(rejects_scored$Score[j] <= parc[i+1]) &
(runif(n = 1, min = 0, max = 1) < (rej_bump*parc_perc[i]))) {
rejects$bad[j] <- 1
}
}
}
table(rejects_scored$Score_parc, rejects$bad)
rejects$good <- abs(rejects$bad - 1)
accepts$weight_ar <- ifelse(accepts$bad == 1, weight_ab, weight_ag)
rejects$weight_ar <- ifelse(rejects$bad == 1, weight_rb, weight_rg)
comb_parc <- rbind(accepts[, !(names(accepts) == 'weight')], rejects) # New Combined Data Set #
# Reject Inference - Fuzzy Augmentation #
rejects_scored$pred <- predict(initial_score, newdata=rejects_scored, type='response')
rejects_g <- rejects
rejects_b <- rejects
rejects_g$bad <- 0
rejects_g$weight_ar <- (1-rejects_scored$pred)*weight_rg
rejects_g$good <- 1
rejects_b$bad <- 1
rejects_b$weight_ar <- (rejects_scored$pred)*weight_rb
rejects_b$good <- 0
accepts$weight_ar <- ifelse(accepts$bad == 1, weight_ab, weight_ag)
comb_fuzz <- rbind(accepts[, !(names(accepts) == 'weight')], rejects_g, rejects_b)
# Build Final Scorecard Model - Basically Repeating ALL Steps with New Data #
comb <- comb_parc # Select which data set you want to use from above techniques #
set.seed(12345)
train_id <- sample(seq_len(nrow(comb)), size = floor(0.75*nrow(comb)))
train_comb <- comb[train_id, ]
test_comb <- comb[-train_id, ]
iv_summary <- smbinning.sumiv(df = train_comb, y = "good")
smbinning.sumiv.plot(iv_summary)
iv_summary
num_names <- names(train_comb)[sapply(train_comb, is.numeric)] # Gathering the names of numeric variables in data #
result_all_sig <- list() # Creating empty list to store all results #
for(i in 1:length(num_names)){
check_res <- smbinning(df = train_comb, y = "good", x = num_names[i])
if(check_res == "Uniques values < 5") {
next
}
else if(check_res == "No significant splits") {
next
}
else if(check_res$iv < 0.1) {
next
}
else {
result_all_sig[[num_names[i]]] <- check_res
}
}
for(i in 1:length(result_all_sig)) {
train_comb <- smbinning.gen(df = train_comb, ivout = result_all_sig[[i]], chrname = paste(result_all_sig[[i]]$x, "_bin", sep = ""))
}
for (j in 1:length(result_all_sig)) {
for (i in 1:nrow(train_comb)) {
bin_name <- paste(result_all_sig[[j]]$x, "_bin", sep = "")
bin <- substr(train_comb[[bin_name]][i], 2, 2)
woe_name <- paste(result_all_sig[[j]]$x, "_WOE", sep = "")
if(bin == 0) {
bin <- dim(result_all_sig[[j]]$ivtable)[1] - 1
train_comb[[woe_name]][i] <- result_all_sig[[j]]$ivtable[bin, "WoE"]
} else {
train_comb[[woe_name]][i] <- result_all_sig[[j]]$ivtable[bin, "WoE"]
}
}
}
final_score <- glm(data = train_comb, bad ~ tot_tr_WOE +
tot_derog_WOE +
age_oldest_tr_WOE +
tot_rev_line_WOE +
rev_util_WOE +
bureau_score_WOE +
ltv_WOE
, weights = train_comb$weight_ar, family = "binomial")
summary(final_score)
train_comb$pred <- final_score$fitted.values
smbinning.metrics(dataset = train_comb, prediction = "pred", actualclass = "bad", report = 1)
smbinning.metrics(dataset = train_comb, prediction = "pred", actualclass = "bad", report = 0, plot = "ks")
smbinning.metrics(dataset = train_comb, prediction = "pred", actualclass = "bad", report = 0, plot = "auc")
for(i in 1:length(result_all_sig)) {
test_comb <- smbinning.gen(df = test_comb, ivout = result_all_sig[[i]], chrname = paste(result_all_sig[[i]]$x, "_bin", sep = ""))
}
for (j in 1:length(result_all_sig)) {
for (i in 1:nrow(test_comb)) {
bin_name <- paste(result_all_sig[[j]]$x, "_bin", sep = "")
bin <- substr(test_comb[[bin_name]][i], 2, 2)
woe_name <- paste(result_all_sig[[j]]$x, "_WOE", sep = "")
if(bin == 0) {
bin <- dim(result_all_sig[[j]]$ivtable)[1] - 1
test_comb[[woe_name]][i] <- result_all_sig[[j]]$ivtable[bin, "WoE"]
} else {
test_comb[[woe_name]][i] <- result_all_sig[[j]]$ivtable[bin, "WoE"]
}
}
}
test_comb$pred <- predict(final_score, newdata=test_comb, type='response')
smbinning.metrics(dataset = test_comb, prediction = "pred", actualclass = "bad", report = 1)
smbinning.metrics(dataset = test_comb, prediction = "pred", actualclass = "bad", report = 0, plot = "ks")
smbinning.metrics(dataset = test_comb, prediction = "pred", actualclass = "bad", report = 0, plot = "auc")
pdo <- 20
score <- 600
odds <- 50
fact <- pdo/log(2)
os <- score - fact*log(odds)
var_names <- names(final_score$coefficients[-1])
for(i in var_names) {
beta <- final_score$coefficients[i]
beta0 <- final_score$coefficients["(Intercept)"]
nvar <- length(var_names)
WOE_var <- train_comb[[i]]
points_name <- paste(str_sub(i, end = -4), "points", sep="")
train_comb[[points_name]] <- -(WOE_var*(beta) + (beta0/nvar))*fact + os/nvar
}
colini <- (ncol(train_comb)-nvar + 1)
colend <- ncol(train_comb)
train_comb$Score <- rowSums(train_comb[, colini:colend])
hist(train_comb$Score, breaks = 50, main = "Distribution of Scores", xlab = "Score")
for(i in var_names) {
beta <- final_score$coefficients[i]
beta0 <- final_score$coefficients["(Intercept)"]
nvar <- length(var_names)
WOE_var <- test_comb[[i]]
points_name <- paste(str_sub(i, end = -4), "points", sep="")
test_comb[[points_name]] <- -(WOE_var*(beta) + (beta0/nvar))*fact + os/nvar
}
colini <- (ncol(test_comb)-nvar + 1)
colend <- ncol(test_comb)
test_comb$Score <- rowSums(test_comb[, colini:colend])
hist(test_comb$Score, breaks = 50, main = "Distribution of Test Scores", xlab = "Score")
accepts_scored_comb <- rbind(train_comb, test_comb)
hist(accepts_scored_comb$Score, breaks = 50, xlim = c(450,650), main = "Distribution of Scores", xlab = "Score")
cutpoints <- quantile(accepts_scored_comb$Score, probs = seq(0,1,0.10))
accepts_scored_comb$Score.QBin <- cut(accepts_scored_comb$Score, breaks=cutpoints, include.lowest=TRUE)
Default.QBin.pop <- round(table(accepts_scored_comb$Score.QBin, accepts_scored_comb$bad)[,2]/(table(accepts_scored_comb$Score.QBin, accepts_scored_comb$bad)[,2] + table(accepts_scored_comb$Score.QBin, accepts_scored_comb$bad)[,1]*4.75)*100,2)
print(Default.QBin.pop)
barplot(Default.QBin.pop,
main = "Default Decile Plot",
xlab = "Deciles of Scorecard",
ylab = "Default Rate (%)", ylim = c(0,20),
col = saturation(heat.colors, scalefac(0.8))(10))
abline(h = 5, lwd = 2, lty = "dashed")
text(11.5, 5, "Current = 5.00%")
# Plotting Default, Acceptance, & Profit By Score #
def <- NULL
acc <- NULL
prof <- NULL
score <- NULL
cost <- 50000
profit <- 1200
for(i in min(floor(train_comb$Score)):max(floor(train_comb$Score))){
score[i - min(floor(train_comb$Score)) + 1] <- i
def[i - min(floor(train_comb$Score)) + 1] <- 100*sum(train_comb$bad[which(train_comb$Score >= i)])/(length(train_comb$bad[which(train_comb$Score >= i & train_comb$bad == 1)]) + 4.75*length(train_comb$bad[which(train_comb$Score >= i & train_comb$bad == 0)]))
acc[i - min(floor(train_comb$Score)) + 1] <- 100*(length(train_comb$bad[which(train_comb$Score >= i & train_comb$bad == 1)]) + 4.75*length(train_comb$bad[which(train_comb$Score >= i & train_comb$bad == 0)]))/(length(train_comb$bad[which(train_comb$bad == 1)]) + 4.75*length(train_comb$bad[which(train_comb$bad == 0)]))
prof[i - min(floor(train_comb$Score)) + 1] <- length(train_comb$bad[which(train_comb$Score >= i & train_comb$bad == 1)])*(-cost) + 4.75*length(train_comb$bad[which(train_comb$Score >= i & train_comb$bad == 0)])*profit
}
plot_data <- data.frame(def, acc, prof, score)
def_plot <- xyplot(def ~ score, plot_data,
type = "l" , lwd=2, col="red",
ylab = "Default Rate (%)",
xlab = "Score",
main = "Default Rate by Acceptance Across Score",
panel = function(x, y,...) {
panel.xyplot(x, y, ...)
panel.abline(h = 5.00, col = "red")
})
acc_plot <- xyplot(acc ~ score, plot_data,
type = "l", lwd=2, col="blue",
ylab = "Acceptance Rate (%)",
panel = function(x, y,...) {
panel.xyplot(x, y, ...)
panel.abline(h = 70, col = "blue")
})
prof_plot <- xyplot(prof/1000 ~ score, plot_data,
type = "l" , lwd=2, col="green",
ylab = "Profit (Thousands $)",
xlab = "Score",
main = "Profit by Acceptance Across Score"
)
doubleYScale(def_plot, acc_plot, add.ylab2 = TRUE, use.style=FALSE)
doubleYScale(prof_plot, acc_plot, add.ylab2 = TRUE, use.style=FALSE)
ay1 <- list(
title = "Default Rate (%)",
range = c(0, 10)
)
ay2 <- list(
tickfont = list(),
range = c(0, 100),
overlaying = "y",
side = "right",
title = "Acceptance Rate (%)"
)
fig <- plot_ly()
fig <- fig %>% add_lines(x = ~score, y = ~def, name = "Default Rate (%)")
fig <- fig %>% add_lines(x = ~score, y = ~acc, name = "Acceptance Rate (%)", yaxis = "y2")
fig <- fig %>% layout(
title = "Default Rate by Acceptance Across Score", yaxis = ay1, yaxis2 = ay2,
xaxis = list(title="Scorecard Value"),
legend = list(x = 1.2, y = 0.8)
)
fig
ay1 <- list(
title = "Profit ($)",
showline = FALSE,
showgrid = FALSE
)
ay2 <- list(
tickfont = list(),
range = c(0, 100),
overlaying = "y",
side = "right",
title = "Acceptance Rate (%)"
)
fig <- plot_ly()
fig <- fig %>% add_lines(x = ~score, y = ~prof, name = "Profit ($)")
fig <- fig %>% add_lines(x = ~score, y = ~acc, name = "Acceptance Rate (%)", yaxis = "y2")
fig <- fig %>% layout(
title = "Profit by Acceptance Across Score", yaxis = ay1, yaxis2 = ay2,
xaxis = list(title="Scorecard Value"),
legend = list(x = 1.2, y = 0.8)
)
fig |
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AppService } from '../../services/app.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-registeration',
templateUrl: './registeration.component.html',
styleUrls: ['./registeration.component.scss']
})
export class RegisterationComponent implements OnInit {
registerForm: FormGroup;
toogleclass: boolean;
constructor(private formBuilder: FormBuilder, public appService: AppService, private router: Router) {
this.registerForm = this.formBuilder.group({
'username': ['', Validators.required],
'password': ['', [Validators.required, Validators.minLength(6)]],
'email': ['', [Validators.required, Validators.email]],
'phone': ['', [Validators.required, Validators.pattern(new RegExp("[0-9 ]{10}"))]],
'grade': ['', [Validators.required]],
'section': ['', Validators.required],
'fname': ['', [Validators.required]],
'lname': ['', [Validators.required]],
'parentid': ['', [Validators.required]]
});
}
saveRegister() {
if (this.registerForm.dirty && this.registerForm.valid) {
const obj = {
fname: this.registerForm.value.fname,
lname: this.registerForm.value.lname,
username: this.registerForm.value.username,
password: this.registerForm.value.password,
grade: this.registerForm.value.grade,
section: this.registerForm.value.section,
email: this.registerForm.value.email,
phone: this.registerForm.value.phone,
parentid: this.registerForm.value.parentid,
};
this.appService.registerUser(obj).subscribe(data => {
if (data['status'] < 400) {
console.log('success');
sessionStorage.setItem('username', this.registerForm.value.username);
this.appService.user.username = this.registerForm.value.username;
this.router.navigate(['/dashboard']);
}
return true;
},
error => {
console.error('Error ');
});
}
}
ngOnInit(): void {
}
} |
package com.example.proyecto.servicios;
import com.example.proyecto.entidades.Comentario;
import com.example.proyecto.entidades.Proveedor;
import com.example.proyecto.entidades.Trabajo;
import com.example.proyecto.enumeraciones.EstadoTrabajo;
import com.example.proyecto.excepciones.MiException;
import com.example.proyecto.repositorios.ComentarioRepositorio;
import com.example.proyecto.repositorios.ProveedorRepositorio;
import com.example.proyecto.repositorios.TrabajoRepositorio;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;
//para ver entre todos
@Service
public class ComentarioServicio {
@Autowired
ComentarioRepositorio comentarioRepositorio;
@Autowired
TrabajoRepositorio trabajoRepositorio;
@Autowired
ProveedorRepositorio proveedorRepositorio;
@Autowired
WhatsappServicio whatsappServicio;
private List<String> forbiddenWords = Arrays.asList("palabra1", "palabra2", "groseria1", "groseria2");
public boolean containsForbiddenWords(String comment) {
return forbiddenWords.stream().anyMatch(comment::contains);
}
@Transactional
public void crearComentario(String contenido, Integer calificacion, Long idTrabajo) throws MiException {
Optional<Trabajo> trabajoRespuesta = trabajoRepositorio.findById(idTrabajo);
validarComentarios(contenido, calificacion);
Date fecha = new Date();
if (trabajoRespuesta.isPresent()) {
Trabajo trabajo = trabajoRespuesta.get();
if (trabajo.getEstadoTrabajo() == EstadoTrabajo.FINALIZADO) {
Proveedor proveedor = trabajo.getProveedor();
Integer contador = proveedor.getContdTrabajoRealizado();
Integer califProm = proveedor.getPuntuacionPromedio();
if(contador==null){
contador=0;
}
Integer general = ((califProm * contador) + calificacion) / (contador + 1);
proveedor.setContdTrabajoRealizado((contador + 1));
proveedor.setPuntuacionPromedio(general);
proveedorRepositorio.save(proveedor);
trabajo.setEstadoTrabajo(EstadoTrabajo.CALIFICADO);
String mensaje = trabajo.getProveedor().getNombre()
+ " " + trabajo.getProveedor().getApellido() + " Ha calificado tu Trabajo";
whatsappServicio.Notoficacion(trabajo.getCliente().getTelefono(), mensaje);
trabajoRepositorio.save(trabajo);
Comentario comentario = new Comentario(contenido, calificacion, fecha, true);
comentario.setTrabajo(trabajo);
comentarioRepositorio.save(comentario);
} else {
throw new MiException("El trabajo debe estar en estado FINALIZADO para agregar un comentario.");
}
} else {
throw new MiException("No se encontró un trabajo con el ID proporcionado: " + idTrabajo);
}
}
@Transactional
public void modificarComentarios(Long idTrabajo, String contenido, Integer calificacion, String id) throws MiException {
Optional<Comentario> respuesta = comentarioRepositorio.findById(id);
validarComentarios(contenido, calificacion);
Date fecha = new Date();
if (respuesta.isPresent()) {
Comentario comentario = respuesta.get();
if (comentario.isAltaBaja()) {
comentario.setContenido(contenido);
comentario.setCalificacion(calificacion);
comentario.setFechaHora(fecha);
comentarioRepositorio.save(comentario);
} else {
throw new MiException("El comentario está dado de baja, no se puede modificar.");
}
}
}
@Transactional
public List<Comentario> ListaComentarios() {
List<Comentario> comentarios = new ArrayList<>();
comentarios = comentarioRepositorio.findAll();
return comentarios;
}
//este lo agregue si no entienden pregunte
@Transactional
public List<Comentario> ListaComentariosPorProveedor(String idProveedor) {
List<Comentario> comentarios = new ArrayList<>();
comentarios = comentarioRepositorio.findAll();
for (Comentario comentario : comentarios) {
}
List<Comentario> comentariosProveedor = new ArrayList<>();
for (Comentario comentario : comentarios) {
if (comentario.getTrabajo().getProveedor().getDni().equalsIgnoreCase(idProveedor)) {
comentariosProveedor.add(comentario);
}
}
return comentariosProveedor;
}
@Transactional
@Secured("ROLE_ADMIN")
public void bajaComentario(String id) throws MiException {
Optional<Comentario> comentarioRespuesta = comentarioRepositorio.findById(id);
if (comentarioRespuesta.isPresent()) {
Comentario comentario = comentarioRespuesta.get();
// Verificar si ya está dado de baja
if (comentario.isAltaBaja()) {
comentario.setAltaBaja(false);
comentarioRepositorio.save(comentario);
} else {
throw new MiException("El comentario ya está dado de baja.");
}
} else {
throw new MiException("No se encontró un comentario con el ID proporcionado: " + id);
}
}
// }
@Transactional
private void validarComentarios(String contenido, Integer calificacion) throws MiException {
if (contenido == null || contenido.isEmpty()) {
throw new MiException(" El comentario no puede estar vacio, por favor complete este campo");
}
if (calificacion < 1 || calificacion > 5) {
throw new MiException(" La calificacion no puede ser igual a cero, calificar entre 1 y 5");
}
// List<Comentario> comentario = new ArrayList<>();
// comentario = ListaComentarios();
}
//SE AGREGO AL ULTIMO
//por fecha
@Transactional
public List<Comentario> ListaComentariosOrdenadosPorFecha() {
List<Comentario> comentarios = ListaComentarios();
Collections.sort(comentarios, Comparator.comparing(Comentario::getFechaHora));
return comentarios;
}
// Calificación de menor a mayor
@Transactional
public List<Comentario> ListaComentariosOrdenadosPorCalificacion() {
List<Comentario> comentarios = ListaComentarios();
Collections.sort(comentarios, Comparator.comparingInt(Comentario::getCalificacion));
return comentarios;
}
// Calificación de mayor a menor
@Transactional
public List<Comentario> ListaComentariosOrdenadosPorCalificacionMayor() {
List<Comentario> comentarios = ListaComentarios();
Collections.sort(comentarios, Comparator.comparingInt(Comentario::getCalificacion).reversed());
return comentarios;
}
public void calificacionPromedio(String dniProveedor) throws MiException {
// Obtener el proveedor por su DNI
Proveedor proveedor = proveedorRepositorio.findById(dniProveedor)
.orElseThrow(() -> new MiException("Proveedor no encontrado con DNI: " + dniProveedor));
/*
// Obtener todos los comentarios del proveedor
List<Comentario> comentarios = comentarioRepositorio.findByTrabajoProveedorDniAndAltaBaja(dniProveedor, true);
*/
List<Comentario> comentarios = new ArrayList();
// Calcular la suma de las calificaciones
int sumaCalificaciones = comentarios.stream()
.mapToInt(Comentario::getCalificacion)
.sum();
// Calcular el promedio
double promedioCalificaciones = comentarios.isEmpty() ? 0.0 : (double) sumaCalificaciones / comentarios.size();
// Actualizar la puntuación promedio del proveedor
proveedor.setPuntuacionPromedio((int) Math.round(promedioCalificaciones));
// Guardar el proveedor actualizado
proveedorRepositorio.save(proveedor);
}
} |
<ng-container *ngIf="isLoggedIn();else login">
<div class="principal-box overflow-hidden relative">
<app-aside (navbarBrand)="getTitle($event)" (openM)="openAsideModal($event)" (hideAside)="hideAside($event)"
[ngClass]="!toggleDrawer && innerWidth <= maxWidth? '-translate-x-full hidden' : 'translate-x-0'"
class="-translate-x-full" />
<app-navbar>
<h1 class="text-2xl font-bold truncate">{{navBarTitle || 'home' | capitalize}}</h1>
<div class="inline-options">
<button class="btn-add hover:shadow" (click)="toggleModal(true)">
<span class="mr-1 text-xs">
<i class="fa fa-plus"></i>
</span>{{'add new task'|capitalize}}
</button>
<button class="ml-3" [ngClass]="{'pointer-events-none': toggleDrawer}"
(click)="handleShowDrawer($event)">
<i class="fa fa-bars"></i>
</button>
</div>
</app-navbar>
<app-section class="h-full" [ngClass]="{'overflow-hidden': toggleDrawer, 'overflow-scroll':!toggleDrawer}">
<router-outlet />
</app-section>
<div class="absolute top-0 left-0 h-screen w-full bg-black transition-opacity duration-200 ease-in-out flex items-center justify-center"
[ngClass]="!toggleDrawer? 'opacity-0 pointer-events-none' : 'opacity-60'">
</div>
<app-layout-modal class="base-modal" [ngClass]="{'opacity-0 pointer-events-none': !modalOpened}"
(hideModal)="toggleModal($event)">
<app-add-task class="modal"
[ngClass]="{'scale-1 custom-transition': modalOpened, 'scale-0 custom-transition-revert':!modalOpened}" />
</app-layout-modal>
<app-layout-modal class="base-modal" [ngClass]="{'opacity-0 pointer-events-none': !createBoardModal}"
(hideModal)="toggleModalCreate($event)">
<app-create-board class="modal" (hideModal)="toggleModalCreate($event)"
[ngClass]="{'scale-1 custom-transition': createBoardModal, 'scale-0 custom-transition-revert':!createBoardModal}" />
</app-layout-modal>
<app-dropdown class="absolute top-0 right-0 m-8" [ngClass]="{'hidden': !dropdown}" />
</div>
</ng-container>
<ng-template #login>
<ng-container *ngComponentOutlet="loginComponent" />
</ng-template> |
import toast from "react-hot-toast";
import axios from "axios";
// import { useSelector } from "react-redux";
import { setToken, setUser } from "../slices/AuthSlice";
const API_URL = "http://localhost:4000/api/v1";
// Send Otp
export const sendOtp = async (formData, navigate) => {
try {
const { email } = formData;
const otpRes = await axios.post(`${API_URL}/sendOTP`, {
email,
});
if (otpRes) {
toast.success(otpRes.data.message);
navigate("/signup/verifyOTP");
}
// return otpRes.data;
} catch (error) {
console.log("OTP Verification Error", error);
toast.error(error.response.data.message);
}
};
export const signupStudent = async (formData, navigate) => {
try {
const {
name,
rollNumber,
dob,
email,
mobile,
password,
confirmPassword,
otp,
} = formData;
const response = await axios.post(`${API_URL}/signupStudent`, {
name,
rollNumber,
dob,
email,
mobile,
password,
confirmPassword,
otp,
});
if (response) {
toast.success(response.data.message);
}
// return otpRes.data;
} catch (error) {
console.error(error);
toast.error(error.response.data.message);
}
};
// Faculty Signup
export const signupFaculty = async (formData, navigate) => {
try {
const {
name,
facultyId,
dob,
email,
mobile,
password,
confirmPassword,
otp,
} = formData;
const response = await axios.post(`${API_URL}/signupFaculty`, {
name,
facultyId,
dob,
email,
mobile,
password,
confirmPassword,
otp,
});
if (response) {
toast.success(response.data.message);
}
} catch (error) {
console.error(error);
toast.error(error.response.data.message);
}
};
export function loginStudent(formData, navigate) {
return async (dispatch) => {
try {
const { email, password } = formData;
const response = await axios.post(`${API_URL}/loginStudent`, {
email,
password,
});
console.log(response.data);
if (response) {
toast.success(response.data.message);
dispatch(setToken(response.data.token));
dispatch(setUser(response.data.user));
// dispatch(setUser({ ...response.data.user, image: userImage }))
localStorage.setItem("token", JSON.stringify(response.data.token));
localStorage.setItem("user", JSON.stringify(response.data.user));
navigate("/dashboard");
return response.data;
} else {
toast.error("Not a registered user");
}
} catch (error) {
console.error(error);
// console.log(error.response.data.message)
toast.error(error.response.data.message);
}
};
}
export function loginFaculty(formData, navigate) {
return async (dispatch) => {
try {
const { email, password } = formData;
const response = await axios.post(`${API_URL}/loginFaculty`, {
email,
password,
});
if (response) {
toast.success(response.data.message);
}
dispatch(setToken(response.data.token));
dispatch(setUser(response.data.user));
// dispatch(setUser({ ...response.data.user, image: userImage }))
localStorage.setItem("token", JSON.stringify(response.data.token));
localStorage.setItem("user", JSON.stringify(response.data.user));
navigate("/dashboard");
return response.data;
} catch (error) {
console.error(error);
toast.error(error.response.data.message);
}
};
}
// API Call for Updating Program Details Of Student
export function insertProgram(formData, tokenObj, navigate) {
return async (dispatch) => {
try {
const {
programID,
admissionDate,
completionYear,
isCompletedInStipulatedTime,
} = formData;
const token = tokenObj;
const response = await axios.post(
`${API_URL}/student/insertEnrolledProgramDetails`,
{
programID: programID,
admissionDate: admissionDate,
completionYear: completionYear,
isCompletedInStipulatedTime: isCompletedInStipulatedTime,
token: token,
}
);
if (response) {
toast.success(response.data.message);
}
} catch (error) {
console.error(error);
toast.error(error.response.data.message);
}
};
}
// API change password
export function changeFacultyPassword(formData, tokenObj, navigate) {
return async (dispatch) => {
try {
const { currentPassword, newPassword } = formData;
const token = tokenObj;
const response = await axios.post(
`${API_URL}/changeFacultyPassword`,
{
oldPassword: currentPassword,
newPassword: newPassword,
token: token,
}
);
if (response) {
toast.success(response.data.message);
}
} catch (error) {
console.error(error);
toast.error(error.response.data.message);
}
};
}
// API change password
export function changeStudentPassword(formData, tokenObj, navigate) {
return async (dispatch) => {
try {
const { currentPassword, newPassword } = formData;
const token = tokenObj;
const response = await axios.post(
`${API_URL}/changeStudentPassword`,
{
oldPassword: currentPassword,
newPassword: newPassword,
token: token,
}
);
if (response) {
toast.success(response.data.message);
}
} catch (error) {
console.error(error);
toast.error(error.response.data.message);
}
};
}
export function logout(navigate) {
return (dispatch) => {
dispatch(setToken(null));
dispatch(setUser(null));
// dispatch(resetCart())
localStorage.removeItem("token");
localStorage.removeItem("user");
toast.success("Logged Out");
navigate("/");
};
}
// |
@page "/updaterecipe/{Id:int}"
@inject RecipeService RecServ
@inject NavigationManager NavMan
<h3 style="font-weight: bold">Edytuj przepis</h3>
@if (tags is not null && recipe is not null)
{
<RecipeForm Recipe="recipe" OnValidSubmit="Update" Tags="tags"/>
}
@code {
[Parameter]
public int Id{ get; init; }
List<TagDto>? tags;
RecipeAdapter recipe = new();
//Chcę zgarnąć ten recipe do edycji, wsadzić go do formularza i zmienić treść updaterecipe, żeby się zgadzała :)
async Task Update()
{
//przepis będzie mógł być zmieniony i zapisany do bazy
//mam sklejony przepis w recipe - jest typu recipeAdapter, po zmianach
//chcę zapisać przepis do bazy, wywołując metodę putRecipe, putIngredients, putTags
//zapis przepisu
await RecServ.UpdateRecipeAsync(recipe, recipe.RecipeID);
await RecServ.UpdateIngredientsInRecipeAsync(recipe.Ingridients, recipe.RecipeID);
await RecServ.UpdateTagsInRecipeAsync(recipe.Tags, recipe.RecipeID);
NavMan.NavigateTo("/mybook/" + 4);
}
protected override async Task OnInitializedAsync()
{
tags = await RecServ.GetTagListAsync();
}
protected override async Task OnParametersSetAsync()
{
recipe = await GetRecipe(Id);
}
async Task<RecipeAdapter> GetRecipe(int id)
{
HasIngridientDto hasIngrid = new();
recipe = await RecServ.GetRecipeAsync(id);
List<IngridientDto> ingredients = await RecServ.GetIngredientsListAsync(id);
List<TagDto> tags = await RecServ.GetTagsListAsync(id);
recipe.Ingridients = ingredients;
recipe.Tags = tags;
foreach (var item in recipe.Ingridients)
{
hasIngrid = await RecServ.GetIngredientAmountAsync(recipe.RecipeID, item.IngridientID);
item.Quantity = hasIngrid.Amount;
}
return recipe;
}
} |
class Product:
name: str
price: float
description: str
quantity: int
def __init__(self, name, price, description, quantity):
self.name = name
self.price = price
self.description = description
self.quantity = quantity
def check_quantity(self, quantity) -> bool:
return self.quantity >= quantity
def buy(self, quantity):
if self.check_quantity(quantity):
self.quantity -= quantity
else:
raise ValueError
def __hash__(self):
return hash(self.name + self.description)
class Cart:
products: dict[Product, int]
def __init__(self):
self.products = {}
def add_product(self, product: Product, buy_count=1):
if product in self.products:
self.products[product] += buy_count
else:
self.products[product] = buy_count
def remove_product(self, product: Product, remove_count=None):
if product in self.products:
if remove_count is None or remove_count >= self.products[product]:
del self.products[product]
else:
self.products[product] -= remove_count
def clear(self):
self.products.clear()
def get_total_price(self) -> float:
total_price = 0.0
for product, quantity in self.products.items():
total_price += product.price * quantity
return total_price
def buy(self):
for product, quantity in self.products.items():
if not product.check_quantity(quantity):
raise ValueError(f"Not enough quantity for product {product.name}")
product.buy(quantity)
self.clear() |
import 'package:cart_design_asignment/item_list.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
title: "Cart design",
home: Home(),
);
}
}
class Home extends StatefulWidget {
const Home({super.key});
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: [
IconButton(
onPressed: () {},
icon: const Icon(
Icons.search,
color: Colors.black,
),
)
],
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
"My Bag",
style: TextStyle(
fontSize: 34,
fontWeight: FontWeight.w700,
),
),
Expanded(
child: SingleChildScrollView(
child: Column(
children: [
Item(
image: 'images/pullover.jpg',
itemName: 'Pullover',
color: 'Black',
size: 'L',
quantity: 1,
price: 51,
),
Item(
image: 'images/tshirt.jpg',
itemName: 'T-Shirt',
color: 'Gray',
size: 'L',
quantity: 1,
price: 30,
),
Item(
image: 'images/sport_dress.jpg',
itemName: 'Sport Dress',
color: 'Black',
size: 'M',
quantity: 1,
price: 43,
),
],
),
),
),
Positioned(
bottom: 0,
child: Column(
children: [
const Text("Hello"),
SizedBox(
width: double.infinity,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(25),
),
textStyle: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w600,
),
padding: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 15,
),
),
onPressed: () {
ScaffoldMessenger.of(context)
.showSnackBar(const SnackBar(
content: Text(
'Congratulation! Yor purchase is successful.'),
backgroundColor: Colors.green,
duration: Duration(seconds: 1),
));
},
child: const Text('CHECK OUT'),
),
),
],
)),
],
),
),
// bottomNavigationBar: BottomNavigationBar(items: [Column()]),
);
}
} |
import type { ConfigCommands } from "../../types/structure/commands";
export default <ConfigCommands>{
name: "addmode",
alias: ["addmember"],
usage: "<on|off>",
category: "group setting",
description: "Add Other Members",
isGroup: true,
isGroupAdmin: true,
isBotAdmin: true,
example: `
*Option :* on | off
*Change the Add Other Members setting to All Members*
/addmode on
*Change the Add Other Members setting to Admin*
/addmode off`,
async run({ Chisato, from, args, message, Database, command }) {
const groupSetting = await Database.Group.get(from);
switch (args[0]) {
case "on":
if (groupSetting?.memberAddMode)
return Chisato.sendText(from, `GroupAddMode is still set to All Participants`, message);
await Chisato.groupMemberAddMode(from, "all_member_add");
await Database.Group.update(from, {
memberAddMode: true,
});
return Chisato.sendText(from, `The Add Other Members setting is now set to All Participants!`, message);
case "off":
if (!groupSetting?.memberAddMode)
return Chisato.sendText(from, `GroupAddMode is still set to Admin!`, message);
await Chisato.groupMemberAddMode(from, "admin_add");
await Database.Group.update(from, {
memberAddMode: false,
});
return Chisato.sendText(from, `The Add Other Members setting is now set to Admin!`, message);
default:
return Chisato.sendText(from, `Option not found!\n\n${command.example}`, message);
}
},
}; |
<div class="center-container" *ngIf="product">
<div class="product-card">
<div class="product-image">
<img [src]="product.processedImg" alt="{{product.name}} image">
</div>
<div class="product-details">
<h2>{{product.name}}</h2>
<p class="description">{{product.description}}</p>
<p class="price">Price:${{product.price}}</p>
<p class="category">Category:{{product.categoryName}}>
<mat-icon
class="heart-icon" (click)="addToWishlist()"
style="cursor: pointer;margin-top: 10px;">favorite_border</mat-icon>
</p>
</div>
</div>
</div>
<h1 class="section-heading" *ngIf="reviews.length>0">Customer Reviews</h1>
<div class="review-list" *ngIf="reviews">
<div class="center-container">
<div *ngFor="let review of reviews" class="review-card">
<div class="review-image">
<img [src]="review.processedImg" *ngIf="review.processedImg" alt="{{review.description}} Image"
class="small-image">
</div>
<div class="review-details">
<h2>{{review.description}}</h2>
<div class="details-row">
<p class="rating">Rating: {{review.rating}}</p>
<p class="username">Username: {{review.username}}</p>
</div>
</div>
</div>
</div>
</div>
<h1 class="section-heading" *ngIf="FAQS.length>0">Frequently asked question</h1>
<div class="faq-list" *ngIf="FAQS">
<div class="center-container">
<div *ngFor="let faq of FAQS" class="faq-card">
<div class="faq-details">
<P class="question">Question:</P>
<p class="question-text">{{faq.question}}</p>
<p class="answer">Answer:</p>
<p class="answer-text">{{faq.answer}}</p>
</div>
</div>
</div>
</div> |
from transformers import GPT2Tokenizer, GPT2LMHeadModel, AdamW
from torch.utils.data import DataLoader, Dataset
import torch
# Load the dataset
class MyDebiasedDataset(Dataset):
def __init__(self, file_path):
# Load and preprocess the data
with open(file_path, 'r', encoding='utf-8') as file:
self.examples = [line.strip() for line in file.readlines()]
def __len__(self):
return len(self.examples)
def __getitem__(self, idx):
return self.examples[idx]
# Create dataset and dataloader
file_path = '/Users/brendanmurphy/Desktop/CS330 META/PROJECT/project_code/train.txt'
dataset = MyDebiasedDataset(file_path) #train_small.txt is 50 sentences, train.txt is 3680 this is COUNTERFACTUAL DATA AUGMENTATION
dataloader = DataLoader(dataset, batch_size=8, shuffle=True) #batch_size=32
model = GPT2LMHeadModel.from_pretrained('gpt2')
tokenizer = GPT2Tokenizer.from_pretrained('gpt2', padding_side='left')
model.train()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=5e-5)
epochs = 1
tokenizer.pad_token = tokenizer.eos_token
# Dictionary to store RGN values for each layer
layer_rgn = {}
# Fine-tuning loop
with open('rgn_values.txt', 'w') as file:
for epoch in range(epochs):
for batch in dataloader:
inputs = tokenizer(batch, return_tensors='pt', padding=True, truncation=True, max_length=512).to(device)
outputs = model(**inputs, labels=inputs["input_ids"])
loss = outputs.loss
loss.backward()
# Calculate RGN for each layer
for name, param in model.named_parameters():
if 'weight' in name and param.requires_grad: # Consider only trainable weights
grad_norm = torch.norm(param.grad)
param_norm = torch.norm(param)
rgn = grad_norm / param_norm if param_norm != 0 else 0
if name not in layer_rgn:
layer_rgn[name] = []
layer_rgn[name].append(rgn.item())
file.write(f"Layer {name}, RGN: {rgn:.4f}\n")
print(f"Layer {name}, RGN: {rgn:.4f}")
optimizer.step()
optimizer.zero_grad()
print(f"Epoch: {epoch}, Loss: {loss.item()}")
# Save the model
model.save_pretrained('/Users/brendanmurphy/Desktop/CS330 META/PROJECT/project_code/saved_rgn_models')
# Calculate the average RGN for each layer
average_rgn = {layer: np.mean(rgns) for layer, rgns in layer_rgn.items()}
# Sort layers by RGN in descending order
sorted_layers = sorted(average_rgn.items(), key=lambda x: x[1], reverse=True)
# Select top 10-20% of layers
percentage = 0.15 # for 10%, adjust as needed
num_layers_to_select = int(len(sorted_layers) * percentage)
layers_to_finetune = [layer for layer, _ in sorted_layers[:num_layers_to_select]]
print("Layers to fine-tune based on top RGN values:", layers_to_finetune)
layers_to_ft = ['transformer.h.0.ln_1.weight', 'transformer.h.1.ln_2.weight', 'transformer.h.2.ln_2.weight', 'transformer.h.1.ln_1.weight', 'transformer.h.2.ln_1.weight', 'transformer.h.0.ln_2.weight', 'transformer.h.6.ln_2.weight', 'transformer.h.4.ln_2.weight', 'transformer.h.5.ln_2.weight', 'transformer.h.7.ln_2.weight', 'transformer.h.8.ln_2.weight']
#['transformer.h.0.ln_1.weight', 'transformer.h.1.ln_2.weight', 'transformer.h.2.ln_2.weight', 'transformer.h.1.ln_1.weight', 'transformer.h.2.ln_1.weight', 'transformer.h.0.ln_2.weight', 'transformer.h.6.ln_2.weight', 'transformer.h.4.ln_2.weight', 'transformer.h.5.ln_2.weight', 'transformer.h.7.ln_2.weight', 'transformer.h.8.ln_2.weight']
#THRESHOLD METHOD
# Calculate average RGN for each layer
#average_rgn = {k: np.mean(v) for k, v in layer_rgn.items()}
# Determine a threshold for RGN (this is a sample threshold, adjust based on your analysis)
#rgn_threshold = 0.01 # Example threshold
# Identify layers exceeding the threshold
#layers_to_finetune = [layer for layer, avg_rgn in average_rgn.items() if avg_rgn > rgn_threshold]
#print("Layers to fine-tune based on RGN threshold:", layers_to_finetune) |
#!/usr/bin/env python
#coding:utf-8
import pandas as pd
import itertools
def csp(candidates, players, team, requested_positions_attributes, budget):
"""Beginning of CSP algorithm for finding a valid combination of players.
Parameters
----------
candidates : pandas.core.frame.DataFrame
The dataset containing players from which we will choose.
players : list
The list in which to store our combination of players
team : str
The team specified by the user/manager.
requested_positions_attributes : list
The list of position/attribute pairs specified by the user/manager
budget : int
The transfer budget specified by the user/manager.
Side effects
----------
If no position/attribute pairs were specified, determines the team's weak links among their
common players and sets the positions to search for to equal these positions. Then runs backtracking.
"""
if len(requested_positions_attributes) == 0:
suggested_positions = team_positional_needs(candidates, team)
print("No positions specified; suggesting based on following weaknesses:")
print(suggested_positions)
backtracking(candidates.to_dict(orient='records'), players, team, suggested_positions, budget)
else:
requested_positions = positions(requested_positions_attributes)
backtracking(candidates.to_dict(orient='records'), players, team, requested_positions, budget)
def backtracking(candidates, players, team, requested_positions, budget):
"""Backtracking algorithm for finding a valid combination of players.
Parameters
----------
candidates : pandas.core.frame.DataFrame
The dataset containing players from which we will choose.
players : list
The list of players currently in our set of choices.
team : str
The team specified by the user/manager.
requested_positions_attributes : list
The list of position/attribute pairs we still have yet to choose a player for. (Initially
the full set specified by the user/manager)
budget : int
The transfer budget specified by the user/manager.
Returns
----------
The first found combination of players satisfying the team, budget, and position
constraints.
"""
# If there are no more positions to find players for, we are done"""
if len(requested_positions) == 0:
return True
else:
candidates_temp = candidates.copy()
requested_positions_updated = requested_positions.copy()
while(len(candidates_temp) > 0):
# Try adding every other player to our choices
player = candidates.pop(0) # in the candidates list, to be checked
# If this player satisfies constraints, add them to our choices
if Is_valid(player, team, requested_positions, budget):
players.append(player)
requested_positions_updated.remove(player['position'])
candidates_temp.remove(player)
# Next step of recursion
if backtracking(candidates_temp, players, team, requested_positions_updated, budget - player['price']):
return True
# Backtrack
players.pop()
requested_positions_updated.append(player['position'])
candidates_temp.append(player)
return False
def Is_valid(player, team, requested_positions, budget):
"""Predicate checking if given player satisfies team, position, and budget constraints.
Parameters
----------
player : (?)
The player we are validating.
team : str
The team specified by the user/manager.
requested_positions_attributes : list
The list of position/attribute pairs we still have yet to choose a player for.
budget : int
The remaining unallocated portion of the transfer budget specified by the user/manager.
Returns
----------
Whether or not the player given is a valid addition to the selection.
"""
# Player's price must be within budget
if budget < player['price'] :
return False
# Player's position must be one we are looking for
if player['position'] not in requested_positions:
return False
# Player must not already be on team
if player['team'] == team:
return False
return True
def hill_climb(candidates, init_state, team, requested_positions_attributes, budget):
"""Hill-climbing algorithm for improving on the initial CSP solution.
Parameters
----------
candidates : pandas.core.frame.DataFrame
The dataset containing players from which we will choose.
init_state : list
The combination of players in the current state
team : str
The team specified by the user/manager.
requested_positions_attributes : list
The list of positions/attributes specified by the user/manager.
budget : int
The transfer budget specified by the user/manager.
Returns
----------
The combination of players satisfying the budget, position, and attribute requirements
with the maximal heuristic.
"""
cur_state = init_state
while True:
max_attribute_assignment_value, max_attribute_assignment_permutation = max_attribute_assignment(cur_state, requested_positions_attributes)
# print_output(cur_state, max_attribute_assignment_permutation)
# print(heur(cur_state, requested_positions_attributes, budget))
neighbors = generate_neighbors(candidates, cur_state, team, budget)
best_neighbor = max(neighbors, key=lambda x: heur(x, requested_positions_attributes, budget))
if heur(best_neighbor, requested_positions_attributes, budget) <= heur(cur_state, requested_positions_attributes, budget):
return cur_state
cur_state = best_neighbor
def generate_neighbors(candidates, players, team, budget):
"""Generates all neighbors for the hill-climbing algorithm.
Parameters
----------
candidates : pandas.core.frame.DataFrame
The dataset containing players from which we will choose.
players : list
The combination of players in the current state
team : str
The team specified by the user/manager.
budget : int
The transfer budget specified by the user/manager.
Returns
----------
The list of all states in which a transition has been made by swapping one player
for another who plays the same position.
"""
result = []
for pos in unique_positions(players):
candidates_pos = candidates[candidates['position'] == pos]
for cur_player in players_at_position(players, pos):
for _, new_player in candidates_pos.iterrows():
if new_player.to_dict() not in players and new_player['team'] != team:
new_state_players = players.copy()
new_state_budget = total_price(players)
new_state_players.remove(cur_player)
new_state_budget -= cur_player['price']
new_state_players.append(new_player.to_dict())
new_state_budget += new_player['price']
if new_state_budget <= budget:
result.append(new_state_players)
return result
def heur(players, requested_positions_attributes, budget):
"""Heuristic for hill-climbing algorithm.
Parameters
----------
players : list
The combination of players in the current state
requested_positions_attributes : list
The list of positions/attributes specified by the user/manager.
budget : int
The transfer budget specified by the user/manager.
Returns
----------
The heuristic for the current state, which uses the formula:
result = rating_comp + 1.5*budget_comp + 2*attr_comp
where
rating_comp = the average player rating,
budget_comp = the proportion of the transfer budget used, and
attr_comp = the maximal sum resulting from assigning each player in players
one attribute associated with their position and summing the min-max-normalized
values of the corresponding player statistics.
"""
max_attribute_assignment_value, _ = max_attribute_assignment(players, requested_positions_attributes)
result = 0.0
rating_comp = 0.0
budget_comp = 0.0
attr_comp = 0.0
for player in players:
rating_comp += player['rating'] / len(players)
budget_comp += 1.5 * proportion_of_budget(player, budget)
if len(players) != 0:
attr_comp = 2 * max_attribute_assignment_value / len(players)
result += rating_comp
result += budget_comp
result += attr_comp
return result
def positions(requested_positions_attributes):
"""Gets just the positions from a list of position/attribute pairs.
Parameters
----------
requested_positions_attributes : list
A list of position/attribute pairs.
Returns
----------
The list of positions only.
"""
requested_positions = []
for x in requested_positions_attributes:
requested_positions.append(x[0])
return requested_positions
def attributes_at_position(requested_positions_attributes, pos):
"""Gets just the attributes associated with some position from a
list of position/attribute pairs.
Parameters
----------
requested_positions_attributes : list
A list of position/attribute pairs.
pos : str
The position whose attributes to extract.
Returns
----------
The list of attributes associated with the given position.
"""
requested_attributes = []
for x in requested_positions_attributes:
if x[0] == pos:
requested_attributes.append(x[1])
return requested_attributes
def max_attribute_assignment(players, requested_positions_attributes):
"""Computes the maximal sum of normalized player statistics corresponding to their
assigned attributes over all possible assignments of attributes to players.
Parameters
----------
players : list
The combination of players in the current state
requested_positions_attributes : list
The list of positions/attributes specified by the user/manager.
Returns
----------
result_value : int
The aforementioned maximal sum.
result_permutation: list
The order of assigning attributes to the position-sorted list of players that
produces this maximal sum.
"""
requested_positions = unique_positions(players)
result_value = 0.0
result_permutation = []
for position in requested_positions:
players_at_pos = players_at_position(players, position)
position_attributes = attributes_at_position(requested_positions_attributes, position)
max_position_sum = -20.0
attribute_permutations = list(itertools.permutations(position_attributes))
for permutation in attribute_permutations:
cur_position_sum = 0.0
for i in range(len(players_at_pos)):
if not permutation[i] == 'None':
cur_position_sum += players_at_pos[i][permutation[i]]
if cur_position_sum > max_position_sum:
max_position_sum = cur_position_sum
cur_position_permutation = permutation
result_value += max_position_sum
result_permutation += cur_position_permutation
return result_value, result_permutation
def total_price(players):
"""Computes the total price of all players in a list.
Parameters
----------
players : list
The combination of players in the current state
Returns
----------
The players' total price.
"""
result = 0
for player in players:
result += player['price']
return result
def proportion_of_budget(player, budget):
"""Computes the proportion of the budget used by a player.
Parameters
----------
player : (?)
The player being considered.
budget : int
The transfer budget specified by the user/manager.
Returns
----------
The player's price divided by the transfer budget.
"""
return player['price'] / budget
def unique_positions(players):
"""Returns the set of unique positions played by a set of players.
Parameters
----------
players : list
The combination of players in the current state
Returns
----------
The unique positions played by the players.
"""
result = set()
for player in players:
result.add(player['position'])
return result
def players_at_position(players, pos):
"""Returns the set of players playing a given position.
Parameters
----------
players : list
The combination of players in the current state
pos : str
The position to search for.
Returns
----------
The list of players playing the given position.
"""
result = []
for player in players:
if player['position'] == pos:
result.append(player)
return result
def team_positional_needs(candidates, team):
"""Algorithm for determining the weak spots on a given team's roster (if the user/manager
does not enter any positions.)
Parameters
----------
candidates : pandas.core.frame.DataFrame
The dataset containing players from which we will choose.
team : str
The team specified by the user/manager.
Returns
----------
The list of positions (possibly including duplicates) where among the players on the given team
who have played the equivalent of at least 10 games (approximately a fourth of a full season),
the Z-score (with respect to all players on the team) of the player at that position is -1 or less.
"""
df_team_roster = candidates[candidates['team'] == team]
df_common_players = df_team_roster[df_team_roster['games'] >= 10]
text_cols = df_common_players.select_dtypes(include='object')
numerical_cols = df_common_players.select_dtypes(include=['float', 'int'])
normalized_numerical_cols = (numerical_cols - numerical_cols.mean()) / numerical_cols.std()
df_common_players_norm = pd.concat([normalized_numerical_cols, text_cols], axis=1)
df_common_weaknesses = df_common_players_norm[df_common_players_norm['rating'] < -1]
df_common_weaknesses = df_common_weaknesses.sort_values(by=['rating'], ascending=True)
if len(df_common_weaknesses) == 0:
# Find the index of the row with the lowest rating
min_rating_index = df_common_players_norm['rating'].idxmin()
# Get the position of the row with the lowest rating
position_lowest_rating = df_common_players_norm.at[min_rating_index, 'position']
# print("Lowest rating position is:", position_lowest_rating)
return [position_lowest_rating]
return df_common_weaknesses['position'].to_list()[:5]
# Unique Non-GK Positions:
# Attacking Midfield (M)
# Central Midfield (M)
# Centre-Back (D)
# Centre-Forward (F)
# Centre Midfield (M)
# Defensive Midfield (M)
# Left Winger (F)
# Left-Back (D)
# Left Midfield (M)
# Right Winger (F)
# Right-Back (D)
# Right Midfield (M)
# Second Striker (F)
def print_output(output, max_attribute_assignment_permutation):
"""Prints information about the players in the given state.
Parameters
----------
output : list
The combination of players in the state to output
max_attribute_assignment_permutation : list
The order in which the position-sorted list of players is assigned attributes
that results in the maximal sum of normalized player stats
Returns
----------
The name, position, team, price, rating, and (if applicable) attribute of each player
in the output list.
"""
unique_pos_list = unique_positions(players)
i = 0
# Print all players at a given position before moving on to the next, since the permutation
# lists all attributes for one position, then another, and so on
for position in unique_pos_list:
for player in output:
if player['position'] == position:
if max_attribute_assignment_permutation[i] == 'None':
print('name:', player['name'],
'position:', player['position'],
'team:', player['team'],
'price:', player['price'],
'rating:', round(player['rating'], 3))
else:
print('name:', player['name'],
'position:', player['position'],
'team:', player['team'],
'price:', player['price'],
'rating:', round(player['rating'], 3),
max_attribute_assignment_permutation[i], round(player[max_attribute_assignment_permutation[i]], 3))
i += 1
if __name__ == '__main__':
import pandas as pd
## Load candidates
df_transfers = pd.read_csv('new_player_scores.csv')
# Pick useful information
df_transfers = df_transfers[['Player', '90s', 'sub_position', 'Squad', 'market_value_in_eur', 'score', 'FK', 'SoT', 'PrgDist', 'Blocks', 'CrsPA', 'KP']]
# Rename columns
df_transfers.columns=['name', 'games', 'position', 'team', 'price', 'rating', 'Free-kick Specialist', 'Sharp-shooter', 'Playmaker', 'Impenetrable Wall', 'Crossing Specialist', 'Assisting Machine']
# Normalize data (with min-max)
data_to_normalize = df_transfers[['Free-kick Specialist', 'Sharp-shooter', 'Playmaker', 'Impenetrable Wall', 'Crossing Specialist', 'Assisting Machine']]
data_not_to_normalize = df_transfers[['name', 'games', 'position', 'team', 'price', 'rating']]
data_normalized = (data_to_normalize - data_to_normalize.min()) / (data_to_normalize.max() - data_to_normalize.min())
df_transfers_norm = pd.concat([data_not_to_normalize, data_normalized], axis=1)
## budget and requeted_position. We can change it to input file later
# The following is just for testing now
budget = 100000000
team = 'Clermont Foot'
requested_positions_attributes = [['Right-Back', 'Playmaker']]
# initial condition
players = [] # the players we choose under restrictions
csp(df_transfers_norm, players, team, requested_positions_attributes, budget)
if len(requested_positions_attributes) == 0:
suggested_positions = team_positional_needs(df_transfers_norm, team)
requested_positions_attributes = [[position, 'None'] for position in suggested_positions]
players = hill_climb(df_transfers_norm, players, team, requested_positions_attributes, budget)
_, max_attribute_assignment_permutation = max_attribute_assignment(players, requested_positions_attributes)
print_output(players, max_attribute_assignment_permutation) |
/*This is the class creation of a board piece for the chessboard*/
#include<string>
#include<iostream>
using namespace std;
#ifndef PIECE_H
#define PIECE_H
class Piece
{
protected:
/* Information about the piece including its coordinate on the board by file and rank and its team*/
char rank;
char file;
int team;
public:
/*Piece constructor*/
Piece(char inital_rank, char initial_file, int team_colour);
/*public functions to set the piece position variables to the values found in new_position and find the value of the team for the piece*/
void set_position(string new_position);
int get_colour() {return team;}
/*Virtual function to check if a piece is able to move in a specific format */
virtual int make_move(char* new_position)=0;
/*Virtual function to check the name of a piece*/
virtual string get_id()=0;
virtual char get_symbol()=0;
/*Virtual piece constructor*/
virtual ~Piece(){}
};
#endif |
//===- ae.cpp -- Abstract Execution -------------------------------------//
//
// SVF: Static Value-Flow Analysis
//
// Copyright (C) <2013-2017> <Yulei Sui>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
//===-----------------------------------------------------------------------===//
/*
// Abstract Execution
//
// Author: Jiawei Wang, Xiao Cheng, Jiawei Yang, Jiawei Ren, Yulei Sui
*/
#include "SVF-LLVM/SVFIRBuilder.h"
#include "WPA/WPAPass.h"
#include "Util/CommandLine.h"
#include "Util/Options.h"
#include "AE/Svfexe/BufOverflowChecker.h"
#include "AE/Core/RelExeState.h"
#include "AE/Core/RelationSolver.h"
using namespace SVF;
using namespace SVFUtil;
static Option<bool> SYMABS(
"symabs",
"symbolic abstraction test",
false
);
class SymblicAbstractionTest
{
public:
SymblicAbstractionTest() = default;
~SymblicAbstractionTest() = default;
static z3::context& getContext()
{
return Z3Expr::getContext();
}
void test_print()
{
outs() << "hello print\n";
}
IntervalESBase RSY_time(IntervalESBase& inv, const Z3Expr& phi,
RelationSolver& rs)
{
auto start_time = std::chrono::high_resolution_clock::now();
IntervalESBase resRSY = rs.RSY(inv, phi);
auto end_time = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(
end_time - start_time);
outs() << "running time of RSY : " << duration.count()
<< " microseconds\n";
return resRSY;
}
IntervalESBase Bilateral_time(IntervalESBase& inv, const Z3Expr& phi,
RelationSolver& rs)
{
auto start_time = std::chrono::high_resolution_clock::now();
IntervalESBase resBilateral = rs.bilateral(inv, phi);
auto end_time = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(
end_time - start_time);
outs() << "running time of Bilateral: " << duration.count()
<< " microseconds\n";
return resBilateral;
}
IntervalESBase BS_time(IntervalESBase& inv, const Z3Expr& phi,
RelationSolver& rs)
{
auto start_time = std::chrono::high_resolution_clock::now();
IntervalESBase resBS = rs.BS(inv, phi);
auto end_time = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(
end_time - start_time);
outs() << "running time of BS : " << duration.count()
<< " microseconds\n";
return resBS;
}
void testRelExeState1_1()
{
outs() << sucMsg("\t SUCCESS :") << "test1_1 start\n";
IntervalESBase itv;
RelExeState relation;
// var0 := [0, 1];
itv[0] = IntervalValue(0, 1);
relation[0] = getContext().int_const("0");
// var1 := var0 + 1;
relation[1] =
getContext().int_const("1") == getContext().int_const("0") + 1;
itv[1] = itv[0] + IntervalValue(1);
// Test extract sub vars
Set<u32_t> res;
relation.extractSubVars(relation[1], res);
assert(res == Set<u32_t>({0, 1}) && "inconsistency occurs");
IntervalESBase inv = itv.sliceState(res);
RelationSolver rs;
const Z3Expr& relExpr = relation[1];
const Z3Expr& initExpr = rs.gamma_hat(inv);
const Z3Expr& phi = (relExpr && initExpr).simplify();
IntervalESBase resRSY = rs.RSY(inv, phi);
IntervalESBase resBilateral = rs.bilateral(inv, phi);
IntervalESBase resBS = rs.BS(inv, phi);
// 0:[0,1] 1:[1,2]
assert(resRSY == resBS && resBS == resBilateral && "inconsistency occurs");
for (auto r : resRSY.getVarToVal())
{
outs() << r.first << " " << r.second << "\n";
}
IntervalESBase::VarToValMap intendedRes = {{0, IntervalValue(0, 1)}, {1, IntervalValue(1, 2)}};
assert(IntervalESBase::eqVarToValMap(resBS.getVarToVal(), intendedRes) && "inconsistency occurs");
}
void testRelExeState1_2()
{
outs() << "test1_2 start\n";
IntervalESBase itv;
RelExeState relation;
// var0 := [0, 1];
relation[0] = getContext().int_const("0");
itv[0] = IntervalValue(0, 1);
// var1 := var0 + 1;
relation[1] =
getContext().int_const("1") == getContext().int_const("0") * 2;
itv[1] = itv[0] * IntervalValue(2);
// Test extract sub vars
Set<u32_t> res;
relation.extractSubVars(relation[1], res);
assert(res == Set<u32_t>({0, 1}) && "inconsistency occurs");
IntervalESBase inv = itv.sliceState(res);
RelationSolver rs;
const Z3Expr& relExpr = relation[1];
const Z3Expr& initExpr = rs.gamma_hat(inv);
const Z3Expr& phi = (relExpr && initExpr).simplify();
IntervalESBase resRSY = rs.RSY(inv, phi);
IntervalESBase resBilateral = rs.bilateral(inv, phi);
IntervalESBase resBS = rs.BS(inv, phi);
// 0:[0,1] 1:[0,2]
assert(resRSY == resBS && resBS == resBilateral && "inconsistency occurs");
for (auto r : resRSY.getVarToVal())
{
outs() << r.first << " " << r.second << "\n";
}
IntervalESBase::VarToValMap intendedRes = {{0, IntervalValue(0, 1)}, {1, IntervalValue(0, 2)}};
assert(IntervalESBase::eqVarToValMap(resBS.getVarToVal(), intendedRes) && "inconsistency occurs");
}
void testRelExeState2_1()
{
outs() << "test2_1 start\n";
IntervalESBase itv;
RelExeState relation;
// var0 := [0, 10];
relation[0] = getContext().int_const("0");
itv[0] = IntervalValue(0, 10);
// var1 := var0;
relation[1] =
getContext().int_const("1") == getContext().int_const("0");
itv[1] = itv[0];
// var2 := var1 - var0;
relation[2] = getContext().int_const("2") ==
getContext().int_const("1") - getContext().int_const("0");
itv[2] = itv[1] - itv[0];
// Test extract sub vars
Set<u32_t> res;
relation.extractSubVars(relation[2], res);
assert(res == Set<u32_t>({0, 1, 2}) && "inconsistency occurs");
IntervalESBase inv = itv.sliceState(res);
RelationSolver rs;
const Z3Expr& relExpr = relation[2] && relation[1];
const Z3Expr& initExpr = rs.gamma_hat(inv);
const Z3Expr& phi = (relExpr && initExpr).simplify();
IntervalESBase resRSY = rs.RSY(inv, phi);
IntervalESBase resBilateral = rs.bilateral(inv, phi);
IntervalESBase resBS = rs.BS(inv, phi);
// 0:[0,10] 1:[0,10] 2:[0,0]
assert(resRSY == resBS && resBS == resBilateral && "inconsistency occurs");
for (auto r : resRSY.getVarToVal())
{
outs() << r.first << " " << r.second << "\n";
}
// ground truth
IntervalESBase::VarToValMap intendedRes = {{0, IntervalValue(0, 10)},
{1, IntervalValue(0, 10)},
{2, IntervalValue(0, 0)}
};
assert(IntervalESBase::eqVarToValMap(resBS.getVarToVal(), intendedRes) && "inconsistency occurs");
}
void testRelExeState2_2()
{
outs() << "test2_2 start\n";
IntervalESBase itv;
RelExeState relation;
// var0 := [0, 100];
relation[0] = getContext().int_const("0");
itv[0] = IntervalValue(0, 100);
// var1 := var0;
relation[1] =
getContext().int_const("1") == getContext().int_const("0");
itv[1] = itv[0];
// var2 := var1 - var0;
relation[2] = getContext().int_const("2") ==
getContext().int_const("1") - getContext().int_const("0");
itv[2] = itv[1] - itv[0];
// Test extract sub vars
Set<u32_t> res;
relation.extractSubVars(relation[2], res);
assert(res == Set<u32_t>({0, 1, 2}) && "inconsistency occurs");
IntervalESBase inv = itv.sliceState(res);
RelationSolver rs;
const Z3Expr& relExpr = relation[2] && relation[1];
const Z3Expr& initExpr = rs.gamma_hat(inv);
const Z3Expr& phi = (relExpr && initExpr).simplify();
IntervalESBase resRSY = rs.RSY(inv, phi);
IntervalESBase resBilateral = rs.bilateral(inv, phi);
IntervalESBase resBS = rs.BS(inv, phi);
// 0:[0,100] 1:[0,100] 2:[0,0]
assert(resRSY == resBS && resBS == resBilateral && "inconsistency occurs");
for (auto r : resRSY.getVarToVal())
{
outs() << r.first << " " << r.second << "\n";
}
// ground truth
IntervalESBase::VarToValMap intendedRes = {{0, IntervalValue(0, 100)},
{1, IntervalValue(0, 100)},
{2, IntervalValue(0, 0)}
};
assert(IntervalESBase::eqVarToValMap(resBS.getVarToVal(), intendedRes) && "inconsistency occurs");
}
void testRelExeState2_3()
{
outs() << "test2_3 start\n";
IntervalESBase itv;
RelExeState relation;
// var0 := [0, 1000];
relation[0] = getContext().int_const("0");
itv[0] = IntervalValue(0, 1000);
// var1 := var0;
relation[1] =
getContext().int_const("1") == getContext().int_const("0");
itv[1] = itv[0];
// var2 := var1 - var0;
relation[2] = getContext().int_const("2") ==
getContext().int_const("1") - getContext().int_const("0");
itv[2] = itv[1] - itv[0];
// Test extract sub vars
Set<u32_t> res;
relation.extractSubVars(relation[2], res);
assert(res == Set<u32_t>({0, 1, 2}) && "inconsistency occurs");
IntervalESBase inv = itv.sliceState(res);
RelationSolver rs;
const Z3Expr& relExpr = relation[2] && relation[1];
const Z3Expr& initExpr = rs.gamma_hat(inv);
const Z3Expr& phi = (relExpr && initExpr).simplify();
IntervalESBase resRSY = rs.RSY(inv, phi);
IntervalESBase resBilateral = rs.bilateral(inv, phi);
IntervalESBase resBS = rs.BS(inv, phi);
// 0:[0,1000] 1:[0,1000] 2:[0,0]
assert(resRSY == resBS && resBS == resBilateral && "inconsistency occurs");
for (auto r : resRSY.getVarToVal())
{
outs() << r.first << " " << r.second << "\n";
}
// ground truth
// ground truth
IntervalESBase::VarToValMap intendedRes = {{0, IntervalValue(0, 1000)},
{1, IntervalValue(0, 1000)},
{2, IntervalValue(0, 0)}
};
assert(IntervalESBase::eqVarToValMap(resBS.getVarToVal(), intendedRes) && "inconsistency occurs");
}
void testRelExeState2_4()
{
outs() << "test2_4 start\n";
IntervalESBase itv;
RelExeState relation;
// var0 := [0, 10000];
relation[0] = getContext().int_const("0");
itv[0] = IntervalValue(0, 10000);
// var1 := var0;
relation[1] =
getContext().int_const("1") == getContext().int_const("0");
itv[1] = itv[0];
// var2 := var1 - var0;
relation[2] = getContext().int_const("2") ==
getContext().int_const("1") - getContext().int_const("0");
itv[2] = itv[1] - itv[0];
// Test extract sub vars
Set<u32_t> res;
relation.extractSubVars(relation[2], res);
assert(res == Set<u32_t>({0, 1, 2}) && "inconsistency occurs");
IntervalESBase inv = itv.sliceState(res);
RelationSolver rs;
const Z3Expr& relExpr = relation[2] && relation[1];
const Z3Expr& initExpr = rs.gamma_hat(inv);
const Z3Expr& phi = (relExpr && initExpr).simplify();
IntervalESBase resRSY = RSY_time(inv, phi, rs);
IntervalESBase resBilateral = Bilateral_time(inv, phi, rs);
IntervalESBase resBS = BS_time(inv, phi, rs);
// 0:[0,10000] 1:[0,10000] 2:[0,0]
assert(resRSY == resBS && resBS == resBilateral && "inconsistency occurs");
for (auto r : resRSY.getVarToVal())
{
outs() << r.first << " " << r.second << "\n";
}
// ground truth
// ground truth
IntervalESBase::VarToValMap intendedRes = {{0, IntervalValue(0, 10000)},
{1, IntervalValue(0, 10000)},
{2, IntervalValue(0, 0)}
};
assert(IntervalESBase::eqVarToValMap(resBS.getVarToVal(), intendedRes) && "inconsistency occurs");
}
void testRelExeState2_5()
{
outs() << "test2_5 start\n";
IntervalESBase itv;
RelExeState relation;
// var0 := [0, 100000];
relation[0] = getContext().int_const("0");
itv[0] = IntervalValue(0, 100000);
// var1 := var0;
relation[1] =
getContext().int_const("1") == getContext().int_const("0");
itv[1] = itv[0];
// var2 := var1 - var0;
relation[2] = getContext().int_const("2") ==
getContext().int_const("1") - getContext().int_const("0");
itv[2] = itv[1] - itv[0];
// Test extract sub vars
Set<u32_t> res;
relation.extractSubVars(relation[2], res);
assert(res == Set<u32_t>({0, 1, 2}) && "inconsistency occurs");
IntervalESBase inv = itv.sliceState(res);
RelationSolver rs;
const Z3Expr& relExpr = relation[2] && relation[1];
const Z3Expr& initExpr = rs.gamma_hat(inv);
const Z3Expr& phi = (relExpr && initExpr).simplify();
IntervalESBase resRSY = RSY_time(inv, phi, rs);
IntervalESBase resBilateral = Bilateral_time(inv, phi, rs);
IntervalESBase resBS = BS_time(inv, phi, rs);
// 0:[0,100000] 1:[0,100000] 2:[0,0]
assert(resRSY == resBS && resBS == resBilateral && "inconsistency occurs");
for (auto r : resRSY.getVarToVal())
{
outs() << r.first << " " << r.second << "\n";
}
// ground truth
// ground truth
IntervalESBase::VarToValMap intendedRes = {{0, IntervalValue(0, 100000)},
{1, IntervalValue(0, 100000)},
{2, IntervalValue(0, 0)}
};
assert(IntervalESBase::eqVarToValMap(resBS.getVarToVal(), intendedRes) && "inconsistency occurs");
}
void testRelExeState3_1()
{
outs() << "test3_1 start\n";
IntervalESBase itv;
RelExeState relation;
// var0 := [1, 10];
relation[0] = getContext().int_const("0");
itv[0] = IntervalValue(1, 10);
// var1 := var0;
relation[1] =
getContext().int_const("1") == getContext().int_const("0");
itv[1] = itv[0];
// var2 := var1 / var0;
relation[2] = getContext().int_const("2") ==
getContext().int_const("1") / getContext().int_const("0");
itv[2] = itv[1] / itv[0];
// Test extract sub vars
Set<u32_t> res;
relation.extractSubVars(relation[2], res);
assert(res == Set<u32_t>({0, 1, 2}) && "inconsistency occurs");
IntervalESBase inv = itv.sliceState(res);
RelationSolver rs;
const Z3Expr& relExpr = relation[2] && relation[1];
const Z3Expr& initExpr = rs.gamma_hat(inv);
const Z3Expr& phi = (relExpr && initExpr).simplify();
IntervalESBase resRSY = rs.RSY(inv, phi);
IntervalESBase resBilateral = rs.bilateral(inv, phi);
IntervalESBase resBS = rs.BS(inv, phi);
// 0:[1,10] 1:[1,10] 2:[1,1]
assert(resRSY == resBS && resBS == resBilateral && "inconsistency occurs");
for (auto r : resRSY.getVarToVal())
{
outs() << r.first << " " << r.second << "\n";
}
// ground truth
IntervalESBase::VarToValMap intendedRes = {{0, IntervalValue(1, 10)},
{1, IntervalValue(1, 10)},
{2, IntervalValue(1, 1)}
};
assert(IntervalESBase::eqVarToValMap(resBS.getVarToVal(), intendedRes) && "inconsistency occurs");
}
void testRelExeState3_2()
{
outs() << "test3_2 start\n";
IntervalESBase itv;
RelExeState relation;
// var0 := [1, 1000];
relation[0] = getContext().int_const("0");
itv[0] = IntervalValue(1, 1000);
// var1 := var0;
relation[1] =
getContext().int_const("1") == getContext().int_const("0");
itv[1] = itv[0];
// var2 := var1 / var0;
relation[2] = getContext().int_const("2") ==
getContext().int_const("1") / getContext().int_const("0");
itv[2] = itv[1] / itv[0];
// Test extract sub vars
Set<u32_t> res;
relation.extractSubVars(relation[2], res);
assert(res == Set<u32_t>({0, 1, 2}) && "inconsistency occurs");
IntervalESBase inv = itv.sliceState(res);
RelationSolver rs;
const Z3Expr& relExpr = relation[2] && relation[1];
const Z3Expr& initExpr = rs.gamma_hat(inv);
const Z3Expr& phi = (relExpr && initExpr).simplify();
IntervalESBase resRSY = rs.RSY(inv, phi);
IntervalESBase resBilateral = rs.bilateral(inv, phi);
IntervalESBase resBS = rs.BS(inv, phi);
// 0:[1,1000] 1:[1,1000] 2:[1,1]
assert(resRSY == resBS && resBS == resBilateral && "inconsistency occurs");
for (auto r : resRSY.getVarToVal())
{
outs() << r.first << " " << r.second << "\n";
}
// ground truth
IntervalESBase::VarToValMap intendedRes = {{0, IntervalValue(1, 1000)},
{1, IntervalValue(1, 1000)},
{2, IntervalValue(1, 1)}
};
assert(IntervalESBase::eqVarToValMap(resBS.getVarToVal(), intendedRes) && "inconsistency occurs");
}
void testRelExeState3_3()
{
outs() << "test3_3 start\n";
IntervalESBase itv;
RelExeState relation;
// var0 := [1, 10000];
relation[0] = getContext().int_const("0");
itv[0] = IntervalValue(1, 10000);
// var1 := var0;
relation[1] =
getContext().int_const("1") == getContext().int_const("0");
itv[1] = itv[0];
// var2 := var1 / var0;
relation[2] = getContext().int_const("2") ==
getContext().int_const("1") / getContext().int_const("0");
itv[2] = itv[1] / itv[0];
// Test extract sub vars
Set<u32_t> res;
relation.extractSubVars(relation[2], res);
assert(res == Set<u32_t>({0, 1, 2}) && "inconsistency occurs");
IntervalESBase inv = itv.sliceState(res);
RelationSolver rs;
const Z3Expr& relExpr = relation[2] && relation[1];
const Z3Expr& initExpr = rs.gamma_hat(inv);
const Z3Expr& phi = (relExpr && initExpr).simplify();
IntervalESBase resRSY = RSY_time(inv, phi, rs);
IntervalESBase resBilateral = Bilateral_time(inv, phi, rs);
IntervalESBase resBS = BS_time(inv, phi, rs);
// 0:[1,10000] 1:[1,10000] 2:[1,1]
assert(resRSY == resBS && resBS == resBilateral && "inconsistency occurs");
for (auto r : resRSY.getVarToVal())
{
outs() << r.first << " " << r.second << "\n";
}
// ground truth
IntervalESBase::VarToValMap intendedRes =
Map<u32_t, IntervalValue>({{0, IntervalValue(1, 10000)},
{1, IntervalValue(1, 10000)},
{2, IntervalValue(1, 1)}});
}
void testRelExeState3_4()
{
outs() << "test3_4 start\n";
IntervalESBase itv;
RelExeState relation;
// var0 := [1, 100000];
relation[0] = getContext().int_const("0");
itv[0] = IntervalValue(1, 100000);
// var1 := var0;
relation[1] =
getContext().int_const("1") == getContext().int_const("0");
itv[1] = itv[0];
// var2 := var1 / var0;
relation[2] = getContext().int_const("2") ==
getContext().int_const("1") / getContext().int_const("0");
itv[2] = itv[1] / itv[0];
// Test extract sub vars
Set<u32_t> res;
relation.extractSubVars(relation[2], res);
assert(res == Set<u32_t>({0, 1, 2}) && "inconsistency occurs");
IntervalESBase inv = itv.sliceState(res);
RelationSolver rs;
const Z3Expr& relExpr = relation[2] && relation[1];
const Z3Expr& initExpr = rs.gamma_hat(inv);
const Z3Expr& phi = (relExpr && initExpr).simplify();
IntervalESBase resRSY = RSY_time(inv, phi, rs);
IntervalESBase resBilateral = Bilateral_time(inv, phi, rs);
IntervalESBase resBS = BS_time(inv, phi, rs);
// 0:[1,100000] 1:[1,100000] 2:[1,1]
assert(resRSY == resBS && resBS == resBilateral && "inconsistency occurs");
for (auto r : resRSY.getVarToVal())
{
outs() << r.first << " " << r.second << "\n";
}
// ground truth
IntervalESBase::VarToValMap intendedRes = {{0, IntervalValue(1, 100000)},
{1, IntervalValue(1, 100000)},
{2, IntervalValue(1, 1)}
};
assert(IntervalESBase::eqVarToValMap(resBS.getVarToVal(), intendedRes) && "inconsistency occurs");
}
void testRelExeState4_1()
{
outs() << "test4_1 start\n";
IntervalESBase itv;
RelExeState relation;
// var0 := [0, 10];
relation[0] = getContext().int_const("0");
itv[0] = IntervalValue(0, 10);
// var1 := var0;
relation[1] =
getContext().int_const("1") == getContext().int_const("0");
itv[1] = itv[0];
// var2 := var1 / var0;
relation[2] = getContext().int_const("2") ==
getContext().int_const("1") / getContext().int_const("0");
itv[2] = itv[1] / itv[0];
// Test extract sub vars
Set<u32_t> res;
relation.extractSubVars(relation[2], res);
assert(res == Set<u32_t>({0, 1, 2}) && "inconsistency occurs");
IntervalESBase inv = itv.sliceState(res);
RelationSolver rs;
const Z3Expr& relExpr = relation[2] && relation[1];
const Z3Expr& initExpr = rs.gamma_hat(inv);
const Z3Expr& phi = (relExpr && initExpr).simplify();
// IntervalExeState resRSY = rs.RSY(inv, phi);
outs() << "rsy done\n";
// IntervalExeState resBilateral = rs.bilateral(inv, phi);
outs() << "bilateral done\n";
IntervalESBase resBS = rs.BS(inv, phi);
outs() << "bs done\n";
// 0:[0,10] 1:[0,10] 2:[-00,+00]
// assert(resRSY == resBS && resBS == resBilateral);
for (auto r : resBS.getVarToVal())
{
outs() << r.first << " " << r.second << "\n";
}
// ground truth
IntervalESBase::VarToValMap intendedRes = {{0, IntervalValue(0, 10)},
{1, IntervalValue(0, 10)},
{2, IntervalValue(IntervalValue::minus_infinity(), IntervalValue::plus_infinity())}
};
assert(IntervalESBase::eqVarToValMap(resBS.getVarToVal(), intendedRes) && "inconsistency occurs");
}
void testsValidation()
{
SymblicAbstractionTest saTest;
saTest.testRelExeState1_1();
saTest.testRelExeState1_2();
saTest.testRelExeState2_1();
saTest.testRelExeState2_2();
saTest.testRelExeState2_3();
// saTest.testRelExeState2_4(); /// 10000
// saTest.testRelExeState2_5(); /// 100000
saTest.testRelExeState3_1();
saTest.testRelExeState3_2();
// saTest.testRelExeState3_3(); /// 10000
// saTest.testRelExeState3_4(); /// 100000
outs() << "start top\n";
saTest.testRelExeState4_1(); /// top
}
};
int main(int argc, char** argv)
{
int arg_num = 0;
int extraArgc = 3;
char **arg_value = new char *[argc + extraArgc];
for (; arg_num < argc; ++arg_num)
{
arg_value[arg_num] = argv[arg_num];
}
// add extra options
int orgArgNum = arg_num;
arg_value[arg_num++] = (char*) "-model-consts=true";
arg_value[arg_num++] = (char*) "-model-arrays=true";
arg_value[arg_num++] = (char*) "-pre-field-sensitive=false";
assert(arg_num == (orgArgNum + extraArgc) && "more extra arguments? Change the value of extraArgc");
std::vector<std::string> moduleNameVec;
moduleNameVec = OptionBase::parseOptions(
arg_num, arg_value, "Static Symbolic Execution", "[options] <input-bitcode...>"
);
delete[] arg_value;
if (SYMABS())
{
SymblicAbstractionTest saTest;
saTest.testsValidation();
return 0;
}
SVFModule *svfModule = LLVMModuleSet::getLLVMModuleSet()->buildSVFModule(moduleNameVec);
SVFIRBuilder builder(svfModule);
SVFIR* pag = builder.build();
AndersenWaveDiff* ander = AndersenWaveDiff::createAndersenWaveDiff(pag);
PTACallGraph* callgraph = ander->getPTACallGraph();
builder.updateCallGraph(callgraph);
if (Options::BufferOverflowCheck())
{
BufOverflowChecker ae;
ae.initExtAPI();
ae.runOnModule(pag);
}
else
{
AbstractExecution ae;
ae.initExtAPI();
ae.runOnModule(pag);
}
LLVMModuleSet::releaseLLVMModuleSet();
return 0;
} |
package br.com.danielschiavo.mapper.cliente;
import java.time.LocalDate;
import org.mapstruct.Context;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;
import br.com.danielschiavo.shop.model.cliente.Cliente;
import br.com.danielschiavo.shop.model.cliente.carrinho.Carrinho;
import br.com.danielschiavo.shop.model.cliente.dto.AlterarClienteDTO;
import br.com.danielschiavo.shop.model.cliente.dto.CadastrarClienteDTO;
import br.com.danielschiavo.shop.model.cliente.dto.MostrarClienteDTO;
import br.com.danielschiavo.shop.model.cliente.endereco.Endereco;
import br.com.danielschiavo.shop.model.filestorage.ArquivoInfoDTO;
@Mapper(componentModel = "spring")
public abstract class ClienteMapper {
@Mapping(target = "fotoPerfil", source = "fotoPerfil", qualifiedByName = "stringParaArquivoInfoDTO")
@Mapping(target = "enderecos", ignore = true)
@Mapping(target = "cartoes", ignore = true)
public abstract MostrarClienteDTO clienteParaMostrarClienteDTO(Cliente cliente, @Context FileStoragePerfilService fileStorageService);
@Named("stringParaArquivoInfoDTO")
public ArquivoInfoDTO stringParaArquivoInfoDTO(String nomeArquivo, @Context FileStoragePerfilService fileStorageService) {
return fileStorageService.pegarFotoPerfilPorNome(nomeArquivo);
}
@Mapping(target = "id", ignore = true)
@Mapping(target = "cpf", ignore = true)
@Mapping(target = "dataNascimento", ignore = true)
@Mapping(target = "dataCriacaoConta", ignore = true)
@Mapping(target = "email", ignore = true)
@Mapping(target = "celular", ignore = true)
@Mapping(target = "fotoPerfil", source = "fotoPerfil", qualifiedByName = "stringParaArquivoInfoDTO")
@Mapping(target = "enderecos", ignore = true)
@Mapping(target = "cartoes", ignore = true)
public abstract MostrarClientePaginaInicialDTO clienteParaMostrarClientePaginaInicialDTO(Cliente cliente, @Context FileStoragePerfilService fileStorageService);
public Cliente cadastrarClienteDtoParaCliente(CadastrarClienteDTO clienteDTO) {
Cliente cliente = new Cliente();
cliente.setCpf(clienteDTO.cpf());
cliente.setNome(clienteDTO.nome());
cliente.setSobrenome(clienteDTO.sobrenome());
cliente.setDataNascimento(clienteDTO.dataNascimento());
cliente.setDataCriacaoConta(LocalDate.now());
cliente.setEmail(clienteDTO.email());
cliente.setSenha(clienteDTO.senha());
cliente.setCelular(clienteDTO.celular());
if (clienteDTO.fotoPerfil() != null) {
cliente.setFotoPerfil(clienteDTO.fotoPerfil());
}
else {
cliente.setFotoPerfil("Padrao.jpeg");
}
cliente.setCarrinho(new Carrinho(null, null, null, cliente));
return cliente;
}
public void alterarClienteDtoSetarAtributosEmCliente(AlterarClienteDTO alterarClienteDTO, Cliente cliente) {
if (alterarClienteDTO.cpf() != null) {
cliente.setCpf(alterarClienteDTO.cpf());
}
if (alterarClienteDTO.nome() != null) {
cliente.setNome(alterarClienteDTO.nome());
}
if (alterarClienteDTO.sobrenome() != null) {
cliente.setSobrenome(alterarClienteDTO.sobrenome());
}
if (alterarClienteDTO.dataNascimento() != null) {
cliente.setDataNascimento(alterarClienteDTO.dataNascimento());
}
if (alterarClienteDTO.email() != null) {
cliente.setEmail(alterarClienteDTO.email());
}
if (alterarClienteDTO.senha() != null) {
cliente.setSenha(alterarClienteDTO.senha());
}
if (alterarClienteDTO.celular() != null) {
cliente.setCelular(alterarClienteDTO.celular());
}
}
public Endereco cadastrarClienteDtoParaEndereco(CadastrarClienteDTO clienteDTO, Cliente cliente) {
Endereco endereco = new Endereco();
endereco.setCep(clienteDTO.endereco().cep());
endereco.setRua(clienteDTO.endereco().rua());
endereco.setNumero(clienteDTO.endereco().numero());
endereco.setComplemento(clienteDTO.endereco().complemento());
endereco.setBairro(clienteDTO.endereco().bairro());
endereco.setCidade(clienteDTO.endereco().cidade());
endereco.setEstado(clienteDTO.endereco().estado());
endereco.setEnderecoPadrao(clienteDTO.endereco().enderecoPadrao());
endereco.setCliente(cliente);
return endereco;
}
} |
const express = require('express');
const bodyParser = require('body-parser');
const path = require("path");
const app = express();
const cors = require("cors");
app.use(bodyParser.json());
app.use(cors());
let todos = [];
function findIndex(arr, id) {
for (let i = 0; i < arr.length; i++) {
if (arr[i].id === id) return i;
}
return -1;
}
function removeAtIndex(arr, index) {
let newArray = [];
for (let i = 0; i < arr.length; i++) {
if (i !== index) newArray.push(arr[i]);
}
return newArray;
}
app.get('/todos', (req, res) => {
res.json(todos);
});
var ctr = 1;
app.post('/todos', (req, res) => {
const newTodo = {
id: ctr, // unique random id
title: req.body.title,
description: req.body.description
};
ctr = ctr + 1
todos.push(newTodo);
res.status(201).json(newTodo);
});
app.delete('/todos/:id', (req, res) => {
const todoIndex = findIndex(todos, parseInt(req.params.id));
if (todoIndex === -1) {
res.status(404).send();
} else {
todos = removeAtIndex(todos, todoIndex);
res.status(200).send();
}
});
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "index.html"));
})
// for all other routes, return 404
app.use((req, res, next) => {
res.status(404).send();
});
app.listen(3000); |
import { Button, Dialog, DialogActions, DialogContent, DialogTitle, TextField } from '@mui/material'
import { useContext, useState } from 'react'
import { useForm } from 'react-hook-form'
import { Transition } from '@/components/Transition'
import { useTranslation } from 'react-i18next'
import { CreateGuardianInput } from '.'
import { SnackbarContext } from '@/contexts/SnackbarContextProvider'
import { yupResolver } from '@hookform/resolvers/yup'
import { guardianSchema } from '@/validation/guardianSchema'
interface CreateGuardianDialogProps {
cancel(): void
createGuardian(input: CreateGuardianInput ): Promise<void>
isAddingGuardian: boolean
}
const CreateGuardianDialog = ({ cancel, createGuardian, isAddingGuardian }: CreateGuardianDialogProps) => {
const [disableButtons, setDisableButtons] = useState<boolean>(false)
const { t } = useTranslation(['guardians', 'common'])
const { showErrorSnackbar } = useContext(SnackbarContext)
const {
handleSubmit,
register,
reset,
formState: {
errors,
touchedFields
}
} = useForm<CreateGuardianInput>({ resolver: yupResolver(guardianSchema) })
const createGuardianAction = async (data: CreateGuardianInput) => {
try {
setDisableButtons(true)
await createGuardian(data)
setDisableButtons(false)
reset()
} catch (e) {
// TODO: Need better error handling
console.error(e as string)
setDisableButtons(false)
showErrorSnackbar('Error creating Guardian.')
}
}
return (
<Dialog
open={isAddingGuardian}
onClose={cancel}
TransitionComponent={Transition}
PaperProps={{
component: 'form',
onSubmit: handleSubmit(createGuardianAction),
sx: { padding: 4, minWidth: '25%' }
}}
>
<DialogTitle textAlign='center'>{t('addGuardian')}</DialogTitle>
<DialogContent>
<TextField
fullWidth
label='First Name'
{...register('given_name')}
error={!!errors.given_name?.message && touchedFields.given_name}
helperText={errors.given_name?.message ? t(errors.given_name.message, { ns: 'common' }) : ''}
/>
<TextField
fullWidth
label='Last Name'
{...register('family_name')}
error={!!errors.family_name?.message && touchedFields.family_name}
helperText={errors.family_name?.message ? t(errors.family_name.message, { ns: 'common' }) : ''}
/>
<TextField
fullWidth
label='Email'
{...register('email')}
error={!!errors.email?.message && touchedFields.email}
helperText={errors.email?.message ? t(errors.email.message, { ns: 'common' }) : ''}
/>
<TextField
fullWidth
label='Address'
{...register('address')}
error={!!errors.address?.message && touchedFields.address}
helperText={errors.address?.message ? t(errors.address.message, { ns: 'common' }) : ''}
/>
</DialogContent>
<DialogActions sx={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-evenly' }}>
<Button disabled={disableButtons} variant='contained' onClick={cancel}>{t('cancel', { ns: 'common' })}</Button>
<Button disabled={disableButtons} variant='contained' type="submit">{t('createGuardian')}</Button>
</DialogActions>
</Dialog>
)
}
export default CreateGuardianDialog |
import { ReactElement } from 'react';
import Document, { DocumentContext, DocumentInitialProps, Head, Html, Main, NextScript } from 'next/document';
import { enableNextSsr } from '@uniformdev/context-next';
import createUniformContext from '@/context/createUniformContext';
type CustomDocumentProps = DocumentInitialProps;
// Docs: https://docs.uniform.app/docs/guides/personalization/activate-personalization#server-side
class AppDocument extends Document<CustomDocumentProps> {
// required to enable SSR personalization
static async getInitialProps(ctx: DocumentContext): Promise<DocumentInitialProps> {
const serverTracker = createUniformContext(ctx);
enableNextSsr(ctx, serverTracker);
return await Document.getInitialProps(ctx);
}
render(): ReactElement {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default AppDocument; |
import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/compat/auth';
import { catchError, from, Observable, of, throwError } from 'rxjs';
import { map } from 'rxjs/operators';
import { GoogleAuthProvider, AuthProvider } from 'firebase/auth';
@Injectable({
providedIn: 'root'
})
export class AuthenticationService {
constructor(
private auth: AngularFireAuth
) { }
isLogged(): Observable<boolean> {
return this.auth.authState.pipe(
catchError(() => of(null)),
map((user) => !!user)
);
}
signIn(params: SignIn): Observable<any> {
return from(this.auth.signInWithEmailAndPassword(
params.email, params.password
)).pipe(
catchError((error: FirebaseError) =>
throwError(() => new Error(this.translateFirebaseErrorMessage(error)))
)
);
}
recoverPassword(email: string): Observable<void> {
return from(this.auth.sendPasswordResetEmail(email)).pipe(
catchError((error: FirebaseError) =>
throwError(() => new Error(this.translateFirebaseErrorMessage(error)))
)
);
}
GoogleAuth() {
return this.AuthLogin(new GoogleAuthProvider());
}
private AuthLogin(provider: AuthProvider): Promise<void> {
return this.auth.signInWithPopup(provider)
.then((result) => {
console.log('You have been successfully logged in!');
})
.catch((error) => {
console.log(error);
});
}
private translateFirebaseErrorMessage({code, message}: FirebaseError) {
if (code === "auth/user-not-found") {
return "User not found.";
}
if (code === "auth/wrong-password") {
return "User not found.";
}
return message;
}
// signInWithPhoneNumber(phoneNumber: string, appVerifier: any): Observable<any> {
// return from(this.auth.signInWithPhoneNumber(phoneNumber, appVerifier)).pipe(
// catchError((error: FirebaseError) =>
// throwError(() => new Error(this.translateFirebaseErrorMessage(error)))
// )
// );
// }
// verifyPhoneNumber(verificationId: string, verificationCode: string): Observable<any> {
// return from(this.auth.signInWithPhoneNumber(verificationId, verificationCode)).pipe(
// catchError((error: FirebaseError) =>
// throwError(() => new Error(this.translateFirebaseErrorMessage(error)))
// )
// );
// }
}
type SignIn = {
email: string;
password: string;
}
type FirebaseError = {
code: string;
message: string
}; |
import { apiHandler } from '@libs/api-gateway';
import { Result } from '@libs/api-gateway/types';
import { Logger } from '@libs/log';
import createEvent from '@serverless/event-mocks';
import {
APIGatewayEvent,
APIGatewayProxyEvent,
APIGatewayProxyEventPathParameters,
APIGatewayProxyResult,
Context,
} from 'aws-lambda';
import { z } from 'zod';
import { Mocks, expectResponse } from '../../../common';
jest.mock('@libs/log');
const RESOURCE_PATH = '/hello';
const ID = '22543534-d8dd-48eb-8b5c-c714ed2df982';
const createRequestMock = (name: string | number): string => {
return JSON.stringify({
name: name,
});
};
const HelloData = z.object({
name: z.string(),
});
const processEvent = (
event: APIGatewayEvent,
body: HelloDataType,
pathParameters: HelloDataType,
): Promise<Result> => {
return Promise.resolve({
body: {
message: `Hello ${body.name}!`,
},
statusCode: 200,
});
};
type HelloDataType = z.infer<typeof HelloData>;
describe('Libs - API Gateway - Request', (): void => {
let eventMock: APIGatewayProxyEvent;
let contextMock: Context;
beforeEach((): void => {
Logger.prototype.info = jest.fn();
Logger.prototype.error = jest.fn();
eventMock = createEvent('aws:apiGateway', {
body: createRequestMock('Linkal'),
headers: {
'Content-Type': 'application/json',
},
httpMethod: 'POST',
path: RESOURCE_PATH,
pathParameters: {
name: ID,
} as APIGatewayProxyEventPathParameters,
requestContext: {
requestTimeEpoch: Date.now(),
},
}) as APIGatewayProxyEvent;
contextMock = Mocks.createContext();
});
afterEach((): void => {
jest.clearAllMocks();
jest.resetAllMocks();
});
test('Should return error when event body is null', async () => {
eventMock.body = null;
const response: APIGatewayProxyResult = await apiHandler({
context: contextMock,
event: eventMock,
execute: (
event: APIGatewayEvent,
body: HelloDataType,
pathParameters: HelloDataType,
log: Logger,
) => processEvent(event, body, pathParameters),
input: {
body: HelloData,
},
});
expectResponse(response, 404, {
code: 'invalid-input',
date: expect.anything(),
});
});
test('Should return error when event body has incorrect format', async () => {
eventMock.body = createRequestMock(1);
const response: APIGatewayProxyResult = await apiHandler({
context: contextMock,
event: eventMock,
execute: (
event: APIGatewayEvent,
body: HelloDataType,
pathParameters: HelloDataType,
log: Logger,
) => processEvent(event, body, pathParameters),
input: {
body: HelloData,
},
});
expectResponse(response, 404, {
code: 'invalid-input',
date: expect.anything(),
});
});
test('Should return error when event pathParameters has incorrect format', async () => {
eventMock.pathParameters = {};
const response: APIGatewayProxyResult = await apiHandler({
context: contextMock,
event: eventMock,
execute: (
event: APIGatewayEvent,
body: HelloDataType,
pathParameters: HelloDataType,
log: Logger,
) => processEvent(event, body, pathParameters),
input: {
body: HelloData,
pathParameters: HelloData,
},
});
expectResponse(response, 404, {
code: 'invalid-input',
date: expect.anything(),
});
});
test('Should return success when event has the correct format', async () => {
const response: APIGatewayProxyResult = await apiHandler({
context: contextMock,
event: eventMock,
execute: (
event: APIGatewayEvent,
body: HelloDataType,
pathParameters: HelloDataType,
log: Logger,
) => processEvent(event, body, pathParameters),
input: {
body: HelloData,
},
});
expectResponse(response, 200, { message: 'Hello Linkal!' });
});
}); |
import { orderBy, range } from "lodash";
import { ObjectId } from "mongodb";
import {
Arg,
Authorized,
Ctx,
FieldResolver,
Int,
Query,
Resolver,
Root,
} from "type-graphql";
import { isDocument, Ref } from "@typegoose/typegoose";
import { ADMIN } from "../../constants";
import { CategoryImageAssociationModel } from "../entities/associations/categoryImageAssociation";
import { TagCategoryAssociationModel } from "../entities/associations/tagCategoryAssociation";
import { User, UserModel } from "../entities/auth/user";
import { ImageModel } from "../entities/image";
import { UserStats, UserStatsModel } from "../entities/stats";
import { TagModel } from "../entities/tag";
import { IContext } from "../interfaces";
import { assertIsDefined } from "../utils/assert";
import { ObjectIdScalar } from "../utils/ObjectIdScalar";
let userAdmins: ObjectId[] | undefined = undefined;
/**
* This level function pretends to represent
* level 1 ~> 0 score;
* level 2 ~> 5 score;
* level 3 ~> 15 score;
* level 4 ~> 27 score;
* level 5 ~> (level 4 score + (level 4 score - level 3 score) * 1.2) = 41 score;
* level y ~> x score;
*
* @param {number} score score
* @param {number} m m in function
* @param {number} b b in function
* @returns {number} level
*/
const levelFunction = (
score: number,
m: number = 1.15,
b: number = 0.0796
): number => {
const level = Math.round(b + Math.log(m * score));
return level >= 1 ? level : 1;
};
@Resolver(() => UserStats)
export class UserStatsResolver {
static async updateUserStats({ user }: { user: Ref<User> }) {
assertIsDefined(user, "User should be specified if stats is not given");
const stats = await UserStatsModel.findOneAndUpdate(
{
user: isDocument(user) ? user._id : user,
},
{},
{
setDefaultsOnInsert: true,
upsert: true,
new: true,
}
);
[
stats.nAssociatedImages,
stats.nAssociatedTags,
stats.nUploadedImages,
stats.nValidatedUploadedImages,
] = await Promise.all([
CategoryImageAssociationModel.countDocuments({
user: isDocument(user) ? user._id : user,
}),
TagCategoryAssociationModel.countDocuments({
user: isDocument(user) ? user._id : user,
}),
ImageModel.countDocuments({
uploader: isDocument(user) ? user._id : user,
active: true,
}),
ImageModel.countDocuments({
uploader: isDocument(user) ? user._id : user,
active: true,
validated: true,
}),
]);
stats.score =
stats.nValidatedUploadedImages * 10 +
stats.nAssociatedTags * 2 +
stats.nAssociatedImages * 2 +
stats.nUploadedImages * 5;
stats.imagesLevel = levelFunction(stats.nAssociatedImages);
stats.tagsLevel = levelFunction(stats.nAssociatedTags);
stats.uploadLevel = levelFunction(
stats.nUploadedImages + stats.nValidatedUploadedImages
);
stats.overallLevel = levelFunction(stats.score, 0.8);
await stats.save();
return stats;
}
@Authorized([ADMIN])
@Query(() => [String])
async generalUserProgress() {
const [totalTags, totalImages] = await Promise.all([
TagModel.countDocuments({}),
ImageModel.countDocuments({}),
]);
const steps = range(0, 1, 0.1);
if (userAdmins === undefined) {
userAdmins = (await UserModel.find({ admin: true })).map(
({ _id }) => _id
);
}
const results = await Promise.all(
steps.map(async i => {
const [nAssociatedTags, nAssociatedImages] = await Promise.all([
UserStatsModel.countDocuments({
nAssociatedTags: {
$gte: Math.round(totalTags * i),
$lt: Math.round(totalTags * (i + 0.1)),
},
user: {
$not: {
$in: userAdmins,
},
},
}),
UserStatsModel.countDocuments({
nAssociatedImages: {
$gte: Math.round(totalImages * i),
$lt: Math.round(totalImages * (i + 0.1)),
},
user: {
$not: {
$in: userAdmins,
},
},
}),
]);
return [
`${nAssociatedTags} usuario(s) han respondido entre ${Math.round(
i * 100
)}% y ${Math.round((i + 0.1) * 100)}% de etiquetas`,
`${nAssociatedImages} usuario(s) han respondido entre ${Math.round(
i * 100
)}% y ${Math.round((i + 0.1) * 100)}% de imágenes`,
];
})
);
return results.flat();
}
@Authorized([ADMIN])
@Query(() => UserStats, { nullable: true })
async userStats(@Arg("user_id", () => ObjectIdScalar) user_id: ObjectId) {
const user = await UserModel.findById(user_id);
if (user) {
return await UserStatsResolver.updateUserStats({ user });
}
return null;
}
@Authorized()
@Query(() => [UserStats])
async rankingStats(
@Arg("limit", () => Int, { defaultValue: 5 }) limit: number
) {
if (userAdmins === undefined) {
userAdmins = (await UserModel.find({ admin: true })).map(
({ _id }) => _id
);
}
let ranking = await UserStatsModel.find(
{
score: {
$gt: 0,
},
user: {
$not: {
$in: userAdmins,
},
},
},
"user"
)
.limit(limit)
.sort({
score: "desc",
});
ranking = await Promise.all(
ranking
.filter(({ user }) => user)
.map(({ user }) => {
assertIsDefined(user, "filter is not working");
return UserStatsResolver.updateUserStats({ user });
})
);
return orderBy(
ranking,
["overallLevel", "score", "email"],
["desc", "desc", "asc"]
);
}
@Authorized()
@Query(() => UserStats)
async ownStats(@Ctx() { user }: IContext) {
assertIsDefined(user, "Context user failed!");
return await UserStatsResolver.updateUserStats({ user });
}
@FieldResolver()
async user(@Root() { user }: Pick<UserStats, "user">) {
return isDocument(user) ? user : await UserModel.findById(user);
}
@FieldResolver()
async rankingPosition(@Root() { user }: Pick<UserStats, "user">) {
if (userAdmins === undefined) {
userAdmins = (await UserModel.find({ admin: true })).map(
({ _id }) => _id
);
}
let ranking = await UserStatsModel.find(
{
score: {
$gt: 0,
},
user: {
$not: {
$in: userAdmins,
},
},
},
"user"
).sort({
score: "desc",
});
const userId = isDocument(user) ? user._id : user;
const position = ranking.findIndex(stats => {
return userId.equals(stats.user);
});
return position;
}
} |
package com.macaosoftware.sdui.app.marketplace.auth
import androidx.compose.runtime.mutableStateOf
import com.macaosoftware.component.core.Component
import com.macaosoftware.component.stack.StackComponent
import com.macaosoftware.component.stack.StackComponentViewModel
import com.macaosoftware.component.stack.StackStatePresenter
import com.macaosoftware.component.viewmodel.StateComponent
import com.macaosoftware.plugin.account.AccountPlugin
import com.macaosoftware.plugin.account.MacaoUser
import com.macaosoftware.plugin.account.UserData
import com.macaosoftware.sdui.app.marketplace.auth.forget.ForgotCredentialsComponentView
import com.macaosoftware.sdui.app.marketplace.auth.forget.ForgotCredentialsViewModel
import com.macaosoftware.sdui.app.marketplace.auth.forget.ForgotCredentialsViewModelFactory
import com.macaosoftware.sdui.app.marketplace.auth.forget.ForgotCredentialsViewModelMsg
import com.macaosoftware.sdui.app.marketplace.auth.login.LoginComponentView
import com.macaosoftware.sdui.app.marketplace.auth.login.LoginViewModel
import com.macaosoftware.sdui.app.marketplace.auth.login.LoginViewModelFactory
import com.macaosoftware.sdui.app.marketplace.auth.login.LoginViewModelMsg
import com.macaosoftware.sdui.app.marketplace.auth.signup.SignupComponentView
import com.macaosoftware.sdui.app.marketplace.auth.signup.SignupViewModel
import com.macaosoftware.sdui.app.marketplace.auth.signup.SignupViewModelFactory
import com.macaosoftware.sdui.app.marketplace.auth.signup.SignupViewModelMsg
import com.macaosoftware.util.MacaoResult
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class AuthViewModel(
stackComponent: StackComponent<AuthViewModel>,
override val stackStatePresenter: StackStatePresenter,
val accountPlugin: AccountPlugin
) : StackComponentViewModel(stackComponent) {
val viewModelScope = CoroutineScope(Dispatchers.Default)
var userData = mutableStateOf<UserData?>(null)
private var currentComponent: Component? = null
private val loginComponent: StateComponent<LoginViewModel> by lazy {
StateComponent<LoginViewModel>(
viewModelFactory = LoginViewModelFactory(
accountPlugin = accountPlugin,
loginViewModelMessageHandler = ::loginViewModelMessageHandler
),
content = LoginComponentView
)
}
private val signupComponent: StateComponent<SignupViewModel> by lazy {
StateComponent<SignupViewModel>(
viewModelFactory = SignupViewModelFactory(
accountPlugin = accountPlugin,
signupViewModelMessageHandler = ::signupViewModelMessageHandler
),
content = SignupComponentView
)
}
private val forgotCredentialsComponent: StateComponent<ForgotCredentialsViewModel> by lazy {
StateComponent<ForgotCredentialsViewModel>(
viewModelFactory = ForgotCredentialsViewModelFactory(
accountPlugin = accountPlugin,
viewModelMessageHandler = ::forgotCredentialsViewModelMessageHandler
),
content = ForgotCredentialsComponentView
)
}
override fun onAttach() {
//authPlugin.initialize()
stackComponent.navigator.push(loginComponent)
}
override fun onStart() {
}
override fun onStop() {
}
override fun onDetach() {
}
override fun onCheckChildForNextUriFragment(deepLinkPathSegment: String): Component? {
return loginComponent
}
override fun onStackTopUpdate(topComponent: Component) {
currentComponent = topComponent
}
fun checkAndFetchUserData() = viewModelScope.launch {
val result = accountPlugin.checkAndFetchUserData()
when (result) {
is MacaoResult.Success -> {
println("User Data: $result")
userData.value = result.value
}
is MacaoResult.Error -> {
println("User not logged in: ${result.error}")
// Handle error
println("Error: ${result.error}")
}
}
}
fun fetchUserDataAndHandleResult() {
viewModelScope.launch {
val userDataResult = accountPlugin.fetchUserData()
when (userDataResult) {
is MacaoResult.Success -> {
val userData = userDataResult.value
// Handle user data
println("User Data: $userData")
}
is MacaoResult.Error -> {
val error = userDataResult.error
// Handle error
println("Error: $error")
}
}
}
}
fun updateData(currentUser: MacaoUser, updatedUser: MacaoUser) = viewModelScope.launch {
//val database = Firebase.database("https://macao-sdui-app-30-default-rtdb.firebaseio.com/")
//val userRef = database.reference().child("Users").child(currentUser.uid)
//userRef.setValue(updatedUser)
println("Data Updated Successfully: $updatedUser ")
}
private fun loginViewModelMessageHandler(viewModelMsg: LoginViewModelMsg) =
when (viewModelMsg) {
LoginViewModelMsg.OnCreateAccountClick -> {
stackComponent.navigator.push(signupComponent)
}
LoginViewModelMsg.OnForgotCredentialsClick -> {
stackComponent.navigator.push(forgotCredentialsComponent)
}
LoginViewModelMsg.OnLoginWithEmailLinkClick -> {
}
is LoginViewModelMsg.OnError -> {}
is LoginViewModelMsg.OnSuccess -> {}
}
private fun signupViewModelMessageHandler(viewModelMsg: SignupViewModelMsg) =
when (viewModelMsg) {
SignupViewModelMsg.OnGoBack -> {
stackComponent.navigator.pop()
}
is SignupViewModelMsg.OnSuccess -> {
}
}
private fun forgotCredentialsViewModelMessageHandler(viewModelMsg: ForgotCredentialsViewModelMsg) =
when (viewModelMsg) {
ForgotCredentialsViewModelMsg.OnGoBack -> {
stackComponent.navigator.pop()
}
ForgotCredentialsViewModelMsg.OnCreateAccountClick -> {
stackComponent.navigator.push(signupComponent)
}
is ForgotCredentialsViewModelMsg.OnSuccess -> {
stackComponent.navigator.push(loginComponent)
}
}
} |
# -*- coding: utf-8 -*-
# BSD 3-Clause License
#
# Copyright (c) 2020-2023, Faster Speeding
# 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.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may 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 HOLDER 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.
r"""Parameter annotation based strategy for declaring slash and message command arguments.
[with_annotated_args][tanjun.annotations.with_annotated_args] should be used to
parse the options for both message commands and slash commands.
`follow_wrapped=True` should be passed if you want this to parse options for
all the commands being declared in a decorator call chain.
This implementation exposes 3 ways to mark an argument as a command option:
1. Using any of the following types as an argument's type-hint (this may
be as the first argument to [typing.Annotated][]) will mark it as a
command argument:
* [annotations.Attachment][tanjun.annotations.Attachment]\*
* [annotations.Bool][tanjun.annotations.Bool]
* [annotations.Channel][tanjun.annotations.Channel]
* [annotations.InteractionChannel][tanjun.annotations.InteractionChannel]\*
* [annotations.Color][tanjun.annotations.Color]/[annotations.Colour][tanjun.annotations.Colour]
* [annotations.Datetime][tanjun.annotations.Datetime]
* [annotations.Float][tanjun.annotations.Float]
* [annotations.Int][tanjun.annotations.Int]
* [annotations.Member][tanjun.annotations.Member]
* [annotations.InteractionMember][tanjun.annotations.InteractionMember]\*
* [annotations.Mentionable][tanjun.annotations.Mentionable]
* [annotations.Role][tanjun.annotations.Role]
* [annotations.Snowflake][tanjun.annotations.Snowflake]
* [annotations.Str][tanjun.annotations.Str]
* [annotations.User][tanjun.annotations.User]
\* These types are specific to slash commands and will raise an exception
when set for a message command's parameter which has no real default.
```py
@tanjun.with_annotated_args(follow_wrapped=True)
@tanjun.as_message_command("name")
@tanjun.as_slash_command("name", "description")
async def command(
ctx: tanjun.abc.Context,
# Here the option's description is passed as a string to Annotated:
# this is necessary for slash commands but ignored for message commands.
name: Annotated[Str, "The character's name"],
# `= False` declares this field as optional, with it defaulting to `False`
# if not specified.
lawyer: Annotated[Bool, "Whether they're a lawyer"] = False,
) -> None:
raise NotImplementedError
```
When doing this the following objects can be included in a field's
annotations to add extra configuration:
* [annotations.Default][tanjun.annotations.Default]
Set the default for an option in the annotations (rather than using
the argument's actual default).
* [annotations.Flag][tanjun.annotations.Flag]
Mark an option as being a flag option for message commands.
* [annotations.Greedy][tanjun.annotations.Greedy]
Mark an option as consuming the rest of the provided positional
values for message commands.
* [annotations.Length][tanjun.annotations.Length]
Set the length restraints for a string option.
* [annotations.Min][tanjun.annotations.Min]
Set the minimum valid size for float and integer options.
* [annotations.Max][tanjun.annotations.Max]
Set the maximum valid size for float and integer options.
* [annotations.Name][tanjun.annotations.Name]
Override the option's name.
* [annotations.Positional][tanjun.annotations.Positional]
Mark optional arguments as positional for message commands.
* [annotations.Ranged][tanjun.annotations.Ranged]
Set range constraints for float and integer options.
* [annotations.SnowflakeOr][tanjun.annotations.SnowflakeOr]
Indicate that a role, user, channel, member, role, or mentionable
option should be left as the ID for message commands.
* [annotations.TheseChannels][tanjun.annotations.TheseChannels]
Constrain the valid channel types for a channel option.
```py
async def command(
ctx: tanjun.abc.Context,
name: Annotated[Str, Length(1, 20)],
channel: Annotated[Role | hikari.Snowflake | None, SnowflakeOr()] = None,
) -> None:
raise NotImplementedError
```
It should be noted that wrapping in [typing.Annotated][] isn't necessary for
message commands options as they don't have descriptions.
```py
async def message_command(
ctx: tanjun.abc.MessageContext,
name: Str,
value: Str,
enable: typing.Optional[Bool] = None,
) -> None:
raise NotImplementedError
```
2. By assigning [tanjun.Converted][tanjun.annotations.Converted] as one of
the other arguments to [typing.Annotated][]:
```py
@tanjun.with_annotated_args(follow_wrapped=True)
@tanjun.as_message_command("e")
@tanjun.as_slash_command("e", "description")
async def command(
ctx: tanjun.abc.Context,
value: Annotated[ParsedType, Converted(parse_value), "description"],
) -> None:
raise NotImplementedError
```
When doing this the option type will be `str`.
3. By using any of the following default descriptors as the argument's
default:
* [annotations.attachment_field][tanjun.annotations.attachment_field]\*
* [annotations.bool_field][tanjun.annotations.bool_field]
* [annotations.channel_field][tanjun.annotations.channel_field]
* [annotations.float_field][tanjun.annotations.float_field]
* [annotations.int_field][tanjun.annotations.int_field]
* [annotations.member_field][tanjun.annotations.member_field]
* [annotations.mentionable_field][tanjun.annotations.mentionable_field]
* [annotations.role_field][tanjun.annotations.role_field]
* [annotations.str_field][tanjun.annotations.str_field]
* [annotations.user_field][tanjun.annotations.user_field]
\* These are specific to slash commands and will raise an exception
when set for a message command's parameter which has no real default.
```py
@tanjun.with_annotated_args(follow_wrapped=True)
@tanjun.as_message_command("e")
@tanjun.as_slash_command("e", "description")
async def command(
ctx: tanjun.abc.Context,
user_field: hikari.User | None = annotations.user_field(default=None),
field: bool = annotations.bool_field(default=False, empty_value=True),
) -> None:
raise NotImplementedError
```
A [typing.TypedDict][] can be used to declare multiple options by
typing the passed `**kwargs` dict as it using [typing.Unpack][].
These options can be marked as optional using [typing.NotRequired][],
`total=False` or [Default][tanjun.annotations.Default].
```py
class CommandOptions(typing.TypedDict):
argument: Annotated[Str, "A required string argument"]
other: NotRequired[Annotated[Bool, "An optional string argument"]]
@tanjun.with_annotated_args(follow_wrapped=True)
@tanjun.as_message_command("name")
@tanjun.as_slash_command("name", "description")
async def command(
ctx: tanjun.abc.Context, **kwargs: Unpack[CommandOptions],
) -> None:
raise NotImplementedError
```
Community Resources:
* An extended implementation of this which parses callback docstrings to get the
descriptions for slash commands and their options can be found in
<https://github.com/FasterSpeeding/Tan-chan>.
"""
from __future__ import annotations
__all__: list[str] = [
"Attachment",
"Bool",
"Channel",
"Choices",
"Color",
"Colour",
"Converted",
"Datetime",
"Default",
"Flag",
"Float",
"Greedy",
"Int",
"InteractionChannel",
"InteractionMember",
"Length",
"Max",
"Member",
"Mentionable",
"Min",
"Name",
"Positional",
"Ranged",
"Role",
"Snowflake",
"SnowflakeOr",
"Str",
"TheseChannels",
"User",
"attachment_field",
"bool_field",
"channel_field",
"float_field",
"int_field",
"member_field",
"mentionable_field",
"role_field",
"str_field",
"user_field",
"with_annotated_args",
]
import abc
import dataclasses
import datetime
import enum
import itertools
import operator
import typing
import warnings
from collections import abc as collections
import hikari
import typing_extensions
from . import _internal
from . import abc as tanjun
from . import conversion
from . import parsing
from ._internal.vendor import inspect
from .commands import message
from .commands import slash
if typing.TYPE_CHECKING:
from typing_extensions import Self
_T = typing.TypeVar("_T")
_OtherT = typing.TypeVar("_OtherT")
_ConverterSig = collections.Callable[
typing_extensions.Concatenate[str, ...], typing.Union[collections.Coroutine[typing.Any, typing.Any, _T], _T]
]
_ChannelTypeIsh = typing.Union[type[hikari.PartialChannel], int]
_ChoiceUnion = typing.Union[int, float, str]
_ChoiceT = typing.TypeVar("_ChoiceT", int, float, str)
_CommandUnion = typing.Union[slash.SlashCommand[typing.Any], message.MessageCommand[typing.Any]]
_CommandUnionT = typing.TypeVar("_CommandUnionT", bound=_CommandUnion)
_EnumT = typing.TypeVar("_EnumT", bound="enum.Enum")
_NumberT = typing.TypeVar("_NumberT", float, int)
_MentionableUnion = typing.Union[hikari.User, hikari.Role]
class _ConfigIdentifier(abc.ABC):
__slots__ = ()
@abc.abstractmethod
def set_config(self, config: _ArgConfig, /) -> None:
raise NotImplementedError
class _OptionMarker(_ConfigIdentifier):
__slots__ = ("_type",)
def __init__(self, type_: typing.Any, /) -> None:
self._type = type_
@property
def type(self) -> typing.Any:
return self._type
def set_config(self, config: _ArgConfig, /) -> None:
config.set_option_type(self._type)
Attachment = typing.Annotated[hikari.Attachment, _OptionMarker(hikari.Attachment)]
"""Type-hint for marking an argument which accepts a file.
!!! warning
This is currently only supported for slash commands.
"""
Bool = typing.Annotated[bool, _OptionMarker(bool)]
"""Type-hint for marking an argument which takes a bool-like value."""
Channel = typing.Annotated[hikari.PartialChannel, _OptionMarker(hikari.PartialChannel)]
"""Type-hint for marking an argument which takes a channel.
[hikari.InteractionChannel][hikari.interactions.base_interactions.InteractionChannel]
will be passed for options typed as this when being called as a slash command.
"""
InteractionChannel = typing.Annotated[hikari.InteractionChannel, _OptionMarker(hikari.InteractionChannel)]
"""Type-hint for marking an argument which takes a channel with interaction specific metadata.
!!! warning
This is only supported for slash commands and will not work for message
commands (unlike [annotations.Channel][tanjun.annotations.Channel]).
"""
Float = typing.Annotated[float, _OptionMarker(float)]
"""Type-hint for marking an argument which takes a floating point number."""
Int = typing.Annotated[int, _OptionMarker(int)]
"""Type-hint for marking an argument which takes an integer."""
Member = typing.Annotated[hikari.Member, _OptionMarker(hikari.Member)]
"""Type-hint for marking an argument which takes a guild member.
[hikari.InteractionMember][hikari.interactions.base_interactions.InteractionMember]
will be passed for options typed as this when being called as a slash command.
"""
InteractionMember = typing.Annotated[hikari.InteractionMember, _OptionMarker(hikari.InteractionMember)]
"""Type-hint for marking an argument which takes an interactio.
!!! warning
This is only supported for slash commands and will not work for message
commands (unlike [annotations.Member][tanjun.annotations.Member]).
"""
Mentionable = typing.Annotated[typing.Union[hikari.User, hikari.Role], _OptionMarker(_MentionableUnion)]
"""Type-hint for marking an argument which takes a user or role."""
Role = typing.Annotated[hikari.Role, _OptionMarker(hikari.Role)]
"""Type-hint for marking an argument which takes a role."""
Str = typing.Annotated[str, _OptionMarker(str)]
"""Type-hint for marking an argument which takes string input."""
User = typing.Annotated[hikari.User, _OptionMarker(hikari.User)]
"""Type-hint for marking an argument which takes a user."""
@dataclasses.dataclass()
class _Field(_ConfigIdentifier):
__slots__ = (
"_channel_types",
"_choices",
"_default",
"_description",
"_empty_value",
"_is_greedy",
"_is_positional",
"_message_names",
"_min_length",
"_max_length",
"_min_value",
"_max_value",
"_option_type",
"_slash_name",
"_snowflake_converter",
"_str_converters",
)
_channel_types: collections.Sequence[_ChannelTypeIsh]
_choices: typing.Optional[collections.Mapping[str, _ChoiceUnion]]
_default: typing.Any
_description: str
_empty_value: typing.Any
_is_greedy: typing.Optional[bool]
_is_positional: typing.Optional[bool]
_message_names: collections.Sequence[str]
_min_length: typing.Union[int, None]
_max_length: typing.Union[int, None]
_min_value: typing.Union[int, float, None]
_max_value: typing.Union[int, float, None]
_option_type: typing.Any
_slash_name: str
_snowflake_converter: typing.Optional[collections.Callable[[str], hikari.Snowflake]]
_str_converters: collections.Sequence[_ConverterSig[typing.Any]]
# TODO: _float_converter, _int_converter
@classmethod
def new(
cls,
option_type: type[_T],
/,
*,
channel_types: collections.Sequence[_ChannelTypeIsh] = (),
choices: typing.Optional[collections.Mapping[str, _ChoiceUnion]] = None,
default: typing.Any = tanjun.NO_DEFAULT,
description: str = "",
empty_value: typing.Any = tanjun.NO_DEFAULT,
greedy: typing.Optional[bool] = None,
message_names: collections.Sequence[str] = (),
min_length: typing.Union[int, None] = None,
max_length: typing.Union[int, None] = None,
min_value: typing.Union[int, float, None] = None,
max_value: typing.Union[int, float, None] = None,
positional: typing.Optional[bool] = None,
slash_name: str = "",
snowflake_converter: typing.Optional[collections.Callable[[str], hikari.Snowflake]] = None,
str_converters: typing.Union[_ConverterSig[typing.Any], collections.Sequence[_ConverterSig[typing.Any]]] = (),
) -> _T:
if not isinstance(str_converters, collections.Sequence):
str_converters = (str_converters,)
return typing.cast(
"_T",
cls(
_channel_types=channel_types,
_choices=choices,
_default=default,
_description=description,
_empty_value=empty_value,
_is_greedy=greedy,
_is_positional=positional,
_message_names=message_names,
_min_length=min_length,
_max_length=max_length,
_min_value=min_value,
_max_value=max_value,
_option_type=option_type,
_slash_name=slash_name,
_snowflake_converter=snowflake_converter,
_str_converters=str_converters,
),
)
def set_config(self, config: _ArgConfig, /) -> None:
config.channel_types = self._channel_types or config.channel_types
config.choices = self._choices or config.choices
if self._default is not tanjun.NO_DEFAULT:
config.default = self._default
config.description = self._description or config.description
if self._empty_value is not tanjun.NO_DEFAULT:
config.empty_value = self._empty_value
if self._is_greedy is not None:
config.is_greedy = self._is_greedy
if self._is_positional is not None:
config.is_positional = self._is_positional
if self._message_names:
config.main_message_name = self._message_names[0]
config.message_names = self._message_names
if self._min_length is not None:
config.min_length = self._min_length
if self._max_length is not None:
config.max_length = self._max_length
if self._min_value is not None:
config.min_value = self._min_value
if self._max_value is not None:
config.max_value = self._max_value
config.set_option_type(self._option_type)
config.slash_name = self._slash_name or config.slash_name
config.snowflake_converter = self._snowflake_converter or config.snowflake_converter
config.str_converters = self._str_converters or config.str_converters
def attachment_field(
*, default: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT, description: str = "", slash_name: str = ""
) -> typing.Union[hikari.Attachment, _T]:
"""Mark a parameter as an attachment option using a descriptor.
!!! warning
This is currently only supported for slash commands.
Examples
--------
```py
async def command(
ctx: tanjun.abc.SlashContext,
field: hikari.Attachment | None = annotations.attachment_field(default=None),
) -> None:
...
```
Parameters
----------
default : typing.Any
Default value to pass if this option wasn't provided.
If not passed then this option will be required.
description
The option's description.
slash_name
The name to use for this option in slash commands.
"""
return _Field.new(hikari.Attachment, default=default, description=description, slash_name=slash_name)
def bool_field(
*,
default: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
description: str = "",
empty_value: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
greedy: typing.Optional[bool] = None,
message_names: collections.Sequence[str] = (),
positional: typing.Optional[bool] = None,
slash_name: str = "",
) -> typing.Union[bool, _T]:
"""Mark a parameter as a bool option using a descriptor.
Examples
--------
```py
async def command(
ctx: tanjun.abc.SlashContext,
field: bool | None = annotations.bool_field(default=None),
) -> None:
...
```
Parameters
----------
default : typing.Any
Default value to pass if this option wasn't provided.
If not passed then this option will be required.
Otherwise, this will mark the option as being a flag for message
commands unless `positional=False` is also passed.
description
The option's description.
empty_value : typing.Any
Value to pass when this is used as a message flag without a value
(i.e. `--name`).
If not passed then a value will be required and is ignored unless
`default` is also passed.
greedy
Whether this option should be marked as "greedy" form message command
parsing.
A greedy option will consume the rest of the positional arguments.
This can only be applied to one positional argument and is no-op for
slash commands and flags.
message_names
The names this option may be triggered by as a message command flag
option.
These must all be prefixed with `"-"` and are ignored unless `default`
is also passed.
positional
Whether this should be a positional argument.
Arguments will be positional by default unless `default` is provided.
slash_name
The name to use for this option in slash commands.
"""
return _Field.new(
bool,
default=default,
description=description,
empty_value=empty_value,
greedy=greedy,
message_names=message_names,
positional=positional,
slash_name=slash_name,
)
@typing.overload
def channel_field(
*,
channel_types: collections.Sequence[_ChannelTypeIsh] = (),
default: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
description: str = "",
empty_value: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
greedy: typing.Optional[bool] = None,
message_names: collections.Sequence[str] = (),
or_snowflake: typing.Literal[False] = False,
positional: typing.Optional[bool] = None,
slash_name: str = "",
) -> typing.Union[hikari.PartialChannel, _T]:
...
@typing.overload
def channel_field(
*,
channel_types: collections.Sequence[_ChannelTypeIsh] = (),
default: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
description: str = "",
empty_value: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
greedy: typing.Optional[bool] = None,
message_names: collections.Sequence[str] = (),
or_snowflake: typing.Literal[True],
positional: typing.Optional[bool] = None,
slash_name: str = "",
) -> typing.Union[hikari.PartialChannel, hikari.Snowflake, _T]:
...
def channel_field(
*,
channel_types: collections.Sequence[_ChannelTypeIsh] = (),
default: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
description: str = "",
empty_value: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
greedy: typing.Optional[bool] = None,
message_names: collections.Sequence[str] = (),
or_snowflake: bool = False,
positional: typing.Optional[bool] = None,
slash_name: str = "",
) -> typing.Union[hikari.PartialChannel, hikari.Snowflake, _T]:
"""Mark a parameter as a channel option using a descriptor.
```py
async def command(
ctx: tanjun.abc.Context,
field: hikari.PartialChannel | None = annotations.channel_field(default=None),
) -> None:
...
```
Parameters
----------
channel_types
Sequence of the channel types allowed for this option.
If left as an empty sequence then all channel types will be allowed.
default : typing.Any
Default value to pass if this option wasn't provided.
If not passed then this option will be required.
Otherwise, this will mark the option as being a flag for message
commands unless `positional=False` is also passed.
description
The option's description.
empty_value : typing.Any
Value to pass when this is used as a message flag without a value
(i.e. `--name`).
If not passed then a value will be required and is ignored unless
`default` is also passed.
greedy
Whether this option should be marked as "greedy" form message command
parsing.
A greedy option will consume the rest of the positional arguments.
This can only be applied to one positional argument and is no-op for
slash commands and flags.
message_names
The names this option may be triggered by as a message command flag
option.
These must all be prefixed with `"-"` and are ignored unless `default`
is also passed.
or_snowflake
Whether this should just pass the parsed channel ID as a
[hikari.Snowflake][hikari.snowflakes.Snowflake] for message command
calls.
positional
Whether this should be a positional argument.
Arguments will be positional by default unless `default` is provided.
slash_name
The name to use for this option in slash commands.
"""
return _Field.new(
hikari.PartialChannel,
channel_types=channel_types,
default=default,
description=description,
empty_value=empty_value,
greedy=greedy,
message_names=message_names,
snowflake_converter=conversion.parse_channel_id if or_snowflake else None,
positional=positional,
slash_name=slash_name,
)
def float_field(
*,
choices: typing.Optional[collections.Mapping[str, float]] = None,
default: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
description: str = "",
empty_value: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
greedy: typing.Optional[bool] = None,
message_names: collections.Sequence[str] = (),
min_value: typing.Optional[float] = None,
max_value: typing.Optional[float] = None,
positional: typing.Optional[bool] = None,
slash_name: str = "",
) -> typing.Union[float, _T]:
"""Mark a parameter as a float option using a descriptor.
```py
async def command(
ctx: tanjun.abc.Context,
field: float | None = annotations.float_field(default=None),
) -> None:
...
```
Parameters
----------
choices
A mapping of up to 25 names to the choices values for this option.
This is ignored for message command parsing.
default : typing.Any
Default value to pass if this option wasn't provided.
If not passed then this option will be required.
Otherwise, this will mark the option as being a flag for message
commands unless `positional=False` is also passed.
description
The option's description.
empty_value : typing.Any
Value to pass when this is used as a message flag without a value
(i.e. `--name`).
If not passed then a value will be required and is ignored unless
`default` is also passed.
greedy
Whether this option should be marked as "greedy" form message command
parsing.
A greedy option will consume the rest of the positional arguments.
This can only be applied to one positional argument and is no-op for
slash commands and flags.
message_names
The names this option may be triggered by as a message command flag
option.
These must all be prefixed with `"-"` and are ignored unless `default`
is also passed.
min_value
The minimum allowed value for this argument.
max_value
The maximum allowed value for this argument.
positional
Whether this should be a positional argument.
Arguments will be positional by default unless `default` is provided.
slash_name
The name to use for this option in slash commands.
"""
return _Field.new(
float,
choices=choices,
default=default,
description=description,
empty_value=empty_value,
greedy=greedy,
message_names=message_names,
min_value=min_value,
max_value=max_value,
positional=positional,
slash_name=slash_name,
)
def int_field(
*,
choices: typing.Optional[collections.Mapping[str, int]] = None,
default: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
description: str = "",
empty_value: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
greedy: typing.Optional[bool] = None,
message_names: collections.Sequence[str] = (),
min_value: typing.Optional[int] = None,
max_value: typing.Optional[int] = None,
positional: typing.Optional[bool] = None,
slash_name: str = "",
) -> typing.Union[int, _T]:
"""Mark a parameter as a int option using a descriptor.
```py
async def command(
ctx: tanjun.abc.Context,
field: int | None = annotations.int_field(default=None),
) -> None:
...
```
Parameters
----------
choices
A mapping of up to 25 names to the choices values for this option.
This is ignored for message command parsing.
default : typing.Any
Default value to pass if this option wasn't provided.
If not passed then this option will be required.
Otherwise, this will mark the option as being a flag for message
commands unless `positional=False` is also passed.
description
The option's description.
empty_value : typing.Any
Value to pass when this is used as a message flag without a value
(i.e. `--name`).
If not passed then a value will be required and is ignored unless
`default` is also passed.
greedy
Whether this option should be marked as "greedy" form message command
parsing.
A greedy option will consume the rest of the positional arguments.
This can only be applied to one positional argument and is no-op for
slash commands and flags.
message_names
The names this option may be triggered by as a message command flag
option.
These must all be prefixed with `"-"` and are ignored unless `default`
is also passed.
min_value
The minimum allowed value for this argument.
max_value
The maximum allowed value for this argument.
positional
Whether this should be a positional argument.
Arguments will be positional by default unless `default` is provided.
slash_name
The name to use for this option in slash commands.
"""
return _Field.new(
int,
choices=choices,
default=default,
description=description,
empty_value=empty_value,
greedy=greedy,
message_names=message_names,
min_value=min_value,
max_value=max_value,
positional=positional,
slash_name=slash_name,
)
@typing.overload
def member_field(
*,
default: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
description: str = "",
empty_value: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
greedy: typing.Optional[bool] = None,
message_names: collections.Sequence[str] = (),
or_snowflake: typing.Literal[False] = False,
positional: typing.Optional[bool] = None,
slash_name: str = "",
) -> typing.Union[hikari.Member, _T]:
...
@typing.overload
def member_field(
*,
default: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
description: str = "",
empty_value: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
greedy: typing.Optional[bool] = None,
message_names: collections.Sequence[str] = (),
or_snowflake: typing.Literal[True],
positional: typing.Optional[bool] = None,
slash_name: str = "",
) -> typing.Union[hikari.Member, hikari.Snowflake, _T]:
...
def member_field(
*,
default: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
description: str = "",
empty_value: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
greedy: typing.Optional[bool] = None,
message_names: collections.Sequence[str] = (),
or_snowflake: bool = False,
positional: typing.Optional[bool] = None,
slash_name: str = "",
) -> typing.Union[hikari.Member, hikari.Snowflake, _T]:
"""Mark a parameter as a guild member option using a descriptor.
```py
async def command(
ctx: tanjun.abc.Context,
field: hikari.Member | None = annotations.member_field(default=None),
) -> None:
...
```
Parameters
----------
default : typing.Any
Default value to pass if this option wasn't provided.
If not passed then this option will be required.
Otherwise, this will mark the option as being a flag for message
commands unless `positional=False` is also passed.
description
The option's description.
empty_value : typing.Any
Value to pass when this is used as a message flag without a value
(i.e. `--name`).
If not passed then a value will be required and is ignored unless
`default` is also passed.
greedy
Whether this option should be marked as "greedy" form message command
parsing.
A greedy option will consume the rest of the positional arguments.
This can only be applied to one positional argument and is no-op for
slash commands and flags.
message_names
The names this option may be triggered by as a message command flag
option.
These must all be prefixed with `"-"` and are ignored unless `default`
is also passed.
or_snowflake
Whether this should just pass the parsed user ID as a
[hikari.Snowflake][hikari.snowflakes.Snowflake] for message command
calls.
positional
Whether this should be a positional argument.
Arguments will be positional by default unless `default` is provided.
slash_name
The name to use for this option in slash commands.
"""
return _Field.new(
hikari.Member,
default=default,
description=description,
empty_value=empty_value,
greedy=greedy,
message_names=message_names,
snowflake_converter=conversion.parse_user_id if or_snowflake else None,
positional=positional,
slash_name=slash_name,
)
@typing.overload
def mentionable_field(
*,
default: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
description: str = "",
empty_value: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
greedy: typing.Optional[bool] = None,
message_names: collections.Sequence[str] = (),
or_snowflake: typing.Literal[False] = False,
positional: typing.Optional[bool] = None,
slash_name: str = "",
) -> typing.Union[hikari.User, hikari.Role, _T]:
...
@typing.overload
def mentionable_field(
*,
default: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
description: str = "",
empty_value: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
greedy: typing.Optional[bool] = None,
message_names: collections.Sequence[str] = (),
or_snowflake: typing.Literal[True],
positional: typing.Optional[bool] = None,
slash_name: str = "",
) -> typing.Union[hikari.User, hikari.Role, hikari.Snowflake, _T]:
...
def mentionable_field(
*,
default: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
description: str = "",
empty_value: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
greedy: typing.Optional[bool] = None,
message_names: collections.Sequence[str] = (),
or_snowflake: bool = False,
positional: typing.Optional[bool] = None,
slash_name: str = "",
) -> typing.Union[hikari.User, hikari.Role, hikari.Snowflake, _T]:
"""Mark a parameter as a "mentionable" option using a descriptor.
Mentionable options allow both user and roles.
```py
async def command(
ctx: tanjun.abc.Context,
field: hikari.Role | hikari.User | None = annotations.mentionable_field(default=None),
) -> None:
...
```
Parameters
----------
default : typing.Any
Default value to pass if this option wasn't provided.
If not passed then this option will be required.
Otherwise, this will mark the option as being a flag for message
commands unless `positional=False` is also passed.
description
The option's description.
empty_value : typing.Any
Value to pass when this is used as a message flag without a value
(i.e. `--name`).
If not passed then a value will be required and is ignored unless
`default` is also passed.
greedy
Whether this option should be marked as "greedy" form message command
parsing.
A greedy option will consume the rest of the positional arguments.
This can only be applied to one positional argument and is no-op for
slash commands and flags.
message_names
The names this option may be triggered by as a message command flag
option.
These must all be prefixed with `"-"` and are ignored unless `default`
is also passed.
or_snowflake
Whether this should just pass the parsed ID as a
[hikari.Snowflake][hikari.snowflakes.Snowflake] for message command
calls.
positional
Whether this should be a positional argument.
Arguments will be positional by default unless `default` is provided.
slash_name
The name to use for this option in slash commands.
"""
return _Field.new(
_MentionableUnion,
default=default,
description=description,
empty_value=empty_value,
greedy=greedy,
message_names=message_names,
snowflake_converter=conversion.to_snowflake if or_snowflake else None,
positional=positional,
slash_name=slash_name,
)
@typing.overload
def role_field(
*,
default: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
description: str = "",
empty_value: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
greedy: typing.Optional[bool] = None,
message_names: collections.Sequence[str] = (),
or_snowflake: typing.Literal[False] = False,
positional: typing.Optional[bool] = None,
slash_name: str = "",
) -> typing.Union[hikari.Role, _T]:
...
@typing.overload
def role_field(
*,
default: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
description: str = "",
empty_value: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
greedy: typing.Optional[bool] = None,
message_names: collections.Sequence[str] = (),
or_snowflake: typing.Literal[True],
positional: typing.Optional[bool] = None,
slash_name: str = "",
) -> typing.Union[hikari.Role, hikari.Snowflake, _T]:
...
def role_field(
*,
default: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
description: str = "",
empty_value: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
greedy: typing.Optional[bool] = None,
message_names: collections.Sequence[str] = (),
or_snowflake: bool = False,
positional: typing.Optional[bool] = None,
slash_name: str = "",
) -> typing.Union[hikari.Role, hikari.Snowflake, _T]:
"""Mark a parameter as a guild role option using a descriptor.
```py
async def command(
ctx: tanjun.abc.Context,
field: hikari.Role | None = annotations.role_field(default=None),
) -> None:
...
```
Parameters
----------
default : typing.Any
Default value to pass if this option wasn't provided.
If not passed then this option will be required.
Otherwise, this will mark the option as being a flag for message
commands unless `positional=False` is also passed.
description
The option's description.
empty_value : typing.Any
Value to pass when this is used as a message flag without a value
(i.e. `--name`).
If not passed then a value will be required and is ignored unless
`default` is also passed.
greedy
Whether this option should be marked as "greedy" form message command
parsing.
A greedy option will consume the rest of the positional arguments.
This can only be applied to one positional argument and is no-op for
slash commands and flags.
message_names
The names this option may be triggered by as a message command flag
option.
These must all be prefixed with `"-"` and are ignored unless `default`
is also passed.
or_snowflake
Whether this should just pass the parsed role ID as a
[hikari.Snowflake][hikari.snowflakes.Snowflake] for message command
calls.
positional
Whether this should be a positional argument.
Arguments will be positional by default unless `default` is provided.
slash_name
The name to use for this option in slash commands.
"""
return _Field.new(
hikari.Role,
default=default,
description=description,
empty_value=empty_value,
greedy=greedy,
message_names=message_names,
snowflake_converter=conversion.parse_role_id if or_snowflake else None,
positional=positional,
slash_name=slash_name,
)
@typing.overload
def str_field(
*,
choices: typing.Optional[collections.Mapping[str, str]] = None,
default: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
description: str = "",
empty_value: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
greedy: typing.Optional[bool] = None,
message_names: collections.Sequence[str] = (),
min_length: typing.Union[int, None] = None,
max_length: typing.Union[int, None] = None,
positional: typing.Optional[bool] = None,
slash_name: str = "",
) -> typing.Union[str, _T]:
...
@typing.overload
def str_field(
*,
choices: typing.Optional[collections.Mapping[str, str]] = None,
converters: typing.Union[_ConverterSig[_OtherT], collections.Sequence[_ConverterSig[_OtherT]]],
default: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
description: str = "",
empty_value: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
greedy: typing.Optional[bool] = None,
message_names: collections.Sequence[str] = (),
min_length: typing.Union[int, None] = None,
max_length: typing.Union[int, None] = None,
positional: typing.Optional[bool] = None,
slash_name: str = "",
) -> typing.Union[_OtherT, _T]:
...
def str_field(
*,
choices: typing.Optional[collections.Mapping[str, str]] = None,
converters: typing.Union[_ConverterSig[_OtherT], collections.Sequence[_ConverterSig[_OtherT]]] = (),
default: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
description: str = "",
empty_value: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
greedy: typing.Optional[bool] = None,
message_names: collections.Sequence[str] = (),
min_length: typing.Union[int, None] = None,
max_length: typing.Union[int, None] = None,
positional: typing.Optional[bool] = None,
slash_name: str = "",
) -> typing.Union[str, _T, _OtherT]:
"""Mark a parameter as a string option using a descriptor.
Examples
--------
```py
async def command(
ctx: tanjun.abc.Context,
field: str | None = annotations.str_field(default=None),
) -> None:
...
```
Parameters
----------
choices
A mapping of up to 25 names to the choices values for this option.
This is ignored for message command parsing.
converters
The option's converters.
This may be either one or multiple converter callbacks used to
convert the option's value to the final form.
If no converters are provided then the raw value will be passed.
Only the first converter to pass will be used.
default : typing.Any
Default value to pass if this option wasn't provided.
If not passed then this option will be required.
Otherwise, this will mark the option as being a flag for message
commands unless `positional=False` is also passed.
description
The option's description.
empty_value : typing.Any
Value to pass when this is used as a message flag without a value
(i.e. `--name`).
If not passed then a value will be required and is ignored unless
`default` is also passed.
greedy
Whether this option should be marked as "greedy" form message command
parsing.
A greedy option will consume the rest of the positional arguments.
This can only be applied to one positional argument and is no-op for
slash commands and flags.
message_names
The names this option may be triggered by as a message command flag
option.
These must all be prefixed with `"-"` and are ignored unless `default`
is also passed.
min_length
The minimum length this argument can be.
max_length
The maximum length this string argument can be.
positional
Whether this should be a positional argument.
Arguments will be positional by default unless `default` is provided.
slash_name
The name to use for this option in slash commands.
"""
return _Field.new(
str,
choices=choices,
default=default,
description=description,
empty_value=empty_value,
greedy=greedy,
message_names=message_names,
min_length=min_length,
max_length=max_length,
positional=positional,
slash_name=slash_name,
str_converters=converters,
)
@typing.overload
def user_field(
*,
default: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
description: str = "",
empty_value: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
greedy: typing.Optional[bool] = None,
message_names: collections.Sequence[str] = (),
or_snowflake: typing.Literal[False] = False,
positional: typing.Optional[bool] = None,
slash_name: str = "",
) -> typing.Union[hikari.User, _T]:
...
@typing.overload
def user_field(
*,
default: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
description: str = "",
empty_value: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
greedy: typing.Optional[bool] = None,
message_names: collections.Sequence[str] = (),
or_snowflake: typing.Literal[True],
positional: typing.Optional[bool] = None,
slash_name: str = "",
) -> typing.Union[hikari.User, hikari.Snowflake, _T]:
...
def user_field(
*,
default: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
description: str = "",
empty_value: typing.Union[_T, tanjun.NoDefault] = tanjun.NO_DEFAULT,
greedy: typing.Optional[bool] = None,
message_names: collections.Sequence[str] = (),
or_snowflake: bool = False,
positional: typing.Optional[bool] = None,
slash_name: str = "",
) -> typing.Union[hikari.User, hikari.Snowflake, _T]:
"""Mark a parameter as a user option using a descriptor.
Examples
--------
```py
async def command(
ctx: tanjun.abc.Context,
field: hikari.User | None = annotations.user_field(default=None),
) -> None:
...
```
Parameters
----------
default : typing.Any
Default value to pass if this option wasn't provided.
If not passed then this option will be required.
Otherwise, this will mark the option as being a flag for message
commands unless `positional=False` is also passed.
description
The option's description.
empty_value : typing.Any
Value to pass when this is used as a message flag without a value
(i.e. `--name`).
If not passed then a value will be required and is ignored unless
`default` is also passed.
greedy
Whether this option should be marked as "greedy" form message command
parsing.
A greedy option will consume the rest of the positional arguments.
This can only be applied to one positional argument and is no-op for
slash commands and flags.
message_names
The names this option may be triggered by as a message command flag
option.
These must all be prefixed with `"-"` and are ignored unless `default`
is also passed.
or_snowflake
Whether this should just pass the parsed user ID as a
[hikari.Snowflake][hikari.snowflakes.Snowflake] for message command
calls.
positional
Whether this should be a positional argument.
Arguments will be positional by default unless `default` is provided.
slash_name
The name to use for this option in slash commands.
"""
return _Field.new(
hikari.User,
default=default,
description=description,
empty_value=empty_value,
greedy=greedy,
message_names=message_names,
snowflake_converter=conversion.parse_user_id if or_snowflake else None,
positional=positional,
slash_name=slash_name,
)
class _FloatEnumConverter(_ConfigIdentifier):
"""Specialised converters for float enum choices."""
__slots__ = ("_enum",)
def __init__(self, enum: collections.Callable[[float], typing.Any]) -> None:
self._enum = enum
def set_config(self, config: _ArgConfig, /) -> None:
config.float_converter = self._enum
class _IntEnumConverter(_ConfigIdentifier):
"""Specialised converters for int enum choices."""
__slots__ = ("_enum",)
def __init__(self, enum: collections.Callable[[int], typing.Any]) -> None:
self._enum = enum
def set_config(self, config: _ArgConfig, /) -> None:
config.int_converter = self._enum
class _EnumConverter(_ConfigIdentifier):
__slots__ = ("_converter",)
def __init__(self, enum: collections.Callable[[str], enum.Enum], /) -> None:
self._converter = enum
def set_config(self, config: _ArgConfig, /) -> None:
config.str_converters = [self._converter]
class _ChoicesMeta(abc.ABCMeta):
@typing_extensions.deprecated("Pass Choices(...) to Annotated")
def __getitem__(cls, enum_: type[_EnumT], /) -> type[_EnumT]:
if issubclass(enum_, float):
type_ = float
choices = Choices(enum_.__members__)
converter = _FloatEnumConverter(enum_)
elif issubclass(enum_, int):
type_ = int
choices = Choices(enum_.__members__)
converter = _IntEnumConverter(enum_)
elif issubclass(enum_, str):
type_ = str
choices = Choices(enum_.__members__)
converter = None
else:
raise TypeError("Enum must be a subclass of str, float or int")
# TODO: do we want to wrap the convert callback to give better failed parse messages?
return typing.cast(
"type[_EnumT]", typing.Annotated[enum_, choices, converter, _EnumConverter(enum_), _OptionMarker(type_)]
)
class Choices(_ConfigIdentifier, metaclass=_ChoicesMeta):
"""Assign up to 25 choices for a slash command option.
!!! warning
This is currently ignored for message commands and is only
valid for string, integer and float options.
Examples
--------
```py
@with_annotated_args
@tanjun.as_slash_command("beep", "meow")
async def command(
ctx: tanjun.abc.Context,
location: Annotated[Int, "where do you live?", Choices("London", "Paradise", "Nowhere")],
) -> None:
raise NotImplementedError
```
"""
__slots__ = ("_choices",)
def __init__(
self,
mapping: typing.Union[
collections.Mapping[str, _ChoiceT],
collections.Sequence[tuple[str, _ChoiceT]],
collections.Sequence[_ChoiceT],
] = (),
/,
**kwargs: _ChoiceT,
) -> None:
"""Create a choices instance.
Parameters
----------
mapping
Either a mapping of names to the choices values or a sequence
of `tuple[name, value]` or a sequence of choice values.
**kwargs
Choice values.
"""
if isinstance(mapping, collections.Sequence):
self._choices: dict[str, _ChoiceUnion] = dict(
(value if isinstance(value, tuple) else (str(value), value) for value in mapping), **kwargs
)
else:
self._choices = dict(mapping, **kwargs)
@property
def choices(self) -> collections.Mapping[str, _ChoiceUnion]:
"""Mapping of up to 25 choices for the slash command option."""
return self._choices
def set_config(self, config: _ArgConfig, /) -> None:
config.choices = self._choices
class _ConvertedMeta(abc.ABCMeta):
@typing_extensions.deprecated("Pass Converted(...) to Annotated")
def __getitem__(cls, converters: typing.Union[_ConverterSig[_T], tuple[_ConverterSig[_T]]], /) -> type[_T]:
if not isinstance(converters, tuple):
converters = (converters,)
return typing.cast("type[_T]", typing.Annotated[typing.Any, Converted(*converters)])
class Converted(_ConfigIdentifier, metaclass=_ConvertedMeta):
"""Marked an argument as type [Str][tanjun.annotations.Str] with converters.
Examples
--------
```py
@with_annotated_args
@tanjun.as_slash_command("beep", "boop")
async def command(
ctx: tanjun.abc.SlashContext,
argument: Annotated[OtherType, Converted(callback, other_callback), "description"]
) -> None:
raise NotImplementedError
```
"""
__slots__ = ("_converters",)
def __init__(self, converter: _ConverterSig[typing.Any], /, *other_converters: _ConverterSig[typing.Any]) -> None:
"""Create a converted instance.
Parameters
----------
converter : collections.abc.Callable[[str, ...], collections.Coroutine[Any, Any, Any] | Any]
The first converter this argument should use to handle values passed to it
during parsing.
Only the first converter to pass will be used.
*other_converters : collections.abc.Callable[[str, ...], collections.Coroutine[Any, Any, Any] | Any]
Other first converter(s) this argument should use to handle values passed to it
during parsing.
Only the first converter to pass will be used.
"""
self._converters = [converter, *other_converters]
@property
def converters(self) -> collections.Sequence[_ConverterSig[typing.Any]]:
"""A sequence of the converters."""
return self._converters
def set_config(self, config: _ArgConfig, /) -> None:
config.str_converters = self._converters
config.set_option_type(str)
Color = typing.Annotated[hikari.Color, Converted(conversion.to_color)]
"""An argument which takes a color."""
Colour = Color
"""An argument which takes a colour."""
Datetime = typing.Annotated[datetime.datetime, Converted(conversion.to_datetime)]
"""An argument which takes a datetime."""
Snowflake = typing.Annotated[hikari.Snowflake, Converted(conversion.parse_snowflake)]
"""An argument which takes a snowflake."""
class _DefaultMeta(abc.ABCMeta):
@typing_extensions.deprecated("Pass Default(...) to Annotated")
def __getitem__(cls, value: typing.Union[type[_T], tuple[type[_T], _T]], /) -> type[_T]:
if isinstance(value, tuple):
type_ = value[0]
return typing.Annotated[type_, Default(value[1])]
type_ = typing.cast("type[_T]", value)
return typing.Annotated[type_, Default()]
class Default(_ConfigIdentifier, metaclass=_DefaultMeta):
"""Explicitly configure an argument's default.
Examples
--------
```py
@with_annotated_args
@tanjun.as_slash_command("name", "description")
async def command(
ctx: tanjun.abc.Context,
argument: Annotated[Str, Default(""), "description"],
) -> None:
raise NotImplementedError
```
```py
@with_annotated_args
@tanjun.as_slash_command("name", "description")
async def command(
ctx: tanjun.abc.Context,
required_argument: Annotated[Int, Default(), "description"] = 123,
) -> None:
raise NotImplementedError
```
Passing an empty [Default][tanjun.annotations.Default] allows you to mark
an argument that's optional in the signature as being a required option.
"""
__slots__ = ("_default",)
def __init__(self, default: typing.Any = tanjun.NO_DEFAULT, /) -> None:
"""Initialise a default.
Parameters
----------
default
The argument's default.
If left as [tanjun.abc.NO_DEFAULT][] then the argument will be
required regardless of the signature default.
"""
self._default = default
@property
def default(self) -> typing.Any:
"""The option's default.
This will override the default in the signature for this parameter.
"""
return self._default
def set_config(self, config: _ArgConfig, /) -> None:
config.default = self._default
class Flag(_ConfigIdentifier):
"""Mark an argument as a flag/option for message command parsing.
This indicates that the argument should be specified by name (e.g. `--name`)
rather than positionally for message parsing and doesn't effect slash
command options.
Examples
--------
```py
@with_annotated_args
@tanjun.as_message_command("message")
async def command(
ctx: tanjun.abc.MessageContext,
flag_value: Annotated[Bool, Flag(empty_value=True, aliases=("-f",))] = False,
) -> None:
raise NotImplementedError
```
"""
__slots__ = ("_aliases", "_default", "_empty_value")
@typing.overload
def __init__(
self, *, aliases: typing.Optional[collections.Sequence[str]] = None, empty_value: typing.Any = tanjun.NO_DEFAULT
) -> None:
...
@typing_extensions.deprecated("Use annotations.Default instead of the default arg")
@typing.overload
def __init__(
self,
*,
aliases: typing.Optional[collections.Sequence[str]] = None,
default: typing.Any = tanjun.NO_DEFAULT,
empty_value: typing.Any = tanjun.NO_DEFAULT,
) -> None:
...
def __init__(
self,
*,
aliases: typing.Optional[collections.Sequence[str]] = None,
default: typing.Any = tanjun.NO_DEFAULT,
empty_value: typing.Any = tanjun.NO_DEFAULT,
) -> None:
"""Create a flag instance.
Parameters
----------
aliases
Other names the flag may be triggered by.
This does not override the argument's name and all the aliases must
be prefixed with `"-"`.
empty_value
Value to pass for the argument if the flag is provided without a value.
If left undefined then an explicit value will always be needed.
[tanjun.abc.NO_PASS][] is not supported for this.
"""
if default is not tanjun.NO_DEFAULT:
warnings.warn(
"Flag.__init__'s `default` argument is deprecated, use Default instead", category=DeprecationWarning
)
self._aliases = aliases
self._default = default
self._empty_value = empty_value
@property
def aliases(self) -> typing.Optional[collections.Sequence[str]]:
"""The aliases set for this flag.
These do not override the flag's name.
"""
return self._aliases
@property
@typing_extensions.deprecated("Use annotations.Default instead of the default arg")
def default(self) -> typing.Any:
"""The flag's default.
If not specified then the default in the signature for this argument
will be used.
"""
return self._default
@property
def empty_value(self) -> typing.Any:
"""The value to pass for the argument if the flag is provided without a value.
If this is [tanjun.abc.NO_DEFAULT][] then a value will be required
for this flag.
"""
return self._empty_value
def set_config(self, config: _ArgConfig, /) -> None:
if self._default is not tanjun.NO_DEFAULT:
config.default = self._default
if self._aliases:
config.message_names = [config.main_message_name, *self._aliases]
config.empty_value = self._empty_value
config.is_positional = False
class _PositionalMeta(abc.ABCMeta):
@typing_extensions.deprecated("Pass Positional(...) to Annotated")
def __getitem__(cls, type_: type[_T], /) -> type[_T]:
return typing.Annotated[type_, Positional()]
class Positional(_ConfigIdentifier, metaclass=_PositionalMeta):
"""Mark an argument as being passed positionally for message command parsing.
Arguments will be positional by default (unless it has a default) and this
allows for marking positional arguments as optional.
This only effects message option parsing.
Examples
--------
```py
@with_annotated_args
@tanjun.as_message_command("message")
async def command(
ctx: tanjun.abc.MessageContext,
positional_arg: Annotated[Str, Positional()] = None,
) -> None:
raise NotImplementedError
```
"""
__slots__ = ()
def set_config(self, config: _ArgConfig, /) -> None:
config.is_positional = True
class _GreedyMeta(abc.ABCMeta):
@typing_extensions.deprecated("Pass Greedy(...) to Annotated")
def __getitem__(cls, type_: type[_T], /) -> type[_T]:
return typing.Annotated[type_, Greedy()]
class Greedy(_ConfigIdentifier, metaclass=_GreedyMeta):
"""Mark an argument as "greedy" for message command parsing.
This means that it'll consume the rest of the positional arguments,
can only be applied to one positional argument and is no-op for slash
commands and flags.
Examples
--------
```py
@with_annotated_args
@tanjun.as_message_command("message")
async def command(
ctx: tanjun.abc.MessageContext,
greedy_arg: Annotated[Str, Greedy()],
other_greedy_arg: Annotated[Str, Greedy()],
) -> None:
raise NotImplementedError
```
"""
__slots__ = ()
def set_config(self, config: _ArgConfig, /) -> None:
config.is_greedy = True
class _LengthMeta(abc.ABCMeta):
@typing_extensions.deprecated("Pass Length(...) to Annotated")
def __getitem__(cls, value: typing.Union[int, tuple[int, int]], /) -> type[str]:
if isinstance(value, int):
obj = Length(value)
else:
obj = Length(*value)
return typing.Annotated[Str, obj]
class Length(_ConfigIdentifier, metaclass=_LengthMeta):
"""Define length restraints for a string option.
!!! note
Length constraints are applied before conversion for slash commands
but after conversion for message commands.
Examples
--------
```py
@with_annotated_args
@tanjun.as_slash_command("meow", "blam")
async def command(
ctx: tanjun.abc.Context,
max_and_min: typing.Annotated[Str, Length(123, 321)],
max_only: typing.Annotated[Str, Length(123)],
) -> None:
raise NotImplementedError
```
```py
@with_annotated_args
@tanjun.as_slash_command("meow", "description")
async def command(
ctx: tanjun.abc.SlashContext,
argument: Annotated[Str, range(5, 100), "description"],
other_argument: Annotated[Str, 4:64, "description"],
) -> None:
raise NotImplementedError
```
Alternatively, the slice syntax and `range` may be used to set the length
restraints for a string argument (where the start is inclusive and stop is
exclusive). These default to a min_length of `0` if the start isn't
specified and ignores any specified step.
"""
__slots__ = ("_min_length", "_max_length")
@typing.overload
def __init__(self, max_length: int, /) -> None:
...
@typing.overload
def __init__(self, min_length: int, max_length: int, /) -> None:
...
def __init__(self, min_or_max_length: int, max_length: typing.Optional[int] = None, /) -> None:
"""Initialise a length constraint.
Parameters
----------
min_or_max_length
If `max_length` is left as [None][] then this will be used as the
maximum length and the minimum length will be `0`.
Otherwise this will be the minimum length this string option can be.
max_length
The maximum length this string argument can be.
If not specified then `min_or_max_length` will be used as the max
length.
"""
if max_length is None:
self._min_length = 0
self._max_length = min_or_max_length
else:
self._min_length = min_or_max_length
self._max_length = max_length
@property
def min_length(self) -> int:
"""The minimum length of this string option."""
return self._min_length
@property
def max_length(self) -> int:
"""The maximum length of this string option."""
return self._max_length
def set_config(self, config: _ArgConfig, /) -> None:
config.min_length = self._min_length
config.max_length = self._max_length
# TODO: validate this is only set for str options
class _MaxMeta(abc.ABCMeta):
@typing_extensions.deprecated("Pass Max(...) to Annotated")
def __getitem__(cls, value: _NumberT, /) -> type[_NumberT]:
if isinstance(value, int):
return typing.cast("type[_NumberT]", typing.Annotated[Int, Max(value)])
return typing.cast("type[_NumberT]", typing.Annotated[Float, Max(value)])
class Max(_ConfigIdentifier, metaclass=_MaxMeta):
"""Inclusive maximum value for a [Float][tanjun.annotations.Float] or [Int][tanjun.annotations.Int] argument.
Examples
--------
```py
@with_annotated_args
@tanjun.as_slash_command("beep", "meow")
async def command(
ctx: tanjun.abc.Context,
age: Annotated[Int, Max(130), "How old are you?"],
number: Annotated[Float, Max(130.2), "description"],
) -> None:
raise NotImplementedError
```
"""
__slots__ = ("_value",)
def __init__(self, value: typing.Union[int, float], /) -> None:
"""Create an argument maximum value.
Parameters
----------
value
The maximum allowed value allowed for an argument.
"""
self._value = value
@property
def value(self) -> typing.Union[int, float]:
"""The maximum allowed value."""
return self._value
def set_config(self, config: _ArgConfig, /) -> None:
config.max_value = self._value
class _MinMeta(abc.ABCMeta):
@typing_extensions.deprecated("Pass Min(...) to Annotated")
def __getitem__(cls, value: _NumberT, /) -> type[_NumberT]:
if isinstance(value, int):
return typing.cast("type[_NumberT]", typing.Annotated[Int, Min(value)])
return typing.cast("type[_NumberT]", typing.Annotated[Float, Min(value)])
class Min(_ConfigIdentifier, metaclass=_MinMeta):
"""Inclusive minimum value for a [Float][tanjun.annotations.Float] or [Int][tanjun.annotations.Int] argument.
Examples
--------
```py
@with_annotated_args
@tanjun.as_slash_command("beep", "meow")
async def command(
ctx: tanjun.abc.Context,
age: Annotated[Int, Min(13), "How old are you?"],
number: Annotated[Float, Min(13.9), "description"],
) -> None:
raise NotImplementedError
```
"""
__slots__ = ("_value",)
def __init__(self, value: typing.Union[int, float], /) -> None:
"""Create an argument minimum value.
Parameters
----------
value
The minimum value allowed for an argument.
"""
self._value = value
@property
def value(self) -> typing.Union[int, float]:
"""The minimum allowed value."""
return self._value
def set_config(self, config: _ArgConfig, /) -> None:
config.min_value = self._value
class Name(_ConfigIdentifier):
"""Override the inferred name used to declare an option.
Examples
--------
```py
@with_annotated_args(follow_wrapped=True)
@tanjun.as_slash_command("meow", "nyaa")
@tanjun.as_message_command("meow")
async def command(
ctx: tanjun.abc.Context,
resource_type: Annotated[Str, Name("type"), "The type of resource to get."],
) -> None:
raise NotImplementedError
```
"""
__slots__ = ("_message_name", "_slash_name")
def __init__(
self,
both: typing.Optional[str] = None,
/,
*,
message: typing.Optional[str] = None,
slash: typing.Optional[str] = None,
) -> None:
"""Create an argument name override.
Parameters
----------
both
If provided, the name to use for this option in message and slash
commands.
This will be reformatted a bit for message commands (prefixed with
`--` and `.replace("_", "-")`) and is only used for message flag
options.
message
The name to use for this option in message commands.
This takes priority over `both`, is not reformatted and only is
only used for flag options.
slash
The name to use for this option in slash commands.
This takes priority over `both`.
"""
if both and not message:
message = "--" + both.replace("_", "-")
self._message_name = message
self._slash_name = slash or both
@property
def message_name(self) -> typing.Optional[str]:
"""The name to use for this option in message commands."""
return self._message_name
@property
def slash_name(self) -> typing.Optional[str]:
"""The name to use for this option in slash commands."""
return self._slash_name
def set_config(self, config: _ArgConfig, /) -> None:
config.slash_name = self._slash_name or config.slash_name
if self._message_name:
config.main_message_name = self._message_name
config.message_names = [self._message_name, *config.message_names[1:]]
class _RangedMeta(abc.ABCMeta):
@typing_extensions.deprecated("Pass Ranged(...) to Annotated")
def __getitem__(cls, range_: tuple[_NumberT, _NumberT], /) -> type[_NumberT]:
# This better matches how type checking (well pyright at least) will
# prefer to go to float if either value is float.
if isinstance(range_[0], float) or isinstance(range_[1], float):
return typing.cast("type[_NumberT]", typing.Annotated[Float, Ranged(range_[0], range_[1])])
return typing.cast("type[_NumberT]", typing.Annotated[Int, Ranged(range_[0], range_[1])])
class Ranged(_ConfigIdentifier, metaclass=_RangedMeta):
"""Declare the range limit for an `Int` or `Float` argument.
Examples
--------
```py
@with_annotated_args(follow_wrapped=True)
@tanjun.as_slash_command("meow", "nyaa")
@tanjun.as_message_command("meow")
async def command(
ctx: tanjun.abc.Context,
number_arg: Annotated[Int, Ranged(0, 69), "description"],
other_number_arg: Annotated[Float, Ranged(13.69, 420.69), "description"],
) -> None:
raise NotImplementedError
```
```py
@with_annotated_args
@tanjun.as_slash_command("meow", "description")
async def command(
ctx: tanjun.abc.SlashContext,
float_value: Annotated[Float, 1.5:101.5, "description"],
int_value: Annotated[Int, range(5, 100), "description"],
) -> None:
raise NotImplementedError
```
Alternatively, the slice syntax and `range` may be used to set the range
for a float or integer argument (where the start is inclusive and stop is
exclusive). These default to a min_value of `0` if the start isn't
specified and ignores any specified step.
"""
__slots__ = ("_max_value", "_min_value")
def __init__(self, min_value: typing.Union[int, float], max_value: typing.Union[int, Float], /) -> None:
"""Create an argument range limit.
Parameters
----------
min_value
The minimum allowed value for this argument.
max_value
The maximum allowed value for this argument.
"""
self._max_value = max_value
self._min_value = min_value
@property
def max_value(self) -> typing.Union[int, float]:
"""The maximum allowed value for this argument."""
return self._max_value
@property
def min_value(self) -> typing.Union[int, float]:
"""The minimum allowed value for this argument."""
return self._min_value
def set_config(self, config: _ArgConfig, /) -> None:
config.max_value = self._max_value
config.min_value = self._min_value
# _MESSAGE_ID_ONLY
_SNOWFLAKE_PARSERS: dict[type[typing.Any], collections.Callable[[str], hikari.Snowflake]] = {
hikari.Member: conversion.parse_user_id,
hikari.PartialChannel: conversion.parse_channel_id,
hikari.User: conversion.parse_user_id,
hikari.Role: conversion.parse_role_id,
}
class _SnowflakeOrMeta(abc.ABCMeta):
@typing_extensions.deprecated("Pass SnowflakeOr(...) to Annotated")
def __getitem__(cls, type_: type[_T], /) -> type[typing.Union[hikari.Snowflake, _T]]:
for entry in _snoop_annotation_args(type_):
if not isinstance(entry, _OptionMarker):
continue
try:
parser = _SNOWFLAKE_PARSERS[entry.type]
except (KeyError, TypeError): # Also catch unhashable
pass
else:
descriptor = SnowflakeOr(parse_id=parser)
break
else:
descriptor = SnowflakeOr()
return typing.cast(
"type[typing.Union[hikari.Snowflake, _T]]",
typing.Annotated[typing.Union[hikari.Snowflake, type_], descriptor],
)
class SnowflakeOr(_ConfigIdentifier, metaclass=_SnowflakeOrMeta):
"""Mark an argument as taking an object or its ID.
This allows for the argument to be declared as taking the object for slash
commands without requiring that the message command equivalent fetch the
object each time for the following types:
* [User][tanjun.annotations.User]
* [Role][tanjun.annotations.Role]
* [Member][tanjun.annotations.Member]
* [Channel][tanjun.annotations.Channel]
* [Mentionable][tanjun.annotations.Mentionable]
Examples
--------
```py
@with_annotated_args(follow_wrapped=True)
@tanjun.as_slash_command("meow", "nyaa")
@tanjun.as_message_command("meow")
async def command(
ctx: tanjun.abc.Context,
user: Annotated[User, SnowflakeOr(parse_id=parse_user_id), "The user to target."],
) -> None:
user_id = hikari.Snowflake(user)
```
"""
__slots__ = ("_parse_id",)
def __init__(self, *, parse_id: collections.Callable[[str], hikari.Snowflake] = conversion.parse_snowflake) -> None:
"""Create a snowflake or argument marker.
Parameters
----------
parse_id
The function used to parse the argument's ID.
This can be used to restrain this to only accepting certain mention
formats.
"""
self._parse_id = parse_id
@property
def parse_id(self) -> collections.Callable[[str], hikari.Snowflake]:
"""Callback used to parse this argument's ID."""
return self._parse_id
def set_config(self, config: _ArgConfig, /) -> None:
config.snowflake_converter = self._parse_id
class _TheseChannelsMeta(abc.ABCMeta):
@typing_extensions.deprecated("Pass TheseChannels(...) to Annotated")
def __getitem__(
cls, value: typing.Union[_ChannelTypeIsh, collections.Collection[_ChannelTypeIsh]], /
) -> type[hikari.PartialChannel]:
if not isinstance(value, collections.Collection):
value = (value,)
return typing.Annotated[Channel, TheseChannels(*value)]
class TheseChannels(_ConfigIdentifier, metaclass=_TheseChannelsMeta):
"""Restrain the type of channels a channel argument can target."""
__slots__ = ("_channel_types",)
def __init__(self, channel_type: _ChannelTypeIsh, /, *other_types: _ChannelTypeIsh) -> None:
"""Create a channel argument restraint.
Parameters
----------
channel_type
A channel type to restrain this argument by.
*other_types
Other channel types to restrain this argument by.
"""
self._channel_types = (channel_type, *other_types)
@property
def channel_types(self) -> collections.Sequence[_ChannelTypeIsh]:
"""Sequence of the channel types this is constrained by."""
return self._channel_types
def set_config(self, config: _ArgConfig, /) -> None:
config.channel_types = self._channel_types
def _ensure_value(name: str, type_: type[_T], value: typing.Optional[typing.Any], /) -> typing.Optional[_T]:
if value is None or isinstance(value, type_):
return value
raise TypeError(
f"{name.capitalize()} value of type {type(value).__name__} is not valid for a {type_.__name__} argument"
)
def _ensure_values(
name: str, type_: type[_T], mapping: typing.Optional[collections.Mapping[str, typing.Any]], /
) -> typing.Optional[collections.Mapping[str, _T]]:
if not mapping:
return None
for value in mapping.values():
if not isinstance(value, type_):
raise TypeError(
f"{name.capitalize()} of type {type(value).__name__} is not valid for a {type_.__name__} argument"
)
return typing.cast("collections.Mapping[str, _T]", mapping)
_OPTION_TYPE_TO_CONVERTERS: dict[typing.Any, tuple[collections.Callable[..., typing.Any], ...]] = {
hikari.Attachment: NotImplemented, # This isn't supported for message commands right now.
bool: (conversion.to_bool,),
hikari.PartialChannel: NotImplemented, # This is special-cased down the line.
hikari.InteractionChannel: NotImplemented, # This isn't supported for message commands.
float: (float,),
int: (int,),
hikari.Member: (conversion.to_member,),
hikari.InteractionMember: NotImplemented, # This isn't supported for message commands.
_MentionableUnion: (conversion.to_user, conversion.to_role),
hikari.Role: (conversion.to_role,),
str: (),
hikari.User: (conversion.to_user,),
}
_MESSAGE_ID_ONLY: frozenset[typing.Any] = frozenset(
[hikari.User, hikari.Role, hikari.Member, hikari.PartialChannel, _MentionableUnion]
)
class _ArgConfig:
__slots__ = (
"channel_types",
"choices",
"default",
"description",
"empty_value",
"float_converter",
"has_natural_default",
"int_converter",
"is_greedy",
"is_positional",
"key",
"main_message_name",
"min_length",
"max_length",
"min_value",
"max_value",
"message_names",
"option_type",
"range_or_slice",
"slash_name",
"snowflake_converter",
"str_converters",
)
def __init__(self, key: str, default: typing.Any, /, *, description: typing.Optional[str]) -> None:
self.channel_types: collections.Sequence[_ChannelTypeIsh] = ()
self.choices: typing.Optional[collections.Mapping[str, _ChoiceUnion]] = None
self.default: typing.Any = default
self.description: typing.Optional[str] = description
self.empty_value: typing.Any = tanjun.NO_DEFAULT
self.float_converter: typing.Optional[collections.Callable[[float], typing.Any]] = None
self.has_natural_default: bool = default is tanjun.NO_PASS
self.int_converter: typing.Optional[collections.Callable[[int], typing.Any]] = None
# The float and int converters are just for Choices[Enum].
self.is_greedy: typing.Optional[bool] = None
self.is_positional: typing.Optional[bool] = None
self.key: str = key
self.main_message_name: str = "--" + key.replace("_", "-")
self.min_length: typing.Optional[int] = None
self.max_length: typing.Optional[int] = None
self.min_value: typing.Union[float, int, None] = None
self.max_value: typing.Union[float, int, None] = None
self.message_names: collections.Sequence[str] = [self.main_message_name]
self.option_type: typing.Optional[typing.Any] = None
self.range_or_slice: typing.Union[range, slice, None] = None
self.slash_name: str = key
self.snowflake_converter: typing.Optional[collections.Callable[[str], hikari.Snowflake]] = None
self.str_converters: collections.Sequence[_ConverterSig[typing.Any]] = ()
def set_option_type(self, option_type: typing.Any, /) -> None:
if self.option_type is not None and option_type != self.option_type:
raise RuntimeError(
f"Conflicting option types of {self.option_type} and {option_type} found for {self.key!r} parameter"
)
self.option_type = option_type
def from_annotation(self, annotation: typing.Any, /) -> Self:
for arg in _snoop_annotation_args(annotation):
if isinstance(arg, _ConfigIdentifier):
arg.set_config(self)
elif not self.description and isinstance(arg, str):
self.description = arg
elif isinstance(arg, (range, slice)):
self.range_or_slice = arg
return self
def finalise_slice(self) -> Self:
if not self.range_or_slice:
return self
# Slice's attributes are all Any so we need to cast to int.
if self.range_or_slice.step is None or operator.index(self.range_or_slice.step) > 0:
min_value = operator.index(self.range_or_slice.start) if self.range_or_slice.start is not None else 0
max_value = operator.index(self.range_or_slice.stop) - 1
else:
# start will have to have been specified for this to be reached.
min_value = operator.index(self.range_or_slice.stop) - 1
max_value = operator.index(self.range_or_slice.start)
if self.option_type is str:
self.min_length = min_value
self.max_length = max_value
elif self.option_type is int or self.option_type is float:
self.min_value = min_value
self.max_value = max_value
return self
def add_to_msg_cmds(self, commands: collections.Sequence[message.MessageCommand[typing.Any]], /) -> Self:
if not commands:
return self
if self.str_converters:
converters = self.str_converters
elif self.option_type:
if self.snowflake_converter and self.option_type in _MESSAGE_ID_ONLY:
converters = (self.snowflake_converter,)
elif (converters_ := _OPTION_TYPE_TO_CONVERTERS[self.option_type]) is not NotImplemented:
converters = converters_
elif self.option_type is hikari.PartialChannel:
converters = (conversion.ToChannel(allowed_types=self.channel_types or None),)
elif not self.has_natural_default:
raise RuntimeError(f"{self.option_type!r} is not supported for message commands")
else:
# If there is a real default then this should just be left to always default
# for better interoperability.
return self
else:
return self
for command in commands:
if command.parser:
if not isinstance(command.parser, parsing.AbstractOptionParser):
raise TypeError("Expected parser to be an instance of tanjun.parsing.AbstractOptionParser")
parser = command.parser
else:
parser = parsing.ShlexParser()
command.set_parser(parser)
if self.is_positional or (self.is_positional is None and self.default is tanjun.NO_DEFAULT):
parser.add_argument(
self.key,
converters=converters,
default=self.default,
greedy=False if self.is_greedy is None else self.is_greedy,
min_length=self.min_length,
max_length=self.max_length,
min_value=self.min_value,
max_value=self.max_value,
)
elif self.default is tanjun.NO_DEFAULT:
raise ValueError(f"Flag argument {self.key!r} must have a default")
else:
parser.add_option(
self.key,
*self.message_names,
converters=converters,
default=self.default,
empty_value=self.empty_value,
min_length=self.min_length,
max_length=self.max_length,
min_value=self.min_value,
max_value=self.max_value,
)
return self
def add_to_slash_cmds(self, commands: collections.Sequence[slash.SlashCommand[typing.Any]], /) -> Self:
if self.option_type:
option_adder = self.SLASH_OPTION_ADDER[self.option_type]
for command in commands:
if not self.description:
raise ValueError(f"Missing description for argument {self.key!r}")
option_adder(self, command, self.description)
return self
SLASH_OPTION_ADDER: dict[
typing.Any, collections.Callable[[Self, slash.SlashCommand[typing.Any], str], slash.SlashCommand[typing.Any]]
] = {
hikari.Attachment: lambda self, c, d: c.add_attachment_option(
self.slash_name, d, default=self.default, key=self.key
),
bool: lambda self, c, d: c.add_bool_option(self.slash_name, d, default=self.default, key=self.key),
hikari.PartialChannel: lambda self, c, d: c.add_channel_option(
self.slash_name, d, default=self.default, key=self.key, types=self.channel_types or None
),
float: lambda self, c, d: c.add_float_option(
self.slash_name,
d,
choices=_ensure_values("choice", float, self.choices), # TODO: can we pass ints here as well?
converters=self.float_converter or (),
default=self.default,
key=self.key,
min_value=self.min_value, # TODO: explicitly cast to float?
max_value=self.max_value,
),
int: lambda self, c, d: c.add_int_option(
self.slash_name,
d,
choices=_ensure_values("choice", int, self.choices),
converters=self.int_converter or (),
default=self.default,
key=self.key,
min_value=_ensure_value("min", int, self.min_value),
max_value=_ensure_value("max", int, self.max_value),
),
hikari.Member: lambda self, c, d: c.add_member_option(self.slash_name, d, default=self.default, key=self.key),
_MentionableUnion: lambda self, c, d: c.add_mentionable_option(
self.slash_name, d, default=self.default, key=self.key
),
hikari.Role: lambda self, c, d: c.add_role_option(self.slash_name, d, default=self.default, key=self.key),
str: lambda self, c, d: c.add_str_option(
self.slash_name,
d,
choices=_ensure_values("choice", str, self.choices),
converters=self.str_converters,
default=self.default,
key=self.key,
min_length=self.min_length,
max_length=self.max_length,
),
hikari.User: lambda self, c, d: c.add_user_option(self.slash_name, d, default=self.default, key=self.key),
}
SLASH_OPTION_ADDER[hikari.InteractionChannel] = SLASH_OPTION_ADDER[hikari.PartialChannel]
SLASH_OPTION_ADDER[hikari.InteractionMember] = SLASH_OPTION_ADDER[hikari.Member]
_WRAPPER_TYPES = {typing_extensions.Required, typing_extensions.NotRequired}
def _snoop_annotation_args(type_: typing.Any, /) -> collections.Iterator[typing.Any]:
origin = typing_extensions.get_origin(type_)
if origin is typing.Annotated:
args = typing_extensions.get_args(type_)
yield from _snoop_annotation_args(args[0])
yield from args[1:]
elif origin in _internal.UnionTypes:
yield from itertools.chain.from_iterable(map(_snoop_annotation_args, typing_extensions.get_args(type_)))
elif origin in _WRAPPER_TYPES:
yield from _snoop_annotation_args(typing_extensions.get_args(type_)[0])
def parse_annotated_args(
command: typing.Union[slash.SlashCommand[typing.Any], message.MessageCommand[typing.Any]],
/,
*,
descriptions: typing.Optional[collections.Mapping[str, str]] = None,
follow_wrapped: bool = False,
) -> None:
"""Set a command's arguments based on its signature.
For more information on how this works see
[with_annotated_args][tanjun.annotations.with_annotated_args] which acts as
the decorator equivalent of this. The only difference is function allows
passing a mapping of argument descriptions.
Parameters
----------
command
The message or slash command to set the arguments for.
descriptions
Mapping of descriptions to use for this command's slash command options.
If an option isn't included here then this will default back to getting
the description from its annotation.
follow_wrapped
Whether this should also set the arguments on any other command objects
this wraps in a decorator call chain.
"""
try:
signature = inspect.signature(command.callback, eval_str=True)
except ValueError: # If we can't inspect it then we have to assume this is a NO
# As a note, this fails on some "signature-less" builtin functions/types like str.
return
descriptions = descriptions or {}
message_commands: list[message.MessageCommand[typing.Any]] = []
slash_commands: list[slash.SlashCommand[typing.Any]] = []
if isinstance(command, slash.SlashCommand):
slash_commands.append(command)
else:
message_commands.append(command)
if follow_wrapped:
for sub_command in _internal.collect_wrapped(command):
if isinstance(sub_command, message.MessageCommand):
message_commands.append(sub_command)
elif isinstance(sub_command, slash.SlashCommand):
slash_commands.append(sub_command)
for parameter in signature.parameters.values():
if parameter.annotation is parameter.empty:
continue
if parameter.kind is not parameter.VAR_KEYWORD:
if parameter.default is not parameter.empty and isinstance(parameter.default, _ConfigIdentifier):
arg = _ArgConfig(parameter.name, tanjun.NO_DEFAULT, description=descriptions.get(parameter.name))
parameter.default.set_config(arg)
else:
default = tanjun.NO_DEFAULT if parameter.default is parameter.empty else tanjun.NO_PASS
arg = _ArgConfig(parameter.name, default, description=descriptions.get(parameter.name))
(
arg.from_annotation(parameter.annotation)
.finalise_slice()
.add_to_msg_cmds(message_commands)
.add_to_slash_cmds(slash_commands)
)
continue
if typing_extensions.get_origin(parameter.annotation) is not typing_extensions.Unpack:
continue
typed_dict = typing_extensions.get_args(parameter.annotation)[0]
if not typing_extensions.is_typeddict(typed_dict):
continue
for name, annotation in typing_extensions.get_type_hints(typed_dict, include_extras=True).items():
default = tanjun.NO_PASS if name in typed_dict.__optional_keys__ else tanjun.NO_DEFAULT
(
_ArgConfig(name, default, description=descriptions.get(name))
.from_annotation(annotation)
.finalise_slice()
.add_to_msg_cmds(message_commands)
.add_to_slash_cmds(slash_commands)
)
return
@typing.overload
def with_annotated_args(command: _CommandUnionT, /) -> _CommandUnionT:
...
@typing.overload
def with_annotated_args(*, follow_wrapped: bool = False) -> collections.Callable[[_CommandUnionT], _CommandUnionT]:
...
def with_annotated_args(
command: typing.Optional[_CommandUnionT] = None, /, *, follow_wrapped: bool = False
) -> typing.Union[_CommandUnionT, collections.Callable[[_CommandUnionT], _CommandUnionT]]:
r"""Set a command's arguments based on its signature.
For more information on how this works see [tanjun.annotations][].
Parameters
----------
command : tanjun.SlashCommand | tanjun.MessageCommand
The message or slash command to set the arguments for.
follow_wrapped
Whether this should also set the arguments on any other command objects
this wraps in a decorator call chain.
Returns
-------
tanjun.SlashCommand | tanjun.MessageCommand
The command object to enable using this as a decorator.
"""
if not command:
def decorator(command: _CommandUnionT, /) -> _CommandUnionT:
parse_annotated_args(command, follow_wrapped=follow_wrapped)
return command
return decorator
parse_annotated_args(command, follow_wrapped=follow_wrapped)
return command |
import { BaseShape } from "./BaseShape";
export class Dot extends BaseShape {
private DOT_SIZE: number = 3;
public constructor(x: number, y: number, color: string = 'black') {
super(x, y, color);
}
public getHeight(): number {
return this.DOT_SIZE;
}
public getWidth(): number {
return this.DOT_SIZE;
}
public paint(ctx: CanvasRenderingContext2D): void {
super.paint(ctx);
ctx.fillRect(this.getX() - 1, this.getY() - 1, this.DOT_SIZE, this.DOT_SIZE);
}
} |
/** @module : m_control
* @author : Secure, Trusted, and Assured Microelectronics (STAM) Center
* Copyright (c) 2022 Trireme (STAM/SCAI/ASU)
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
module m_control #(
parameter CORE = 0,
parameter SCAN_CYCLES_MIN = 0,
parameter SCAN_CYCLES_MAX = 1000
) (
input clock,
input reset,
input [6:0] opcode_decode,
input [2:0] funct3, // decode
input [6:0] funct7, // decode
input [5:0] ALU_operation_base,
output [5:0] ALU_operation,
input scan
);
//define the log2 function
function integer log2;
input integer value;
begin
value = value-1;
for (log2=0; value>0; log2=log2+1)
value = value >> 1;
end
endfunction
localparam [6:0]R_TYPE = 7'b0110011,
I_TYPE = 7'b0010011,
STORE = 7'b0100011,
LOAD = 7'b0000011,
BRANCH = 7'b1100011,
JALR = 7'b1100111,
JAL = 7'b1101111,
AUIPC = 7'b0010111,
LUI = 7'b0110111,
FENCE = 7'b0001111,
SYSTEM = 7'b1110011;
// RV64 Opcodes
localparam [6:0]IMM_32 = 7'b0011011,
OP_32 = 7'b0111011;
// Check for operations other than addition. Use addition as default case
assign ALU_operation =
(opcode_decode == R_TYPE & funct3 == 3'b000 & funct7 == 7'b0000001) ? 6'd20 : // MUL
(opcode_decode == R_TYPE & funct3 == 3'b001 & funct7 == 7'b0000001) ? 6'd21 : // MULH
(opcode_decode == R_TYPE & funct3 == 3'b011 & funct7 == 7'b0000001) ? 6'd22 : // MULHU
(opcode_decode == R_TYPE & funct3 == 3'b010 & funct7 == 7'b0000001) ? 6'd23 : // MULHSU
(opcode_decode == R_TYPE & funct3 == 3'b100 & funct7 == 7'b0000001) ? 6'd24 : // DIV
(opcode_decode == R_TYPE & funct3 == 3'b101 & funct7 == 7'b0000001) ? 6'd25 : // DIVU
(opcode_decode == R_TYPE & funct3 == 3'b110 & funct7 == 7'b0000001) ? 6'd26 : // REM
(opcode_decode == R_TYPE & funct3 == 3'b111 & funct7 == 7'b0000001) ? 6'd27 : // REMU
(opcode_decode == OP_32 & funct3 == 3'b000 & funct7 == 7'b0000001) ? 6'd28 : // MULW
(opcode_decode == OP_32 & funct3 == 3'b100 & funct7 == 7'b0000001) ? 6'd29 : // DIVW
(opcode_decode == OP_32 & funct3 == 3'b101 & funct7 == 7'b0000001) ? 6'd30 : // DIVUW
(opcode_decode == OP_32 & funct3 == 3'b110 & funct7 == 7'b0000001) ? 6'd31 : // REMW
(opcode_decode == OP_32 & funct3 == 3'b111 & funct7 == 7'b0000001) ? 6'd32 : // REMUW
ALU_operation_base;
reg [31: 0] cycles;
always @ (posedge clock) begin
cycles <= reset? 0 : cycles + 1;
if (scan & ((cycles >= SCAN_CYCLES_MIN) & (cycles <= SCAN_CYCLES_MAX)) )begin
$display ("------ Core %d M Control Unit - Current Cycle %d ------", CORE, cycles);
$display ("| ALU_operation [%b]", ALU_operation);
$display ("----------------------------------------------------------------------");
end
end
endmodule |
import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import * as actionType from '../../store/actions'
import MySpinner from '../hoc/Spinner'
import { Container, Jumbotron, Col, Table } from 'react-bootstrap';
import ProjectsList from '../projects/projectsList'
import { getUserFromServer } from './UserFunctions'
import { getProjectsFromServer } from '../projects/ProjectFunctions'
import Logout from './Logout';
const Profile = (props) => {
const [loading, setLoading] = useState(true)
const getUser = async (username) => {
await getUserFromServer(username)
.then(response => {
if (response.error) {
props.history.push(`/`)
return
}
props.setProfilePage(response)
getProjects(response)
}).catch(err => console.log(err))
}
const getProjects = async (data) => {
await getProjectsFromServer(props.history.location.pathname.slice(9), data.ID)
.then(projectsRes => {
props.setProjects(projectsRes)
})
.then(res => {
setLoading(false);
}).catch(err => console.log(err));
}
useEffect(() => {
setLoading(true)
getUser(props.history.location.pathname.slice(9))
// eslint-disable-next-line
}, [props.location.state])
return (
<>
{loading ?
<MySpinner /> :
<Container>
<Jumbotron className="mt-5 my-shadow">
<Col sm={8} className="mx-auto">
<h1 className="text-center">{props.profilePageData.user_name}</h1>
</Col>
<Table className="col-md-8 mx-auto">
<tbody>
<tr>
<td>Email</td>
<td>{props.profilePageData.email}</td>
</tr>
<tr>
<td>Github profile</td>
<td><a href={props.profilePageData.github_profile} target="_blank" rel="noopener noreferrer">{props.profilePageData.github_profile}</a></td>
</tr>
</tbody>
</Table>
{props.loggedIn && props.history.location.pathname.slice(9) === props.userData.user_name ? <Logout /> : null}
</Jumbotron>
<ProjectsList user={true} />
</Container>}
</>
)
}
const mapStateToProps = state => {
return {
loggedIn: state.users.isLoggedIn,
userData: state.users.userData,
profilePageData: state.users.profilePageData,
projects: state.projects.projects,
};
}
const mapDispatchToProps = dispatch => {
return {
setProfilePage: (profilePageData) => dispatch({ type: actionType.SET_PROFILE_PAGE_DATA, profilePageData: profilePageData }),
setProjects: (projects) => dispatch({ type: actionType.SET_PROJECTS, projects: projects }),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Profile) |
import 'package:flutter/material.dart';
import 'buttom_row.dart';
import 'button.dart';
class Keyboard extends StatelessWidget {
final void Function(String) cb;
Keyboard(this.cb);
@override
Widget build(BuildContext context) {
return Container(
height: 500,
child: Column(
children: <Widget>[
ButtonRow([
Button.operation(
text: 'AC',
cb: cb,
color: Button.DARK,
),
Button.operation(
text: '+/-',
cb: cb,
//color: Button.DARK,
),
Button.operation(
text: '%',
cb: cb,
//color: Button.DARK,
),
Button.operation(
text: '/',
cb: cb,
),
]),
ButtonRow([
Button(
text: '7',
cb: cb,
),
Button(
text: '8',
cb: cb,
),
Button(
text: '9',
cb: cb,
),
Button.operation(
text: 'x',
cb: cb,
),
]),
ButtonRow([
Button(
text: '4',
cb: cb,
),
Button(
text: '5',
cb: cb,
),
Button(
text: '6',
cb: cb,
),
Button.operation(
text: '-',
cb: cb,
),
]),
ButtonRow([
Button(
text: '1',
cb: cb,
),
Button(
text: '2',
cb: cb,
),
Button(
text: '3',
cb: cb,
),
Button.operation(
text: '+',
cb: cb,
),
]),
ButtonRow([
Button.big(
text: '0',
cb: cb,
),
Button(
text: '.',
cb: cb,
),
Button.operation(
text: '=',
cb: cb,
),
]),
],
),
);
}
} |
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('sessions', {
id: {
type: Sequelize.DataTypes.UUID,
primaryKey: true,
allowNull: false,
unique: true,
},
userId: {
type: Sequelize.DataTypes.UUID,
allowNull: false,
field: 'user_id'
},
osName: {
type: Sequelize.DataTypes.STRING,
field: 'os_name',
},
osVersion: {
type: Sequelize.DataTypes.STRING,
field: 'os_version',
},
device: {
type: Sequelize.DataTypes.STRING,
field: 'device',
},
browser: {
type: Sequelize.DataTypes.STRING,
field: 'browser',
},
browserVersion: {
type: Sequelize.DataTypes.STRING,
field: 'browser_version',
},
browserEngine: {
type: Sequelize.DataTypes.STRING,
field: 'browser_engine',
},
browserEngineVersion: {
type: Sequelize.DataTypes.STRING,
field: 'browser_engine_version',
},
sessionStartTime: {
type: Sequelize.DataTypes.DATE,
allowNull: false,
field: 'session_start_time',
defaultValue: new Date(),
},
sessionEndTime: {
type: Sequelize.DataTypes.DATE,
field: 'session_end_time',
},
lastActivityTime: {
type: Sequelize.DataTypes.DATE,
field: 'last_activity_time',
},
sessionType: {
type: Sequelize.DataTypes.STRING,
allowNull: false,
field: "session_type",
},
sessionStatus: {
type: Sequelize.DataTypes.STRING,
allowNull: false,
field: "session_status",
},
refreshToken: {
type: Sequelize.DataTypes.TEXT,
field: "refresh_token",
},
ipAddress: {
type: Sequelize.DataTypes.STRING,
field: "ip_address",
},
sessionData: {
type: Sequelize.DataTypes.TEXT,
field: "session_data",
},
botInfo: {
type: Sequelize.DataTypes.TEXT,
field: "bot_info",
},
createdAt: {
allowNull: false,
type: Sequelize.DataTypes.DATE,
field: 'created_at',
defaultValue: new Date(),
},
updatedAt: {
type: Sequelize.DataTypes.DATE,
field: 'updated_at'
},
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('sessions');
}
}; |
import { combineLatest } from 'rxjs';
import { map } from 'rxjs/operators';
import { ObservableBoolean } from '../../types';
/**
* Combines a series of ObservableBooleans using 'AND' and returns a single ObservableBoolean
*
* @param observableBooleans - An array of ObservableBooleans
*/
export const combineBooleans = (observableBooleans: ObservableBoolean[]): ObservableBoolean => {
return combineLatest(observableBooleans).pipe(
map((result) => result.reduce((previous, current) => previous && current))
);
}; |
const express = require("express");
const userRouter = express.Router();
const User = require('../Schema/UserSchema');
const bcrypt = require('bcrypt');
const cloudinary = require('cloudinary');
const multer = require("multer");
const generateCertificate = require('./CertficateRoute')
const storage = multer.memoryStorage();
const upload3 = multer({ storage: storage });
cloudinary.config({
cloud_name: process.env.CLOUD_NAME,
api_key: process.env.API_KEY,
api_secret: process.env.SECRET_API,
});
const upload = multer({ dest: 'uploads/' });
userRouter.get("/", async (req, res) => {
try {
const data = await User.find();
res.status(200).send(data);
} catch (err) {
res.status(500).json({ message: err });
}
});
userRouter.post("/signup", async (req, res) => {
try {
const { name, email, password, bio, city } = req.body;
if (!name || !email || !password) {
return res.status(400).json({
error: "Please provide name, email, and password"
});
}
const existingUserWithEmail = await User.findOne({ email });
if (existingUserWithEmail) {
return res.status(400).json({
error: "Email already exists"
});
}
const existingUserWithName = await User.findOne({ name });
if (existingUserWithName) {
return res.status(400).json({
error: "Username already exists"
});
}
// Hash the password
const hashedPassword = await bcrypt.hash(password, 10);
const newUser = new User({
name,
email,
password: hashedPassword,
bio,
city
});
await newUser.save();
res.status(201).json({
message: "User created successfully",
user: newUser
});
} catch (err) {
console.error("Error signing up:", err);
res.status(500).json({
error: "Error signing up"
});
}
});
userRouter.post("/login", async (req, res) => {
const { email } = req.body;
// console.log(hi)
if (!email) {
return res.status(400).send("No email was sent.");
}
console.log(email);
const { password } = req.body;
try {
const user = await User.findOne({ email: email });
if (!user) {
return res.status(404).send({ error: "User not found" });
}
if (user && !password) {
return res.status(200).send(user);
}
const passwordMatch = await bcrypt.compare(password, user.password);
if (passwordMatch) {
return res.status(200).send(user);
} else {
return res.status(401).send({ error: 'Password does not match' });
}
} catch (error) {
console.error("Error logging in user:", error);
res.status(500).json({ error: "Internal server error" });
}
});
userRouter.put("/profile/update", upload.single('profilePhoto'), async (req, res) => {
const { userName, email, bio, city } = req.body;
const file = req.file;
try {
let user = await User.findOne({ email });
if (!user) {
return res.status(404).json({ error: "User not found" });
}
const existingUserWithName = await User.findOne({ name: userName });
if (existingUserWithName && existingUserWithName.email !== email) {
return res.status(400).json({ error: "Username already exists" });
} else {
user.name = userName;
}
if (file) {
try {
const result = await cloudinary.uploader.upload(file.path, {
resource_type: "image",
folder: "images"
});
console.log('Photo uploaded to Cloudinary:', result);
user.profilePhoto = result.secure_url;
} catch (error) {
console.error('Error uploading photo to Cloudinary:', error);
return res.status(500).json({ error: 'Failed to upload photo' });
}
}
user.bio = bio;
user.city = city;
await user.save();
return res.status(200).json({ message: "User updated successfully", user });
} catch (error) {
console.error("Error updating user:", error);
res.status(500).json({ error: "Internal server error" });
}
});
userRouter.post("/profile", async (req, res) => {
const { name } = req.body;
try {
const user = await User.findOne({ name });
res.status(200).json({ user });
} catch (error) {
res.status(400).send("Error: ", error);
}
});
userRouter.delete("/profileDelete", async (req, res) => {
console.log(req.body);
const email = req.body;
try {
const user = await User.findOneAndDelete(email);
if (!user) {
return res.status(404).json({ error: "User not found" });
}
res.status(200).json({ message: "User deleted successfully" });
} catch (error) {
res.status(400).json({ Error: error });
}
});
userRouter.get("/submitted-assignments", async (req, res) => {
try {
const users = await User.find({}, 'name assignments.submitted');
const submittedAssignments = users.flatMap(user =>
user.assignments.submitted.map(submission => ({
userName: user.name,
courseName: submission.courseName,
assignmentLink: submission.assignmentLink,
}))
);
res.status(200).json(submittedAssignments);
} catch (error) {
console.error(error);
res.status(500).json({ message: 'Internal server error' });
}
});
userRouter.post("/assignment-result", upload3.single('file'),async (req, res) => {
const { courseName, name, result, date } = req.body;
console.log(name);
try {
const user = await User.findOne({ name });
if (!user) {
return res.status(404).send("User not found");
}
if (result === "approved") {
if (user.assignments.rejected.includes(courseName)) {
user.assignments.rejected = user.assignments.rejected.filter(
course => course !== courseName
);
}
user.assignments.approved.push(courseName);
const certificateLink = await generateCertificate({ courseName, name, date });
user.assignments.submitted = user.assignments.submitted.filter(
assignment => assignment.courseName !== courseName
);
user.certificates.push(certificateLink)
await user.save();
const updatedUser = await User.findOne({ name });
console.log(updatedUser);
res.status(200).json({
message: "Assignment result updated successfully",
user: updatedUser,
certificateLink: certificateLink
});
} else if (result === "rejected") {
if (!user.assignments.rejected.includes(courseName)) {
user.assignments.rejected.push(courseName);
}
user.assignments.submitted = user.assignments.submitted.filter(
assignment => assignment.courseName !== courseName
);
await user.save();
const updatedUser = await User.findOne({ name });
console.log(updatedUser);
res.status(200).json({
message: "Assignment result updated successfully",
user: updatedUser
});
} else {
return res.status(400).send("Invalid result");
}
} catch (error) {
console.error(error);
res.status(500).send("Internal server error");
}
});
module.exports = {userRouter}; |
import { useState, useEffect } from 'react';
import './characterList.scss';
import { Link } from 'react-router-dom';
import { getCharacters, sortingByName } from '../../services/getCharacters';
const CharacterList = () => {
const [search, setSearch] = useState(localStorage.getItem('search') || '');
const [isLoading, setIsLoading] = useState(false);
const [characters, setCharacters] = useState([]);
const [page, setPage] = useState(1);
useEffect(() => {
setIsLoading(true);
getCharacters(page)
.then((data) => {
setCharacters((prevCharacters) => [...prevCharacters, ...data]);
})
.then(() => setIsLoading(false))
.catch((e) => console.log(e.message));
}, [page]);
useEffect(() => {
localStorage.setItem('search', search);
}, [search]);
const filteredCharacters = characters
.filter((character) =>
character.name.toLowerCase().includes(search.toLowerCase())
)
.slice(0, page * 8);
sortingByName(filteredCharacters);
const handleLoadMore = () => {
setPage(page + 1);
};
console.log(filteredCharacters.length);
return (
<>
<div className='input-container'>
<input
type='text'
placeholder='Filter by name...'
className='input'
value={search}
onChange={(e) => {
setSearch(e.target.value);
}}
/>
</div>
{isLoading && <div>Loading...</div>}
{characters && (
<div className='character-list'>
{filteredCharacters.map((character) => (
<div key={character.id} className='character'>
<Link to={`/details/${character.id}`} className='link'>
<div className='character-image'>
<img src={character.image} alt={character.name} />
</div>
<div className='character-details'>
<p className='character-name'>{character.name}</p>
<p className='character-species'>{character.species}</p>
</div>
</Link>
</div>
))}
{filteredCharacters.length <= 32 && (
<div className='load-more-button'>
<button onClick={handleLoadMore}>Load More</button>
</div>
)}
</div>
)}
</>
);
};
export default CharacterList; |
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:light_mart/modules/login/login_screen.dart';
import 'package:light_mart/shared/network/local/cache_helper.dart';
import 'package:smooth_page_indicator/smooth_page_indicator.dart';
class OnBoardingScreen extends StatefulWidget {
@override
State<OnBoardingScreen> createState() => _OnBoardingScreenState();
}
class _OnBoardingScreenState extends State<OnBoardingScreen> {
List<BoardingModel> boarding = [
BoardingModel(
title: 'on board title 1',
body: 'on board body 1',
image: 'assets/images/onboard_1.jpg',
),
BoardingModel(
title: 'on board title 2',
body: 'on board body 2',
image: 'assets/images/onboard_1.jpg',
),
BoardingModel(
title: 'on board title 3',
body: 'on board body 3',
image: 'assets/images/onboard_1.jpg',
),
];
var boardController = PageController();
bool isLast = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: [
TextButton(
onPressed: () {
CacheHelper.saveData('onBoarding', true).then((value) {
if (value) {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (BuildContext context) => LoginScreen()),
(Route<dynamic> route) => false);
}
});
},
child: Text('SKIP'),
)
],
),
body: Padding(
padding: EdgeInsetsDirectional.all(30.0),
child: Column(
children: [
Expanded(
child: PageView.builder(
onPageChanged: (int index) {
if (index == boarding.length - 1) {
setState(() {
isLast = true;
});
} else {
setState(() {
isLast = false;
});
}
},
physics: BouncingScrollPhysics(),
controller: boardController,
itemBuilder: (context, index) =>
buildOnboardingItem(boarding[index]),
itemCount: boarding.length,
),
),
SizedBox(
height: 40.0,
),
Row(
children: [
SmoothPageIndicator(
effect: ExpandingDotsEffect(
dotColor: Colors.grey,
activeDotColor: Colors.deepOrange,
dotHeight: 10,
expansionFactor: 4,
dotWidth: 10,
spacing: 5,
),
count: boarding.length,
controller: boardController,
),
Spacer(),
FloatingActionButton(
onPressed: () {
if (isLast) {
CacheHelper.saveData('onBoarding', true).then((value) {
if (value) {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (BuildContext context) =>
LoginScreen()),
(Route<dynamic> route) => false);
}
});
} else {
boardController.nextPage(
duration: Duration(
milliseconds: 750,
),
curve: Curves.easeInExpo);
}
},
child: Icon(Icons.arrow_forward_ios),
)
],
),
],
),
),
);
}
Widget buildOnboardingItem(BoardingModel boarding) => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Image(
image: AssetImage(boarding.image),
),
),
SizedBox(
height: 30.0,
),
Text(
'${boarding.title}',
style: TextStyle(
fontSize: 24.0,
),
),
SizedBox(
height: 15.0,
),
Text(
'${boarding.body}',
style: TextStyle(
fontSize: 14.0,
),
),
SizedBox(
height: 30.0,
),
],
);
}
class BoardingModel {
final String image;
final String title;
final String body;
BoardingModel({required this.image, required this.title, required this.body});
} |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import React from 'react';
import { screen, fireEvent } from '@testing-library/react';
import { MOCK_ACCOUNT, renderWithRouter } from '../../../models/mocks';
// import { getFtlBundle, testL10n } from 'fxa-react/lib/test-utils';
// import { FluentBundle } from '@fluent/bundle';
import SigninBounced, { viewName } from '.';
import { usePageViewEvent, logViewEvent } from '../../../lib/metrics';
import { REACT_ENTRYPOINT } from '../../../constants';
jest.mock('../../../lib/metrics', () => ({
usePageViewEvent: jest.fn(),
logViewEvent: jest.fn(),
}));
describe('SigninBounced', () => {
// TODO: enable l10n tests when they've been updated to handle embedded tags in ftl strings
// in FXA-6461
// let bundle: FluentBundle;
// beforeAll(async () => {
// bundle = await getFtlBundle('settings');
// });
// Not needed once this page doesn't use `hardNavigateToContentServer`
const originalWindow = window.location;
beforeAll(() => {
// @ts-ignore
delete window.location;
window.location = { ...originalWindow, href: '' };
});
beforeEach(() => {
window.location.href = originalWindow.href;
});
afterAll(() => {
window.location = originalWindow;
});
it('renders default content as expected', () => {
renderWithRouter(<SigninBounced email={MOCK_ACCOUNT.primaryEmail.email} />);
// testAllL10n(screen, bundle, {
// email:MOCK_EMAIL,
// });
screen.getByRole('heading', {
name: 'Sorry. We’ve locked your account.',
});
const supportLink = screen.getByRole('button', {
name: /let us know/,
});
expect(supportLink).toBeInTheDocument();
});
it('renders the "Back" button when a user can go back', () => {
renderWithRouter(
<SigninBounced email={MOCK_ACCOUNT.primaryEmail.email} canGoBack />
);
const backButton = screen.getByRole('button', { name: 'Back' });
expect(backButton).toBeInTheDocument();
});
it('emits the expected metrics on render', async () => {
renderWithRouter(<SigninBounced email={MOCK_ACCOUNT.primaryEmail.email} />);
expect(usePageViewEvent).toHaveBeenCalledWith(viewName, REACT_ENTRYPOINT);
});
it('emits the expected metrics on the "Create Account" action', () => {
renderWithRouter(<SigninBounced email={MOCK_ACCOUNT.primaryEmail.email} />);
fireEvent.click(screen.getByTestId('signin-bounced-create-account-btn'));
expect(logViewEvent).toHaveBeenCalledWith(
viewName,
'link.create-account',
REACT_ENTRYPOINT
);
});
it('pushes the user to the /signin page if there is no email address available', () => {
renderWithRouter(<SigninBounced />);
expect(window.location.href).toBe('/signin');
});
}); |
<!--/
Angie Tracy
Dr. Payne
CSD 440-311A
Server Side Scripting
2023/10/08
Module 11 Programming Assignment
This file creates a PDF to display all of the data stored in the database in a table format.
-->
<?php
// Create connection to database
$serverName = "localhost";
$userName = "student1";
$password = "pass";
$dbName = "baseball_01";
$conn = new mysqli($serverName, $userName, $password, $dbName);
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
// Query the database table
$sql = "SELECT * FROM sbPlayers";
$result = mysqli_query($conn, $sql);
if(!$result){
exit("Error in SQL");
}
//Removing whitespace before generating PDF
ob_end_clean();
require('fpdf/fpdf.php');
class PDF extends FPDF{
//Create page header
function Header(){
//Set Font
$this -> SetFont('Arial', 'B', 18);
//Add logo to left
$this -> Cell(12);
$this -> Image('logo.jpg', 10, 8, 10);
//Set label
$this -> Cell(100, 10, 'Softball Pitchers and Stats', 0, 1);
$this -> Ln(10);
$this -> SetFont('Arial', '', 14);
$this -> Cell(0, 10, 'This table includes a few stats of some of the best college softball pitchers from the last 50 years.', 0, 1, 'C');
$this -> Ln(10);
}
//Create page footer
Function Footer(){
//Add padding at bottom
$this -> SetY(-15);
//Set Font
$this -> SetFont('Arial', '', 8);
$this -> Cell(0, 10, 'Page '. $this->PageNo()." / {pages}", 0, 0, 'C');
}
}
$pdf = new PDF('L', 'mm', 'letter');
//Define page number alias for total page numbers
$pdf -> AliasNbPages('{pages}');
$pdf -> AddPage();
$width_cell = array(35, 35, 35, 35, 25, 25, 35, 35);
$pdf -> SetFont('Arial', 'B', 14);
// Header colors
$pdf -> SetFillColor(0,0,139);
$pdf -> SetTextColor(255, 255, 255);
// Table Header starts
// Best Softball Pitchers Headers
$pdf -> Cell($width_cell[0], 10, "Last Name", 1, 0, 'C', true);
$pdf -> Cell($width_cell[1], 10, "First Name", 1, 0, 'C', true);
$pdf -> Cell($width_cell[2], 10, "School", 1, 0, 'C', true);
$pdf -> Cell($width_cell[3], 10, "Mascot", 1, 0, 'C', true);
$pdf -> Cell($width_cell[4], 10, "Wins", 1, 0, 'C', true);
$pdf -> Cell($width_cell[5], 10, "ERA", 1, 0, 'C', true);
$pdf -> Cell($width_cell[6], 10, "Shut Outs", 1, 0, 'C', true);
$pdf -> Cell($width_cell[7], 10, "Strike Outs", 1, 1, 'C', true);
$pdf -> SetFont('Arial', '', 10);
// Text Color
$pdf -> SetTextColor(0, 0, 0);
// Background color
$pdf -> SetFillColor(193, 229, 252);
// Alternate Row Color
$fill = false;
if(mysqli_num_rows($result)>0) { // if resultSet has data
while($row = mysqli_fetch_assoc($result)){
//Each record of data on pitcher is one row
$pdf -> Cell($width_cell[0], 10, $row['lastName'], 1, 0, 'C', $fill);
$pdf -> Cell($width_cell[1], 10, $row['firstName'], 1, 0, 'C', $fill);
$pdf -> Cell($width_cell[2], 10, $row['school'], 1, 0, 'C', $fill);
$pdf -> Cell($width_cell[3], 10, $row['mascot'], 1, 0, 'C', $fill);
$pdf -> Cell($width_cell[4], 10, $row['wins'], 1, 0, 'C', $fill);
$pdf -> Cell($width_cell[5], 10, $row['era'], 1, 0, 'C', $fill);
$pdf -> Cell($width_cell[6], 10, $row['shutOuts'], 1, 0, 'C', $fill);
$pdf -> Cell($width_cell[7], 10, $row['strikeOuts'], 1, 1, 'C', $fill);
//Alternating rows with color and no color
$fill = !$fill;
}
}
$pdf -> SetFillColor(0, 0, 139);
$pdf -> SetTextColor(255, 255, 255);
$pdf -> Cell(260, 10, 'Stats provided by NCAA.com', 1,0,'C', true);
$pdf -> SetTextColor(0, 0, 0);
mysqli_close($conn);
$pdf -> Output();
ob_end_clean();
?> |
import pytest
import jwt
from datetime import datetime, timedelta
from flask import current_app, g
from random import randint
import app.crud.user as crud
from app import create_app, db
@pytest.fixture()
def app():
app = create_app(test_config=True)
with app.app_context():
db.create_all()
# adding test user
crud.add_user(
db.session,
{ "nick":"test_user",
"email":"test_email@email.com",
"password":"test_password"}
)
# adding test admin
crud.add_user(
db.session,
{ "nick":"admin",
"email":"admin@admin.com",
"password":"test_password"}
)
yield app
db.session.remove()
db.drop_all()
@pytest.fixture()
def client(app):
return app.test_client()
@pytest.fixture()
def headers():
random_uid = str(randint(0,999999))
data = {
"nick": "test_user_" + random_uid,
"email": "test_email_" + random_uid + "@gmail.com",
"password": "test_password"
}
user = crud.add_user(db.session, data)
token = jwt.encode(
{
'user': user.nick,
'exp': datetime.utcnow() + timedelta(minutes=100000000)
},
current_app.config['SECRET_KEY']
)
g.current_user_nick = user.nick
headers = {
'Authorization': f'Bearer {token}'
}
return headers
@pytest.fixture()
def admin_headers():
token = jwt.encode(
{
'user': "admin",
'exp': datetime.utcnow() + timedelta(minutes=100000000)
},
current_app.config['SECRET_KEY']
)
g.current_user_nick = "admin"
headers = {
'Authorization': f'Bearer {token}'
}
return headers |
using basic.common;
using OpenTK.Graphics.OpenGL4;
using OpenTK.Windowing.Common;
using OpenTK.Windowing.Desktop;
using OpenTK.Windowing.GraphicsLibraryFramework;
namespace basic.Rectangle;
public class OpenGlWindowDrawRectangle : GameWindow
{
private readonly float[] _rectangleVertices = [
0.5f, 0.5f, 0.0f, // top right
0.5f, -0.5f, 0.0f, // bottom right
-0.5f, -0.5f, 0.0f, // bottom left
-0.5f, 0.5f, 0.0f // top left
];
// EBO
// note that we start from zero.
private readonly uint[] _rectangleIndices =
{
0, 1, 3, // first triangle
1, 2, 3 // second triangle.
};
private int _vertexBufferObject;
private int _vertexArrayObject;
private int _elementBufferObject;
private Shader _shader;
[Obsolete]
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
public OpenGlWindowDrawRectangle(int width, int height, string title) : base(GameWindowSettings.Default,
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
new NativeWindowSettings() { Size = (width, height), Title = title })
{
}
protected override void OnLoad()
{
base.OnLoad();
// color of the window
GL.ClearColor(0.2f, 0.3f, 0.3f, 1.0f);
//Code goes here
_vertexBufferObject = GL.GenBuffer();
GL.BindBuffer(BufferTarget.ArrayBuffer, _vertexBufferObject);
GL.BufferData(BufferTarget.ArrayBuffer, _rectangleVertices.Length * sizeof(float), _rectangleVertices,
BufferUsageHint.StaticDraw);
_vertexArrayObject = GL.GenVertexArray();
GL.BindVertexArray(_vertexArrayObject);
// shader.GetAttribLocation("aPosition"); // to skip the layout(location=0)
GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 3 * sizeof(float), 0);
GL.EnableVertexAttribArray(0);
_elementBufferObject = GL.GenBuffer();
GL.BindBuffer(BufferTarget.ElementArrayBuffer, _elementBufferObject);
GL.BufferData(BufferTarget.ElementArrayBuffer, _rectangleIndices.Length * sizeof(uint), _rectangleIndices,
BufferUsageHint.StaticDraw);
_shader = new Shader("Rectangle/shaders/shader.vert", "Rectangle/shaders/shader.frag");
_shader.Use();
}
protected override void OnRenderFrame(FrameEventArgs e)
{
base.OnRenderFrame(e);
// clear screen.
GL.Clear(ClearBufferMask.ColorBufferBit);
//Code goes here.
//GL.DrawArrays(PrimitiveType.Triangles, 0, 3);
GL.DrawElements(PrimitiveType.Triangles, _rectangleIndices.Length, DrawElementsType.UnsignedInt, 0);
// double buffer - OpenGL context
SwapBuffers();
}
// It's really simple to detect key presses!
protected override void OnUpdateFrame(FrameEventArgs e)
{
base.OnUpdateFrame(e);
//Get the state of the keyboard this frame
// KeyboardState' is a property of GameWindow
if (KeyboardState.IsKeyDown(Keys.Escape))
{
Close();
}
}
protected override void OnResize(ResizeEventArgs e)
{
base.OnResize(e);
GL.Viewport(0, 0, e.Width, e.Height);
}
protected override void OnUnload()
{
base.OnUnload();
// Unbind all the resources by binding the targets to 0/null.
GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
GL.BindVertexArray(0);
GL.UseProgram(0);
// Delete all the resources.
GL.DeleteBuffer(_vertexBufferObject);
GL.DeleteVertexArray(_vertexArrayObject);
GL.DeleteBuffer(_elementBufferObject);
GL.DeleteProgram(_shader.Handle);
_shader.Dispose();
}
} |
# ruff: noqa: ANN201
from __future__ import annotations
import typing
import unittest
if typing.TYPE_CHECKING:
from hw8.hashmap import CustomHashMap
else:
from hashmap import CustomHashMap
class TestCustomHashMap(unittest.TestCase):
# NOTE: I made each of these methods short enough and with descriptive enough names
# that if i really need a doctring for THESE, u might want to get ur eyes checked
def test_basic_initialization(self):
hashmap: CustomHashMap[typing.Never, typing.Never] = CustomHashMap()
# NOTE: this is the only place where we use the private variables
self.assertEqual(hashmap._capacity, CustomHashMap._INITIAL_SIZE) # type: ignore
self.assertEqual(hashmap._used, 0) # type: ignore
self.assertEqual(hashmap._table, [None] * CustomHashMap._INITIAL_SIZE) # type: ignore # noqa: E501
def test_len_zero_after_initialization(self):
hashmap: CustomHashMap[typing.Never, typing.Never] = CustomHashMap()
self.assertEqual(len(hashmap), 0)
def test_kwarg_init_and_len(self):
hashmap = CustomHashMap(key1="value1", key2="value2", key3="value3")
self.assertEqual(len(hashmap), 3)
def test_kwarg_type_checking(self):
if typing.TYPE_CHECKING:
hashmap_str_str = CustomHashMap(key1="value1")
hashmap_str_str: CustomHashMap[str, str] = hashmap_str_str
def test_value_lookup(self):
hashmap = CustomHashMap(key1="value1", key2="value2", key3="value3")
self.assertEqual(hashmap["key1"], "value1")
self.assertEqual(hashmap["key2"], "value2")
self.assertEqual(hashmap["key3"], "value3")
def test_value_lookup_keyerror(self):
hashmap = CustomHashMap(key1="value1", key2="value2", key3="value3")
with self.assertRaises(KeyError):
hashmap["key4"]
def test_value_assignment(self):
hashmap: CustomHashMap[str, str] = CustomHashMap()
hashmap["key1"] = "value1"
hashmap["key2"] = "value2"
hashmap["key3"] = "value3"
self.assertEqual(hashmap["key1"], "value1")
self.assertEqual(hashmap["key2"], "value2")
self.assertEqual(hashmap["key3"], "value3")
self.assertEqual(len(hashmap), 3)
def test_value_assignment_overwrite(self):
hashmap = CustomHashMap(key1="value1", key2="value2", key3="value3")
hashmap["key1"] = "value4"
hashmap["key2"] = "value5"
hashmap["key3"] = "value6"
self.assertEqual(hashmap["key1"], "value4")
self.assertEqual(hashmap["key2"], "value5")
self.assertEqual(hashmap["key3"], "value6")
self.assertEqual(len(hashmap), 3)
def test_value_deletion(self):
hashmap = CustomHashMap(key1="value1", key2="value2", key3="value3")
del hashmap["key1"]
del hashmap["key2"]
del hashmap["key3"]
self.assertEqual(len(hashmap), 0)
def test_value_deletion_keyerror(self):
hashmap = CustomHashMap(key1="value1", key2="value2", key3="value3")
with self.assertRaises(KeyError):
del hashmap["key4"]
def test_init_with_dict(self):
hashmap = CustomHashMap({
"one": 1,
"two": 2,
"three": 3,
"four": 4,
})
self.assertEqual(hashmap["one"], 1)
self.assertEqual(hashmap["two"], 2)
self.assertEqual(hashmap["three"], 3)
self.assertEqual(hashmap["four"], 4)
def test_init_with_dict_and_kwargs(self):
hashmap = CustomHashMap({
"one": 1,
"two": 2,
"three": 3,
"four": 4,
}, five=5, six=6)
self.assertEqual(hashmap["one"], 1)
self.assertEqual(hashmap["two"], 2)
self.assertEqual(hashmap["three"], 3)
self.assertEqual(hashmap["four"], 4)
self.assertEqual(hashmap["five"], 5)
self.assertEqual(hashmap["six"], 6)
def test_contains(self):
hashmap = CustomHashMap(key1="value1", key2="value2", key3="value3")
self.assertIn("key1", hashmap)
self.assertIn("key2", hashmap)
self.assertIn("key3", hashmap)
self.assertNotIn("key4", hashmap)
def test_contains_edge_cases(self):
hashmap: CustomHashMap[str | None, str | None] = CustomHashMap()
self.assertNotIn("key1", hashmap)
hashmap["key1"] = "value1"
self.assertIn("key1", hashmap)
del hashmap["key1"]
self.assertNotIn("key1", hashmap)
self.assertNotIn(None, hashmap)
hashmap[None] = "value1"
self.assertEqual(hashmap[None], "value1")
self.assertIn(None, hashmap)
del hashmap[None]
self.assertNotIn(None, hashmap)
self.assertNotIn("key1", hashmap)
hashmap["key1"] = None
self.assertIs(hashmap["key1"], None)
self.assertIn("key1", hashmap)
del hashmap["key1"]
self.assertNotIn("key1", hashmap)
# looking at this gives me brain cancer
self.assertNotIn(None, hashmap)
hashmap[None] = None
self.assertIs(hashmap[None], None)
self.assertIn(None, hashmap)
del hashmap[None]
self.assertNotIn(None, hashmap)
def test_contains_with_ellipsis(self):
if typing.TYPE_CHECKING:
from types import EllipsisType
_type = CustomHashMap[
int | None | EllipsisType,
str | None | EllipsisType
]
hashmap: _type = CustomHashMap()
for i in range(3):
hashmap[i] = f"value{i}"
del hashmap[i]
self.assertNotIn(..., hashmap)
hashmap[...] = None
self.assertIs(hashmap[...], None)
self.assertIn(..., hashmap)
del hashmap[...]
self.assertNotIn(..., hashmap)
self.assertNotIn(None, hashmap)
hashmap[None] = ...
self.assertIs(hashmap[None], ...)
self.assertIn(None, hashmap)
del hashmap[None]
self.assertNotIn(None, hashmap)
def test_iter(self):
hashmap = CustomHashMap(key1="value1", key2="value2", key3="value3")
self.assertEqual(set(hashmap), {"key1", "key2", "key3"})
def test_iter_items(self):
hashmap = CustomHashMap(key1="value1", key2="value2", key3="value3")
# use set since order is not guaranteed
self.assertEqual(set(hashmap.items()), {
("key1", "value1"),
("key2", "value2"),
("key3", "value3")
})
if __name__ == "__main__":
unittest.main() |
<template>
<div class="Dialog">
<p>el-Dialog弹出框</p>
<p>:modal-append-to-body='false'(防止被遮罩层遮住)</p>
<el-dropdown trigger="click">
<span class="el-dropdown-link">
下拉查询条件<i class="el-icon-arrow-down el-icon--right"></i>
</span>
<el-dropdown-menu>
<el-form inline="false">
<el-form-item label="输入框">
<el-input v-model='input1'></el-input>
</el-form-item>
<el-form-item label="输入框2">
<el-input v-model='input1'></el-input>
</el-form-item>
</el-form>
</el-dropdown-menu>
<!-- <el-dropdown-menu slot="dropdown">
<el-dropdown-item icon="el-icon-plus">黄金糕</el-dropdown-item>
<el-dropdown-item icon="el-icon-circle-plus">狮子头</el-dropdown-item>
<el-dropdown-item icon="el-icon-circle-plus-outline">螺蛳粉</el-dropdown-item>
<el-dropdown-item icon="el-icon-check">双皮奶</el-dropdown-item>
<el-dropdown-item icon="el-icon-circle-check">蚵仔煎</el-dropdown-item>
</el-dropdown-menu> -->
</el-dropdown>
<el-row :gutter="20">
<el-col :span="12"
><div class="grid-content bg-purple">
<div>
<el-button @click="DiaTable">打开嵌套表格</el-button>
<el-dialog title="打印的几种方式" :visible.sync="Diafirst">
<el-table :data="gridData">
<el-table-column
property="date"
label="日期"
width="150"
></el-table-column>
<el-table-column
property="name"
label="姓名"
width="200"
></el-table-column>
<el-table-column
property="address"
label="打印的方式"
></el-table-column>
</el-table>
</el-dialog>
</div></div
></el-col>
<el-col :span="12"
><div class="grid-content bg-purple">
<div>
<el-button @click="DiaForm">打开嵌套表单</el-button>
<el-dialog title="收货地址" :visible.sync="dialogFormVisible">
<el-form :model="form">
<el-form-item label="活动名称" :label-width="formLabelWidth">
<el-input v-model="form.name" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="活动区域" :label-width="formLabelWidth">
<el-select v-model="form.region" placeholder="请选择活动区域">
<el-option label="区域一" value="shanghai"></el-option>
<el-option label="区域二" value="beijing"></el-option>
</el-select>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible = false">取 消</el-button>
<el-button type="primary" @click="dialogFormVisible = false"
>确 定</el-button
>
</div>
</el-dialog>
</div>
</div></el-col
>
<el-col :span="12">
<el-button type="text" @click="centerDialogVisible = true"
>点击打开 Dialog</el-button
>
<el-dialog title="提示" :visible.sync="centerDialogVisible" width="30%">
<span>需要注意的是内容是默认不居中的</span>
<span slot="footer" class="dialog-footer">
<el-button @click="centerDialogVisible = false">取 消</el-button>
<el-button type="primary" @click="centerDialogVisible = false"
>确 定</el-button
>
</span>
</el-dialog>
</el-col>
<el-col :span="12">
<el-popover
placement="top-start"
title="标题"
width="200"
trigger="hover"
content="这是一段内容,这是一段内容,这是一段内容,这是一段内容。"
>
<el-button slot="reference">hover 激活</el-button>
</el-popover>
<el-popover
placement="bottom"
title="标题"
width="200"
trigger="click"
content="这是一段内容,这是一段内容,这是一段内容,这是一段内容。"
>
<el-button slot="reference">click 激活</el-button>
</el-popover>
</el-col>
<el-col :span="12">
<el-button
type="primary"
@click="drawer = true"
style="margin-left: 16px;"
>中文数字转换为阿拉伯数字</el-button
>
<el-drawer
title="我嵌套了表格!"
:visible.sync="drawer"
direction="ttb"
size="50%"
>
<el-input v-model="inputA" placeholder="数字数字转为文字"></el-input>
</el-drawer>
</el-col>
</el-row>
</div>
</template>
<script>
export default {
name: "Dialog",
components: {},
data() {
return {
input1:'',
Diafirst: false,
drawer: false,
inputA: "",
gridData: [
{
date: "2016-05-02",
name: "王小虎",
address: "console.group"
},
{
date: "2016-05-04",
name: "王小虎",
address: "console.warn"
},
{
date: "2016-05-01",
name: "王小虎",
address: "console.error"
},
{
date: "2016-05-03",
name: "王小虎",
address: "console.info"
}
],
dialogTableVisible: false,
dialogFormVisible: false,
centerDialogVisible: false,
visible: false,
form: {
name: "",
region: "",
date1: "",
date2: "",
delivery: false,
type: [],
resource: "",
desc: ""
},
formLabelWidth: "120px"
};
},
methods: {
datalist() {
switch (this.inputA) {
case "1":
this.inputA = "一";
break;
case "2":
this.inputA = "二";
break;
case "3":
this.inputA = "三";
break;
case "4":
this.inputA = "四";
break;
default:
alert("系统繁忙,请稍后再试");
}
console.log(this.inputA);
},
DiaTable() {
this.Diafirst = true;
//接口地址
},
DiaForm() {
this.dialogFormVisible = true;
}
},
created() {
// console.group("五虎上将");
// console.log("关羽");
// console.error("张飞");
// console.info("赵云");
// console.warn("五子良将");
}
// watch:{
// datalist()
// }
};
</script>
<style>
</style> |
// Copyright (c) 2021 MIT Digital Currency Initiative,
// Federal Reserve Bank of Boston
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "impl.hpp"
#include "crypto/sha256.h"
#include "util/common/keys.hpp"
#include "util/common/variant_overloaded.hpp"
#include <cassert>
#include <secp256k1.h>
#include <secp256k1_schnorrsig.h>
namespace cbdc::parsec::agent::runner {
static const auto secp_context
= std::unique_ptr<secp256k1_context,
decltype(&secp256k1_context_destroy)>(
secp256k1_context_create(SECP256K1_CONTEXT_VERIFY),
&secp256k1_context_destroy);
lua_runner::lua_runner(std::shared_ptr<logging::log> logger,
const cbdc::parsec::config& cfg,
runtime_locking_shard::value_type function,
parameter_type param,
bool is_readonly_run,
run_callback_type result_callback,
try_lock_callback_type try_lock_callback,
std::shared_ptr<secp256k1_context> secp,
std::shared_ptr<thread_pool> t_pool,
ticket_number_type ticket_number)
: interface(std::move(logger),
cfg,
std::move(function),
std::move(param),
is_readonly_run,
std::move(result_callback),
std::move(try_lock_callback),
std::move(secp),
std::move(t_pool),
ticket_number) {}
auto lua_runner::run() -> bool {
// TODO: use custom allocator to limit memory allocation
m_state
= std::shared_ptr<lua_State>(luaL_newstate(), [](lua_State* s) {
lua_close(s);
});
if(!m_state) {
m_log->error("Failed to allocate new lua state");
m_result_callback(error_code::internal_error);
return true;
}
// TODO: provide custom environment limited only to safe library
// methods
luaL_openlibs(m_state.get());
lua_register(m_state.get(), "check_sig", &lua_runner::check_sig);
static constexpr auto function_name = "contract";
auto load_ret = luaL_loadbufferx(m_state.get(),
m_function.c_str(),
m_function.size(),
function_name,
"b");
if(load_ret != LUA_OK) {
m_log->error("Failed to load function chunk");
m_result_callback(error_code::function_load);
return true;
}
if(lua_pushlstring(m_state.get(), m_param.c_str(), m_param.size())
== nullptr) {
m_log->error("Failed to push function params");
m_result_callback(error_code::internal_error);
return true;
}
schedule_contract();
return true;
}
void lua_runner::contract_epilogue(int n_results) {
if(n_results != 1) {
m_log->error("Contract returned more than one result");
m_result_callback(error_code::result_count);
return;
}
if(lua_istable(m_state.get(), -1) != 1) {
m_log->error("Contract did not return a table");
m_result_callback(error_code::result_type);
return;
}
auto results = runtime_locking_shard::state_update_type();
lua_pushnil(m_state.get());
while(lua_next(m_state.get(), -2) != 0) {
auto key_buf = get_stack_string(-2);
if(!key_buf.has_value()) {
m_log->error("Result key is not a string");
m_result_callback(error_code::result_key_type);
return;
}
auto value_buf = get_stack_string(-1);
if(!value_buf.has_value()) {
m_log->error("Result value is not a string");
m_result_callback(error_code::result_value_type);
return;
}
results.emplace(std::move(key_buf.value()),
std::move(value_buf.value()));
lua_pop(m_state.get(), 1);
}
m_log->trace(this, "running calling result callback");
m_result_callback(std::move(results));
m_log->trace(this, "lua_runner finished contract epilogue");
}
auto lua_runner::get_stack_string(int index) -> std::optional<buffer> {
if(lua_isstring(m_state.get(), index) != 1) {
return std::nullopt;
}
size_t sz{};
const auto* str = lua_tolstring(m_state.get(), index, &sz);
assert(str != nullptr);
auto buf = buffer();
buf.append(str, sz);
return buf;
}
void lua_runner::schedule_contract() {
int n_results{};
auto resume_ret = lua_resume(m_state.get(), nullptr, 1, &n_results);
if(resume_ret == LUA_YIELD) {
if(n_results != 1) {
m_log->error("Contract yielded more than one key");
m_result_callback(error_code::yield_count);
return;
}
auto key_buf = get_stack_string(-1);
if(!key_buf.has_value()) {
m_log->error("Contract did not yield a string");
m_result_callback(error_code::yield_type);
return;
}
lua_pop(m_state.get(), n_results);
auto success
= m_try_lock_callback(std::move(key_buf.value()),
broker::lock_type::write,
[&](auto res) {
handle_try_lock(std::move(res));
});
if(!success) {
m_log->error("Failed to issue try lock command");
m_result_callback(error_code::internal_error);
}
} else if(resume_ret != LUA_OK) {
const auto* err = lua_tostring(m_state.get(), -1);
m_log->error("Error running contract:", err);
m_result_callback(error_code::exec_error);
} else {
contract_epilogue(n_results);
}
}
void lua_runner::handle_try_lock(
const broker::interface::try_lock_return_type& res) {
auto maybe_error = std::visit(
overloaded{
[&](const broker::value_type& v) -> std::optional<error_code> {
if(lua_pushlstring(m_state.get(), v.c_str(), v.size())
== nullptr) {
m_log->error("Failed to push yield params");
return error_code::internal_error;
}
return std::nullopt;
},
[&](const broker::interface::error_code& /* e */)
-> std::optional<error_code> {
m_log->error("Broker error acquiring lock");
return error_code::lock_error;
},
[&](const runtime_locking_shard::shard_error& e)
-> std::optional<error_code> {
if(e.m_error_code
== runtime_locking_shard::error_code::wounded) {
return error_code::wounded;
}
m_log->error("Shard error acquiring lock");
return error_code::lock_error;
}},
res);
if(maybe_error.has_value()) {
m_result_callback(maybe_error.value());
return;
}
schedule_contract();
}
auto lua_runner::check_sig(lua_State* L) -> int {
int n = lua_gettop(L);
if(n != 3) {
lua_pushliteral(L, "not enough arguments");
lua_error(L);
}
for(int i = 1; i <= n; i++) {
if(lua_isstring(L, i) != 1) {
lua_pushliteral(L, "invalid argument");
lua_error(L);
}
}
size_t sz{};
const auto* str = lua_tolstring(L, 1, &sz);
assert(str != nullptr);
pubkey_t key{};
if(sz != key.size()) {
lua_pushliteral(L, "invalid pubkey");
lua_error(L);
}
std::memcpy(key.data(), str, sz);
str = lua_tolstring(L, 2, &sz);
assert(str != nullptr);
signature_t sig{};
if(sz != sig.size()) {
lua_pushliteral(L, "invalid signature");
lua_error(L);
}
std::memcpy(sig.data(), str, sz);
secp256k1_xonly_pubkey pubkey{};
if(secp256k1_xonly_pubkey_parse(secp_context.get(),
&pubkey,
key.data())
!= 1) {
lua_pushliteral(L, "invalid pubkey");
lua_error(L);
}
str = lua_tolstring(L, 3, &sz);
assert(str != nullptr);
auto sha = CSHA256();
auto unsigned_str = std::vector<unsigned char>(sz);
std::memcpy(unsigned_str.data(), str, sz);
sha.Write(unsigned_str.data(), sz);
hash_t sighash{};
sha.Finalize(sighash.data());
if(secp256k1_schnorrsig_verify(secp_context.get(),
sig.data(),
sighash.data(),
&pubkey)
!= 1) {
lua_pushliteral(L, "invalid signature");
lua_error(L);
}
return 0;
}
} |
<?php
namespace amos\podcast\models\search;
use amos\podcast\models\PodcastEpisode;
use open20\amos\core\interfaces\CmsModelInterface;
use open20\amos\core\record\CmsField;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use amos\podcast\models\Podcast;
use yii\db\ActiveQuery;
/**
* PodcastSearch represents the model behind the search form about `amos\podcast\models\Podcast`.
*/
class PodcastSearch extends Podcast implements CmsModelInterface
{
//private $container;
public function __construct(array $config = [])
{
$this->isSearch = true;
parent::__construct($config);
}
public function rules()
{
return [
[['id', 'podcast_category_id', 'created_by', 'updated_by', 'deleted_by'], 'integer'],
[['title', 'description', 'image_description', 'created_at', 'updated_at', 'deleted_at'], 'safe'],
['PodcastCategory', 'safe'],
];
}
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* @param $params
* @param null $queryType
* @return ActiveDataProvider
* @throws \yii\base\InvalidConfigException
*/
public function search($params, $queryType = null)
{
$query = Podcast::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
switch ($queryType) {
case 'published':
$query->andWhere(['status' => self::PODCAST_WORKFLOW_STATUS_PUBLISHED]);
break;
case 'to-validate':
$query->andWhere(['status' => self::PODCAST_WORKFLOW_STATUS_REQUESTPUBLICATION]);
break;
case 'to-validate-plus-episodes':
$query->leftJoin('podcast_episode', 'podcast_episode.podcast_id = podcast.id');
$query->andWhere(['OR',
['podcast_episode.status' => PodcastEpisode::PODCASTEP_WORKFLOW_STATUS_REQUESTPUBLICATION],
['podcast.status' => self::PODCAST_WORKFLOW_STATUS_REQUESTPUBLICATION]
]
);
break;
case 'own':
$query->andWhere(['podcast.created_by' => \Yii::$app->user->id]);
break;
case 'admin':
break;
}
$moduleCwh = \Yii::$app->getModule('cwh');
isset($moduleCwh) ? $scope = $moduleCwh->getCwhScope() : null;
if ($scope && $scope['community']) {
$query->andWhere(['podcast.community_id' => $scope['community']]);
}else {
$query->andWhere(['podcast.community_id' => null]);
}
$query->joinWith('podcastCategory');
$dataProvider = $this->setSortPodcast($dataProvider);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
$this->addFilter($query);
return $dataProvider;
}
/**
* @param $dataProvider
* @return mixed
*/
public function setSortPodcast($dataProvider)
{
$dataProvider->setSort([
'attributes' => [
'title' => [
'asc' => ['podcast.title' => SORT_ASC],
'desc' => ['podcast.title' => SORT_DESC],
],
'description' => [
'asc' => ['podcast.description' => SORT_ASC],
'desc' => ['podcast.description' => SORT_DESC],
],
'image_description' => [
'asc' => ['podcast.image_description' => SORT_ASC],
'desc' => ['podcast.image_description' => SORT_DESC],
],
'podcast_category_id' => [
'asc' => ['podcast.podcast_category_id' => SORT_ASC],
'desc' => ['podcast.podcast_category_id' => SORT_DESC],
],
'podcastCategory' => [
'asc' => ['podcast_category.name' => SORT_ASC],
'desc' => ['podcast_category.name' => SORT_DESC],
],]]);
return $dataProvider;
}
/**
* @param $query ActiveQuery
*/
public function addFilter($query)
{
$query->andFilterWhere([
'id' => $this->id,
'podcast_category_id' => $this->podcast_category_id,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'deleted_at' => $this->deleted_at,
'created_by' => $this->created_by,
'updated_by' => $this->updated_by,
'deleted_by' => $this->deleted_by,
]);
$query->andFilterWhere(['like', 'title', $this->title])
->andFilterWhere(['like', 'description', $this->description])
->andFilterWhere(['like', 'image_description', $this->image_description]);
$query->andFilterWhere(['like', new \yii\db\Expression('podcast_category.name'), $this->PodcastCategory]);
}
/**
* @param $params
* @return ActiveDataProvider
* @throws \yii\base\InvalidConfigException
*/
public function searchPublished($params)
{
return $this->search($params, 'published');
}
/**
* @param $params
* @return ActiveDataProvider
* @throws \yii\base\InvalidConfigException
*/
public function searchToValidate($params)
{
return $this->search($params, 'to-validate');
}
/**
* @param $params
* @return ActiveDataProvider
* @throws \yii\base\InvalidConfigException
*/
public function searchToValidatePlusEpisodes($params)
{
return $this->search($params, 'to-validate-plus-episodes');
}
/**
* @param $params
* @return ActiveDataProvider
* @throws \yii\base\InvalidConfigException
*/
public function searchOwn($params)
{
return $this->search($params, 'own');
}
/**
* @param $params
* @return ActiveDataProvider
* @throws \yii\base\InvalidConfigException
*/
public function searchAdmin($params)
{
return $this->search($params, 'admin');
}
/**
* Search method useful to retrieve news to show in frontend (with cms)
*
* @param $params
* @param int|null $limit
* @return ActiveDataProvider
*/
public function cmsSearch($params, $limit = null)
{
$params = array_merge($params, Yii::$app->request->get());
$this->load($params);
$query = $this->searchPublished($params);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'defaultOrder' => [
'published_at' => SORT_DESC,
],
],
]);
if (!empty($params["withPagination"])) {
$dataProvider->setPagination(['pageSize' => $limit]);
$query->limit(null);
} else {
$query->limit($limit);
}
if (!empty($params["conditionSearch"])) {
$commands = explode(";", $params["conditionSearch"]);
foreach ($commands as $command) {
$query->andWhere(eval("return " . $command . ";"));
}
}
return $dataProvider;
}
/**
* Search method useful to retrieve news to show in frontend (with cms)
*
* @param $params
* @param int|null $limit
* @return ActiveDataProvider
*/
public function cmsSearchPodcastEpisodes($params, $limit = null)
{
$params = array_merge($params, Yii::$app->request->get());
$this->load($params);
$query = PodcastEpisode::find()
->andWhere(['status' => PodcastEpisode::PODCASTEP_WORKFLOW_STATUS_PUBLISHED]);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'defaultOrder' => [
'published_at' => SORT_ASC,
],
],
]);
if (!empty($params["withPagination"])) {
$dataProvider->setPagination(['pageSize' => $limit]);
$query->limit(null);
} else {
$query->limit($limit);
}
if (!empty($params["conditionSearch"])) {
$commands = explode(";", $params["conditionSearch"]);
foreach ($commands as $command) {
$query->andWhere(eval("return " . $command . ";"));
}
}
return $dataProvider;
}
/**
*
* @return array
*/
public function cmsViewFields()
{
$viewFields = [];
// array_push($viewFields, new CmsField("titolo", "TEXT", 'amosnews', $this->attributeLabels()["titolo"]));
// array_push($viewFields, new CmsField("descrizione_breve", "TEXT", 'amosnews', $this->attributeLabels()['descrizione_breve']));
// array_push($viewFields, new CmsField("newsImage", "IMAGE", 'amosnews', $this->attributeLabels()['newsImage']));
// array_push($viewFields, new CmsField("data_pubblicazione", "DATE", 'amosnews', $this->attributeLabels()['data_pubblicazione']));
$viewFields[] = new CmsField("title", "TEXT", 'amospodcast', $this->attributeLabels()["title"]);
$viewFields[] = new CmsField("description", "TEXT", 'amospodcast', $this->attributeLabels()["description"]);
$viewFields[] = new CmsField("abstract", "TEXT", 'amospodcast', $this->attributeLabels()['abstract']);
$viewFields[] = new CmsField("mainImage", "IMAGE", 'amospodcast', $this->attributeLabels()['mainImage']);
$viewFields[] = new CmsField("published_at", "DATE", 'amospodcast', $this->attributeLabels()['published_at']);
return $viewFields;
}
/**
*
* @return array
*/
public function cmsSearchFields()
{
$searchFields = [];
// array_push($searchFields, new CmsField("titolo", "TEXT"));
// array_push($searchFields, new CmsField("sottotitolo", "TEXT"));
// array_push($searchFields, new CmsField("descrizione_breve", "TEXT"));
// array_push($searchFields, new CmsField("data_pubblicazione", "DATE"));
$searchFields[] = new CmsField("title", "TEXT");
$searchFields[] = new CmsField("description", "TEXT");
$searchFields[] = new CmsField("abstract", "TEXT");
$searchFields[] = new CmsField("published_at", "DATE");
return $searchFields;
}
/**
*
* @param int $id
* @return boolean
*/
public function cmsIsVisible($id)
{
$retValue = true;
// if (isset($id)) {
// $md = $this->findOne($id);
// if (!is_null($md)) {
// $retValue = $md->primo_piano;
// }
// }
return $retValue;
}
} |
#Preamble
import numpy as np
from scipy.optimize import fsolve, newton
from Fluids_Library import *
#Initial Conditions
#Calculate Shock Pressures
# Driver Helium properties
gamma_4 = 1.667
R_4 = 2077 # J/kg.K
P_4 = 3e6 # 3Mpa
cp_4 = 5192.6 # J/kg.k
T_4 = 300 # K
L_4 = 0.23 # m
U_4i = 0
# Print statements for Driver Helium
print(f"Gamma for Helium (γ₄): {gamma_4} (dimensionless)")
print(f"Specific Gas Constant for Helium (R₄): {R_4} J/kg.K")
print(f"Pressure for Helium (P₄): {P_4/1e6} MPa")
print(f"Specific Heat Capacity at Constant Pressure for Helium (cp₄): {cp_4} J/kg.K")
print(f"Temperature for Helium (T₄): {T_4} K")
print(f"Length for Helium (L₄): {L_4} m")
# Test Gas Air properties
gamma_1 = 1.4
R_1 = 287 # J/kg.K
P_1 = 15e3 # 15kpa
cp_1 = 1005
T_1 = 300 # K
# Print statements for Test Gas Air
print(f"Gamma for Air (γ₁): {gamma_1} (dimensionless)")
print(f"Specific Gas Constant for Air (R₁): {R_1} J/kg.K")
print(f"Pressure for Air (P₁): {P_1/1000} kPa")
print(f"Specific Heat Capacity at Constant Pressure for Air (cp₁): {cp_1} J/kg.K")
print(f"Temperature for Air (T₁): {T_1} K")
gamma_2 = gamma_1
def sound_speed(gamma,R,Temperature):
return np.sqrt(gamma * R * Temperature)
a_1 = sound_speed(gamma_1, R_1, T_1 )
a_4 = sound_speed(gamma_4, R_4, T_4)
P4_P1_known = P_4/P_1 # The given P4/P1 ratio
# Function to solve for P2/P1 using the equation provided
def solve_for_P2_P1(x):
P2_P1 = x[0]
term_inside_brackets = (gamma_4 - 1) * (a_1 / a_4) * (P2_P1 - 1) / np.sqrt(2 * gamma_1 * (2 * gamma_1 + (gamma_1 + 1) * (P2_P1 - 1)))
return [P4_P1_known - P2_P1 * (1 - term_inside_brackets) ** (-2 * gamma_4 / (gamma_4 - 1))]
# Initial guess for P2_P1
P2_P1_initial_guess = [20.0] # This is a guess and may need to be adjusted
# Use fsolve to find the root
P2_P1_solution = fsolve(solve_for_P2_P1, P2_P1_initial_guess)
print(f"The calculated P2/P1 ratio is: {P2_P1_solution[0]:.4f}")
# Rearrange the ratio to find Pressure of State 2 of accelerated test gas
P_2 = P_1 * P2_P1_solution[0]
#Now with this Pressure ratio, find the resulting Mach number.
#Compressible flow calculator says
print("---" * 5)
print("Data from Compressible flow calculator at P2/P1 = 19.896")
# OUTPUTS:
M_s = 4.14696203 # Upstream Mach number
Mb_2 = 0.43120352 # Downstream Mach number
Po2_Po1 = 0.12263917 # Total pressure ratio across the shock
P1_Po2 = 0.04422986 # Pressure ratio of state 1 to total pressure behind shock
rho2_rho1 = 4.64848391 # Density ratio across the shock
T2_T1 = 4.28028654 # Temperature ratio across the shock
print(f"The M_s is {M_s:.3f}")
print(f"The Mb_2 is { Mb_2:.3f}")
print(f"The rho2_rho1 is {rho2_rho1:.4f}")
print(f"The Po2_Po1 is {Po2_Po1:.4f}")
print(f"The T2_T1 is {T2_T1:.4f}")
print(f"The P1_Po2 is {P1_Po2:.4f}")
#The temperature of State 2 T2
T_2 = T_1 * T2_T1
def Ideal_gas_law_P(rho, R, Temperature):
return rho * R * Temperature
def Ideal_gas_law_rho(Pressure,R, Temperature):
return Pressure / (R * Temperature)
#Density initial at 15kpa Air
rho1 = Ideal_gas_law_rho(P_1, R_1, T_1)
#Density initial at 3MPA helium
rho4 = Ideal_gas_law_rho(P_4, R_4, T_4)
# Have mach number and sound speed, now can find velocity
# Remember reference frame issue
def Mach(velocity, sound_speed):
return velocity / sound_speed
def Velocity(Mach, sound_speed):
return Mach * sound_speed
#Shock Mach
def Shock_Mach(sound_speed, gamma, P2, P1):
return sound_speed * np.sqrt ((gamma + 1) / (2 * gamma) * ((P2/P1)-1) + 1 )
U_s = Shock_Mach(a_1,gamma_1, P_2, P_1)
#U2 post shock speed from post shock mach number 0.7? Direct solve
# The velocity behind the shock wave.
def Post_shock_velocity(sound_speed, gamma, P2, P1):
numerator = (2 * gamma) / (gamma + 1)
denominator = (P2 / P1) + ((gamma - 1) / (gamma + 1))
return (sound_speed / gamma) * ((P2 / P1) - 1) * np.sqrt(numerator / denominator)
U_2 = Post_shock_velocity(a_1, gamma_1, P_2, P_1)
a_2 = sound_speed(gamma_1,R_1,T_2)
#Checking with quick reference frame check with post shock mach number from Comp flow calc
U2 = U_s - Mb_2 * a_2
rho2 = Ideal_gas_law_rho(P_2,R_1,T_2)
# Wave Processing Time
#Reference frame for velocity changes.
def stagnation_pressure_ratio(gamma, Mach):
return (1 + ((gamma - 1) / 2) * Mach ** 2) ** (-gamma / (gamma - 1))
def stagnation_temperature_ratio(gamma, Mach):
return (1 + ((gamma - 1) / 2) * Mach**2) ** -1
def Top_ratio(Denominator, Ratio):
return Denominator * Ratio
def Bottom_ratio(Numerator, Ratio):
return Numerator / Ratio
exit_r = (83.9 / 2)/1000
throat_r = (7 / 2 )/ 1000
A_Astar = (np.pi * (exit_r ** 2))/ ((np.pi * (throat_r ** 2)))
print("--State 4--" * 7)
print(f"The sound speed for State 4 a_4 is {a_4:.2f} m/s")
print(f"The rho4 Density of Helium rho4 is {rho4:.5f} kg/m^3")
print("--State 1--" * 7)
print(f"The sound speed for State 1 a_1 is {a_1:.2f} m/s")
print(f"The rho1 Density of Air rho1 is {rho1:.5f} kg/m^3")
print(f"The shock velocity into the State 1 test gas U_s is {U_s:.2f} m/s" )
print("--State 2--" * 7)
print(f"The calculated P2/P1 ratio is: {P2_P1_solution[0]:.4f}")
print(f"The P_2 Pressure is {P_2/1000:.4f} kPa")
print(f"The T_2 Gas Temperature is {T_2:.2f} K")
print(f"The rho2 Density of Air is {rho2:.5f} kg/m^3")
print(f"The velocity behind the shock wave. Checking the reference frame velocity U2 - main way {U2:.2f} m/s")
print(f"The State 2 Post shock The velocity behind the shock wave short cut is U_2 {U_2:.2f} m/s")
print(f"The sound speed for State 2 a_2 is {a_2:.2f} m/s")
print("-- Intermediate Steps --" *3)
#stagnation points
M_s_2 = Mach(U_s, a_1)
print(f"The mach number of the accelerated test gas is {M_s_2:.2f} ")
print("---" * 5)
#Post shock flow properties
#Tutorial 6
print(f"The exit area ratio is {A_Astar:.2f}")
print("Stagnation Regions")
#Stagnation regions
#P_e = design pressure of the nozzle?
# P_e = 280 # Pa off dial/given.
# Now Stagnation Pressure from Ratio
# Area ratio (A_A*): 143.660005
# Mach number (M): 7.52120812
# Mach angle (mu): 7.64052063 degrees
# Prandtl-Meyer angle (nu): 93.5377253 degrees
# Pressure ratio across shock (P_P0): 0.00015262
# Density ratio across shock (rho_rho0): 0.00187943
# Stagnation pressure ratio across shock (P*_P0*): 0.00028891
# Stagnation density ratio across shock (rho*_rho0*): 0.00296469
# Temperature ratio across shock (T_T0): 0.08121026
# Stagnation temperature ratio across shock (T*_T0*): 0.09745231
print("--State 5--" * 7)
P2_P1 = P2_P1_solution
def find_mach_from_pressure_ratio(pressure_ratio, gamma, initial_guess):
"""
Find the upstream Mach number (M1) for a given pressure ratio (p2/p1) in a normal shock.
:param pressure_ratio: The pressure ratio across the shock (p2/p1).
:param gamma: Specific heat ratio (γ), for air it is typically 1.4.
:param initial_guess: Initial guess for the Mach number.
:return: The upstream Mach number (M1).
"""
def f(M1):
# Implicit equation for the upstream Mach number based on pressure ratio
return 1 + (2 * gamma / (gamma + 1)) * (M1 ** 2 - 1) - pressure_ratio
# Use the Newton-Raphson method to solve for M1
M1 = newton(f, initial_guess)
return M1
M_1_from_P2_P1 = find_mach_from_pressure_ratio(P2_P1, gamma_1, 4)
print(f" The mach number at this pressure ratio is {M_1_from_P2_P1}")
M_2 = U_2 / a_2
print(f"The Mach number 2 is {M_2:.2f}")
M_r = Mach_reflected(M_2, gamma_1)
print(f"The reflected shock mach number M_r is {M_r:.3f}")
T5_T2_Mach = T5_T2wopress(gamma_2, M_r)
print(f"The T5_T2 ratio is {T5_T2_Mach:.4f}")
T_5 = Top_ratio(T5_T2_Mach, T_2)
print(f"The T5 stagnation temperature is {T_5:.2f} K")
T5_T1 = T5_T1(T_5, T_1)
print(f"To Check the theoretical T5_T1 for the graph is {T5_T1:.2f}")
P5_P2 = shock_P2_P1(M_r, gamma_1)
print(f"FTP5_P1 ratio using ideal reflected is {P5_P2:.2f}")
P_5 = Top_ratio(P5_P2, P_2)
print(f"Theroretical P5 stagnation is {P_5 /1000:.2f} kPa")
P5_P1 = P_5 / P_1
print(f"To check the P5_P1 chart {P5_P1:.2f}")
# EQN Analytical
U_3 = U_2 #
a_3 = speed_sound3(U_4i, U_3, gamma_4, a_4)
print(f"Sound speed a_3 is {a_3:.2f}")
def EQN(U_2, a_3, gamma_4, P5_P2):
gamma = gamma_4 + 1
gamma_ = gamma_4 - 1
numer = ((gamma/gamma_) - 1) * (P5_P2 - 1)
denom = (1 + (gamma / gamma_)) * (1 + ( gamma / gamma_) * P5_P2)
return U_2 - a_3 * numer / np.sqrt(denom)
Tailoring15kpa = EQN(U_2, a_3, gamma_4, P5_P2)
print(f"The EQN of the system is {Tailoring15kpa:.2f}") |
/**
* These codes are licensed under the Unlicense.
* http://unlicense.org
*/
#ifndef COMMATA_GUARD_0DE728A7_BABE_4C3A_94B1_A05CB3D0C9E4
#define COMMATA_GUARD_0DE728A7_BABE_4C3A_94B1_A05CB3D0C9E4
#include <algorithm>
#include <cassert>
#include <cctype>
#include <cerrno>
#include <clocale>
#include <cstdint>
#include <cstdlib>
#include <cwchar>
#include <cwctype>
#include <iterator>
#include <locale>
#include <memory>
#include <optional>
#include <string_view>
#include <type_traits>
#include "field_handling.hpp"
#include "text_error.hpp"
#include "detail/member_like_base.hpp"
#include "detail/typing_aid.hpp"
#include "detail/write_ntmbs.hpp"
namespace commata {
class text_value_translation_error : public text_error
{
public:
using text_error::text_error;
};
class text_value_invalid_format : public text_value_translation_error
{
public:
using text_value_translation_error::text_value_translation_error;
};
class text_value_empty : public text_value_invalid_format
{
public:
using text_value_invalid_format::text_value_invalid_format;
};
class text_value_out_of_range : public text_value_translation_error
{
public:
using text_value_translation_error::text_value_translation_error;
};
struct invalid_format_t {};
struct out_of_range_t {};
struct empty_t {};
namespace detail::xlate {
template <class T>
struct numeric_type_traits;
template <>
struct numeric_type_traits<char>
{
static constexpr std::string_view name = "char";
using raw_type =
std::conditional_t<std::is_signed_v<char>, long, unsigned long>;
};
template <>
struct numeric_type_traits<signed char>
{
static constexpr std::string_view name = "signed char";
using raw_type = long;
};
template <>
struct numeric_type_traits<unsigned char>
{
static constexpr std::string_view name = "unsigned char";
using raw_type = unsigned long;
};
template <>
struct numeric_type_traits<short>
{
static constexpr std::string_view name = "short int";
using raw_type = long;
};
template <>
struct numeric_type_traits<unsigned short>
{
static constexpr std::string_view name = "unsigned short int";
using raw_type = unsigned long;
};
template <>
struct numeric_type_traits<int>
{
static constexpr std::string_view name = "int";
using raw_type = long;
};
template <>
struct numeric_type_traits<unsigned>
{
static constexpr std::string_view name = "unsigned int";
using raw_type = unsigned long;
};
template <>
struct numeric_type_traits<long>
{
static constexpr std::string_view name = "long int";
static constexpr const auto strto = std::strtol;
static constexpr const auto wcsto = std::wcstol;
};
template <>
struct numeric_type_traits<unsigned long>
{
static constexpr std::string_view name = "unsigned long int";
static constexpr const auto strto = std::strtoul;
static constexpr const auto wcsto = std::wcstoul;
};
template <>
struct numeric_type_traits<long long>
{
static constexpr std::string_view name = "long long int";
static constexpr const auto strto = std::strtoll;
static constexpr const auto wcsto = std::wcstoll;
};
template <>
struct numeric_type_traits<unsigned long long>
{
static constexpr std::string_view name = "unsigned long long int";
static constexpr const auto strto = std::strtoull;
static constexpr const auto wcsto = std::wcstoull;
};
template <>
struct numeric_type_traits<float>
{
static constexpr std::string_view name = "float";
static constexpr const auto strto = std::strtof;
static constexpr const auto wcsto = std::wcstof;
};
template <>
struct numeric_type_traits<double>
{
static constexpr std::string_view name = "double";
static constexpr const auto strto = std::strtod;
static constexpr const auto wcsto = std::wcstod;
};
template <>
struct numeric_type_traits<long double>
{
static constexpr std::string_view name = "long double";
static constexpr const auto strto = std::strtold;
static constexpr const auto wcsto = std::wcstold;
};
template <class T, class H>
class error_handler
{
using handler_t = std::conditional_t<
detail::is_std_reference_wrapper_v<std::decay_t<H>>,
std::decay_t<H>,
std::reference_wrapper<std::remove_reference_t<H>>>;
handler_t handler_;
public:
template <class Ch>
static constexpr bool is_direct =
std::is_invocable_r_v<T, error_handler&, invalid_format_t,
const Ch*, const Ch*>
&& std::is_invocable_r_v<T, error_handler&, out_of_range_t,
const Ch*, const Ch*, int>
&& std::is_invocable_r_v<T, error_handler&, empty_t>;
explicit error_handler(H& handler) :
handler_(handler)
{}
template <class Ch>
auto operator()(invalid_format_t, const Ch* begin, const Ch* end)
{
return invoke_with_range_typing_as<T>(
as_forwarded(), invalid_format_t(), begin, end);
}
template <class Ch>
auto operator()(out_of_range_t, const Ch* begin, const Ch* end, int sign)
{
return invoke_with_range_typing_as<T>(
as_forwarded(), out_of_range_t(), begin, end, sign);
}
auto operator()(empty_t)
{
return invoke_typing_as<T>(as_forwarded(), empty_t());
}
private:
H&& as_forwarded()
{
return std::forward<H>(as_lvalue());
}
H& as_lvalue()
{
// We wouldn't think there are many points on perfect forwarding
// reference wrappers as is, but we would like to go ahead with this
// to keep the spec simple
if constexpr (detail::is_std_reference_wrapper_v<std::decay_t<H>>) {
return handler_;
} else {
return handler_.get();
}
}
};
template <class T>
struct raw_converter
{
template <class Ch, class U, class H>
auto operator()(
const Ch* begin, const Ch* end, error_handler<U, H> h) const
-> std::conditional_t<
error_handler<U, H>::template is_direct<Ch>, T, std::optional<T>>
{
// For examble, when T is long, it is possible that U is int
static_assert(std::is_convertible_v<U, T>);
Ch* middle;
errno = 0;
const T r = engine(begin, &middle);
const auto has_postfix =
std::any_of<const Ch*>(middle, end, [](Ch c) {
return !is_space(c);
});
if (has_postfix) {
// if a not-whitespace-extra-character found, it is NG
return h(invalid_format_t(), begin, end);
} else if (begin == middle) {
// whitespace only
return h(empty_t());
} else if (errno == ERANGE) {
return h(out_of_range_t(), begin, end, erange(r));
} else {
return r;
}
}
private:
static T engine(const char* s, char** e)
{
if constexpr (std::is_floating_point_v<T>) {
return numeric_type_traits<T>::strto(s, e);
} else {
return numeric_type_traits<T>::strto(s, e, 10);
}
}
static T engine(const wchar_t* s, wchar_t** e)
{
if constexpr (std::is_floating_point_v<T>) {
return numeric_type_traits<T>::wcsto(s, e);
} else {
return numeric_type_traits<T>::wcsto(s, e, 10);
}
}
static int erange([[maybe_unused]] T v)
{
if constexpr (std::is_floating_point_v<T>) {
return (v > T()) ? 1 : (v < T()) ? -1 : 0;
} else if constexpr (std::is_signed_v<T>) {
return (v > T()) ? 1 : -1;
} else {
return 1;
}
}
// To mimic space skipping by std::strtol and its comrades,
// we have to refer current C locale
static bool is_space(char c)
{
return std::isspace(static_cast<unsigned char>(c)) != 0;
}
// ditto
static bool is_space(wchar_t c)
{
return std::iswspace(c) != 0;
}
};
template <class T, class U>
struct restrained_converter
{
template <class Ch, class H>
auto operator()(
const Ch* begin, const Ch* end, error_handler<T, H> h) const
-> std::conditional_t<
error_handler<U, H>::template is_direct<Ch>, T, std::optional<T>>
{
const auto r = raw_converter<U>()(begin, end, h);
if constexpr (error_handler<U, H>::template is_direct<Ch>) {
return restrain(r, begin, end, h);
} else if (!r.has_value()) {
return std::nullopt;
} else {
return restrain(r.value(), begin, end, h);
}
}
private:
template <class Ch, class H>
static auto restrain(U r, const Ch* begin, const Ch* end, H h)
-> std::conditional_t<
error_handler<U, H>::template is_direct<Ch>, T, std::optional<T>>
{
if constexpr (std::is_unsigned_v<T>) {
if constexpr (sizeof(T) < sizeof(U)) {
constexpr T t_max = std::numeric_limits<T>::max();
if (r > t_max) {
const auto s = static_cast<std::make_signed_t<U>>(r);
if (s < 0) {
// -t_max is the lowest number that can be wrapped
// around and then returned
const auto s_wrapped_around = s + t_max + 1;
if (s_wrapped_around > 0) {
return static_cast<T>(s_wrapped_around);
}
}
return h(out_of_range_t(), begin, end, 1);
}
}
} else {
if (r < std::numeric_limits<T>::lowest()) {
return h(out_of_range_t(), begin, end, -1);
} else if (std::numeric_limits<T>::max() < r) {
return h(out_of_range_t(), begin, end, 1);
}
}
return static_cast<T>(r);
}
};
// For types without corresponding "raw_type"
template <class T, class = void>
struct converter :
raw_converter<T>
{};
// For types which have corresponding "raw_type"
template <class T>
struct converter<T, std::void_t<typename numeric_type_traits<T>::raw_type>> :
restrained_converter<T, typename numeric_type_traits<T>::raw_type>
{};
} // end detail::xlate
struct fail_if_conversion_failed
{
explicit fail_if_conversion_failed(replacement_fail_t = replacement_fail)
{}
template <class T, class Ch>
[[noreturn]]
T operator()(invalid_format_t,
const Ch* begin, const Ch* end, T* = nullptr) const
try {
using namespace std::string_view_literals;
assert(*end == Ch());
std::stringbuf s;
if constexpr (
std::is_same_v<Ch, char> || std::is_same_v<Ch, wchar_t>) {
detail::write_ntmbs(&s, std::locale(), begin, end);
sputn(s, ": cannot convert"sv);
} else {
sputn(s, "Cannot convert"sv);
}
write_name<T>(s, " to an instance of "sv);
throw text_value_invalid_format(std::move(s).str());
} catch (const text_value_invalid_format&) {
throw;
} catch (...) {
std::throw_with_nested(text_value_invalid_format());
}
template <class T, class Ch>
[[noreturn]]
T operator()(out_of_range_t,
const Ch* begin, const Ch* end, int, T* = nullptr) const
try {
using namespace std::string_view_literals;
assert(*end == Ch());
std::stringbuf s;
if constexpr (
std::is_same_v<Ch, char> || std::is_same_v<Ch, wchar_t>) {
detail::write_ntmbs(&s, std::locale(), begin, end);
sputn(s, ": out of range"sv);
} else {
sputn(s, "Out of range"sv);
}
write_name<T>(s, " of "sv);
throw text_value_out_of_range(std::move(s).str());
} catch (const text_value_out_of_range&) {
throw;
} catch (...) {
std::throw_with_nested(text_value_invalid_format());
}
template <class T>
[[noreturn]]
T operator()(empty_t, T* = nullptr) const
try {
using namespace std::string_view_literals;
std::stringbuf s;
sputn(s, "Cannot convert an empty string"sv);
write_name<T>(s, " to an instance of "sv);
throw text_value_empty(std::move(s).str());
} catch (const text_value_empty&) {
throw;
} catch (...) {
std::throw_with_nested(text_value_empty());
}
private:
template <class T>
static void write_name(std::streambuf& sb, std::string_view prefix,
decltype(detail::xlate::numeric_type_traits<std::remove_cv_t<T>>
::name)* = nullptr)
{
using namespace detail::xlate;
sputn(sb, prefix);
sputn(sb, detail::xlate::numeric_type_traits<std::remove_cv_t<T>>
::name);
}
template <class T, class... Args>
static void write_name(std::streambuf&, Args&&...)
{}
template <class Ch, class Tr, class Tr2>
static void sputn(std::basic_streambuf<Ch, Tr>& sb,
std::basic_string_view<Ch, Tr2> s)
{
using max_t = std::common_type_t<
std::make_unsigned_t<std::streamsize>,
typename std::basic_string_view<Ch, Tr2>::size_type>;
constexpr max_t max =
static_cast<max_t>(std::numeric_limits<std::streamsize>::max());
while (s.size() > max) {
sb.sputn(s.data(), static_cast<std::streamsize>(max));
s.remove_prefix(static_cast<std::size_t>(max));
}
sb.sputn(s.data(), s.size());
}
};
struct ignore_if_conversion_failed
{
explicit ignore_if_conversion_failed(
replacement_ignore_t = replacement_ignore)
{}
std::nullopt_t operator()(invalid_format_t) const
{
return std::nullopt;
}
std::nullopt_t operator()(out_of_range_t) const
{
return std::nullopt;
}
std::nullopt_t operator()(empty_t) const
{
return std::nullopt;
}
};
namespace detail::xlate::replace_if_conversion_failed_impl {
enum slot : unsigned {
slot_empty = 0,
slot_invalid_format = 1,
slot_above_upper_limit = 2,
slot_below_lower_limit = 3,
slot_underflow = 4
};
struct copy_mode_t {};
template <class T, unsigned N>
struct trivial_store
{
private:
alignas(T) char replacements_[N][sizeof(T)] = {};
std::uint_fast8_t has_ = 0U;
std::uint_fast8_t skips_ =0U;
protected:
trivial_store(copy_mode_t, const trivial_store& other) noexcept :
has_(other.has_), skips_(other.skips_)
{}
public:
using value_type = T;
static constexpr unsigned size = N;
template <class Head, class... Tails>
trivial_store(generic_args_t, Head&& head, Tails&&... tails) :
trivial_store(std::integral_constant<std::size_t, 0>(),
std::forward<Head>(head), std::forward<Tails>(tails)...)
{}
private:
template <std::size_t Slot, class Head, class... Tails>
trivial_store(std::integral_constant<std::size_t, Slot>,
Head&& head, Tails&&... tails) :
trivial_store(std::integral_constant<std::size_t, Slot + 1>(),
std::forward<Tails>(tails)...)
{
init<Slot>(std::forward<Head>(head));
}
trivial_store(std::integral_constant<std::size_t, N>) noexcept :
has_(0), skips_(0)
{}
template <unsigned Slot, class U, std::enable_if_t<
(!std::is_base_of_v<replacement_fail_t, std::decay_t<U>>)
&& (!std::is_base_of_v<replacement_ignore_t, std::decay_t<U>>)>*
= nullptr>
void init(U&& value)
noexcept(std::is_nothrow_constructible_v<T, U&&>)
{
static_assert(Slot < N);
assert(!has(Slot));
assert(!skips(Slot));
emplace(Slot, std::forward<U>(value));
set_has(Slot);
}
template <unsigned Slot>
void init() noexcept(std::is_nothrow_default_constructible_v<T>)
{
static_assert(Slot < N);
assert(!has(Slot));
assert(!skips(Slot));
emplace(Slot);
set_has(Slot);
}
template <unsigned Slot>
void init(replacement_fail_t) noexcept
{
static_assert(Slot < N);
assert(!has(Slot));
assert(!skips(Slot));
}
template <unsigned Slot>
void init(replacement_ignore_t) noexcept
{
static_assert(Slot < N);
assert(!has(Slot));
assert(!skips(Slot));
set_skips(Slot);
}
public:
std::pair<replace_mode, const T*> get(unsigned r) const noexcept
{
return get_g(this, r);
}
private:
template <class ThisType>
static auto get_g(ThisType* me, unsigned r) noexcept
{
using t_t = std::conditional_t<std::is_const_v<ThisType>, const T, T>;
using pair_t = std::pair<replace_mode, t_t*>;
if (me->has(r)) {
return pair_t(replace_mode::replace, std::addressof((*me)[r]));
} else if (me->skips(r)) {
return pair_t(replace_mode::ignore, nullptr);
} else {
return pair_t(replace_mode::fail, nullptr);
}
}
protected:
T& operator[](unsigned r)
{
return *static_cast<T*>(static_cast<void*>(replacements_[r]));
}
const T& operator[](unsigned r) const
{
return *static_cast<const T*>(
static_cast<const void*>(replacements_[r]));
}
template <class... Args>
void emplace(unsigned r, Args&&... args)
noexcept(std::is_nothrow_constructible_v<T, Args&&...>)
{
::new(replacements_[r]) T(std::forward<Args>(args)...);
}
bool has(unsigned r) const noexcept
{
return (has_ & (1 << r)) != 0;
}
void set_has(unsigned r) noexcept
{
has_ |= (1 << r);
}
void set_has(unsigned r, bool v) noexcept
{
if (v) {
set_has(r);
} else {
has_ &= ~(1 << r);
}
}
bool skips(unsigned r) const noexcept
{
return (skips_ & (1 << r)) != 0;
}
void set_skips(unsigned r) noexcept
{
skips_ |= (1 << r);
}
void set_skips(unsigned r, bool v) noexcept
{
if (v) {
set_skips(r);
} else {
skips_ &= ~(1 << r);
}
}
};
template <class T, unsigned N>
struct nontrivial_store : trivial_store<T, N>
{
using trivial_store<T, N>::trivial_store;
nontrivial_store(const nontrivial_store& other)
noexcept(std::is_nothrow_copy_constructible_v<T>) :
trivial_store<T, N>(copy_mode_t(), other)
{
for (unsigned r = 0; r < N; ++r) {
if (this->has(r)) {
this->emplace(r, other[r]);
}
}
}
nontrivial_store(nontrivial_store&& other)
noexcept(std::is_nothrow_move_constructible_v<T>) :
trivial_store<T, N>(copy_mode_t(), other)
{
for (unsigned r = 0; r < N; ++r) {
if (this->has(r)) {
this->emplace(r, std::move(other[r]));
}
}
}
~nontrivial_store()
{
for (unsigned r = 0; r < N; ++r) {
if (this->has(r)) {
(*this)[r].~T();
}
}
}
nontrivial_store& operator=(const nontrivial_store& other)
noexcept(std::is_nothrow_copy_constructible_v<T>
&& std::is_nothrow_copy_assignable_v<T>)
{
assign(other);
return *this;
}
nontrivial_store& operator=(nontrivial_store&& other)
noexcept(std::is_nothrow_move_constructible_v<T>
&& std::is_nothrow_move_assignable_v<T>)
{
assign(std::move(other));
return *this;
}
private:
template <class Other>
void assign(Other&& other)
{
if (this == std::addressof(other)) {
return; // see comments in replace_if_skipped
}
using f_t = std::conditional_t<
std::is_lvalue_reference_v<Other>, const T&, T>;
for (unsigned r = 0; r < N; ++r) {
if (this->has(r)) {
if (other.has(r)) {
(*this)[r] = std::forward<f_t>(other[r]);
continue;
} else {
(*this)[r].~T();
}
} else if (other.has(r)) {
this->emplace(r, std::forward<f_t>(other[r]));
}
this->set_has(r, other.has(r));
this->set_skips(r, other.skips(r));
}
}
public:
void swap(nontrivial_store& other)
noexcept(std::is_nothrow_swappable_v<T>
&& std::is_nothrow_constructible_v<T>)
{
for (unsigned r = 0; r < N; ++r) {
if (this->has(r)) {
if (other.has(r)) {
using std::swap;
swap((*this)[r], other[r]);
continue;
} else {
other.emplace(r, std::move((*this)[r]));
(*this)[r].~T();
}
} else if (other.has(r)) {
this->emplace(r, std::move(other[r]));
other[r].~T();
}
{
const bool t = this->has(r);
this->set_has(r, other.has(r));
other.set_has(r, t);
}
{
const bool t = this->skips(r);
this->set_skips(r, other.skips(r));
other.set_skips(r, t);
}
}
}
};
template <class T, unsigned N>
void swap(nontrivial_store<T, N>& left, nontrivial_store<T, N>& right)
noexcept(noexcept(left.swap(right)))
{
left.swap(right);
}
template <class T, class A>
constexpr bool is_acceptable_arg_v =
std::is_base_of_v<replacement_fail_t, std::decay_t<A>>
|| std::is_base_of_v<replacement_ignore_t, std::decay_t<A>>
|| std::is_constructible_v<T, A>;
template <class T, class A>
constexpr bool is_nothrow_arg_v =
std::is_base_of_v<replacement_fail_t, std::decay_t<A>>
|| std::is_base_of_v<replacement_ignore_t, std::decay_t<A>>
|| std::is_nothrow_constructible_v<T, A>;
template <class T, unsigned N>
struct base_base
{
protected:
using store_t = std::conditional_t<std::is_trivially_copyable_v<T>,
trivial_store<T, N>, nontrivial_store<T, N>>;
private:
store_t store_;
protected:
template <class... As>
base_base(generic_args_t, As&&... as) :
store_(generic_args_t(), std::forward<As>(as)...)
{
static_assert(sizeof...(As) == N);
}
const store_t& store() const
{
return store_;
}
store_t& store()
{
return store_;
}
};
template <class T, unsigned N>
struct base;
template <class T>
struct base<T, 3> : base_base<T, 3>
{
template <class All = T,
std::enable_if_t<is_acceptable_arg_v<T, const All&>>* = nullptr>
explicit base(const All& for_all = All()) :
base(for_all, for_all, for_all)
{}
template <class Empty, class AllButEmpty,
std::enable_if_t<
is_acceptable_arg_v<T, Empty&&>
&& is_acceptable_arg_v<T, const AllButEmpty&>>* = nullptr>
base(Empty&& on_empty, const AllButEmpty& for_all_but_empty) :
base(std::forward<Empty>(on_empty),
for_all_but_empty, for_all_but_empty)
{}
template <class Empty, class InvalidFormat, class AboveUpperLimit,
std::enable_if_t<
is_acceptable_arg_v<T, Empty&&>
&& is_acceptable_arg_v<T, InvalidFormat&&>
&& is_acceptable_arg_v<T, AboveUpperLimit&&>>* = nullptr>
explicit base(
Empty&& on_empty,
InvalidFormat&& on_invalid_format,
AboveUpperLimit&& on_above_upper_limit)
noexcept(std::is_nothrow_default_constructible_v<T>
&& is_nothrow_arg_v<T, Empty>
&& is_nothrow_arg_v<T, InvalidFormat>
&& is_nothrow_arg_v<T, AboveUpperLimit>) :
base_base<T, 3>(
generic_args_t(),
std::forward<Empty>(on_empty),
std::forward<InvalidFormat>(on_invalid_format),
std::forward<AboveUpperLimit>(on_above_upper_limit))
{}
};
template <class T>
struct base<T, 4> : base_base<T, 4>
{
template <class All = T,
std::enable_if_t<is_acceptable_arg_v<T, const All&>>* = nullptr>
explicit base(const All& for_all = All()) :
base(for_all, for_all, for_all, for_all)
{}
template <class Empty, class AllButEmpty,
std::enable_if_t<
is_acceptable_arg_v<T, Empty&&>
&& is_acceptable_arg_v<T, const AllButEmpty&>>* = nullptr>
explicit base(Empty&& on_empty, const AllButEmpty& for_all_but_empty) :
base(std::forward<Empty>(on_empty),
for_all_but_empty, for_all_but_empty, for_all_but_empty)
{}
template <class Empty, class InvalidFormat, class AllOutOfRange,
std::enable_if_t<
is_acceptable_arg_v<T, Empty&&>
&& is_acceptable_arg_v<T, InvalidFormat&&>
&& is_acceptable_arg_v<T, const AllOutOfRange&>>* = nullptr>
base(Empty&& on_empty, InvalidFormat&& on_invalid_format,
const AllOutOfRange& for_all_out_of_range) :
base(std::forward<Empty>(on_empty),
std::forward<InvalidFormat>(on_invalid_format),
for_all_out_of_range, for_all_out_of_range)
{}
template <class Empty, class InvalidFormat,
class AboveUpperLimit, class BelowLowerLimit,
std::enable_if_t<
is_acceptable_arg_v<T, Empty&&>
&& is_acceptable_arg_v<T, InvalidFormat&&>
&& is_acceptable_arg_v<T, AboveUpperLimit&&>
&& is_acceptable_arg_v<T, BelowLowerLimit&&>>* = nullptr>
base(
Empty&& on_empty,
InvalidFormat&& on_invalid_format,
AboveUpperLimit&& on_above_upper_limit,
BelowLowerLimit&& on_below_lower_limit)
noexcept(std::is_nothrow_default_constructible_v<T>
&& is_nothrow_arg_v<T, Empty&&>
&& is_nothrow_arg_v<T, InvalidFormat&&>
&& is_nothrow_arg_v<T, AboveUpperLimit&&>
&& is_nothrow_arg_v<T, BelowLowerLimit&&>) :
base_base<T, 4>(
generic_args_t(),
std::forward<Empty>(on_empty),
std::forward<InvalidFormat>(on_invalid_format),
std::forward<AboveUpperLimit>(on_above_upper_limit),
std::forward<BelowLowerLimit>(on_below_lower_limit))
{}
};
template <class T>
struct base<T, 5> : base_base<T, 5>
{
template <class All = T,
std::enable_if_t<is_acceptable_arg_v<T, const All&>>* = nullptr>
explicit base(const All& for_all = All()) :
base(for_all, for_all, for_all, for_all, for_all)
{}
template <class Empty, class AllButEmpty,
std::enable_if_t<
is_acceptable_arg_v<T, Empty&&>
&& is_acceptable_arg_v<T, const AllButEmpty&>>* = nullptr>
explicit base(Empty&& on_empty, const AllButEmpty& for_all_but_empty) :
base(std::forward<Empty>(on_empty), for_all_but_empty,
for_all_but_empty, for_all_but_empty, for_all_but_empty)
{}
template <class Empty, class InvalidFormat, class AllOutOfRange,
std::enable_if_t<
is_acceptable_arg_v<T, Empty&&>
&& is_acceptable_arg_v<T, InvalidFormat&&>
&& is_acceptable_arg_v<T, const AllOutOfRange&>>* = nullptr>
base(Empty&& on_empty, InvalidFormat&& on_invalid_format,
const AllOutOfRange& for_all_out_of_range) :
base(std::forward<Empty>(on_empty),
std::forward<InvalidFormat>(on_invalid_format),
for_all_out_of_range, for_all_out_of_range, for_all_out_of_range)
{}
template <class Empty, class InvalidFormat,
class AboveUpperLimit, class BelowLowerLimit,
class Underflow,
std::enable_if_t<
is_acceptable_arg_v<T, Empty>
&& is_acceptable_arg_v<T, InvalidFormat>
&& is_acceptable_arg_v<T, AboveUpperLimit>
&& is_acceptable_arg_v<T, BelowLowerLimit>
&& is_acceptable_arg_v<T, Underflow>>* = nullptr>
base(
Empty&& on_empty,
InvalidFormat&& on_invalid_format,
AboveUpperLimit&& on_above_upper_limit,
BelowLowerLimit&& on_below_lower_limit,
Underflow&& on_underflow)
noexcept(is_nothrow_arg_v<T, Empty>
&& is_nothrow_arg_v<T, InvalidFormat>
&& is_nothrow_arg_v<T, AboveUpperLimit>
&& is_nothrow_arg_v<T, BelowLowerLimit>
&& is_nothrow_arg_v<T, Underflow>) :
base_base<T, 5>(
generic_args_t(),
std::forward<Empty>(on_empty),
std::forward<InvalidFormat>(on_invalid_format),
std::forward<AboveUpperLimit>(on_above_upper_limit),
std::forward<BelowLowerLimit>(on_below_lower_limit),
std::forward<Underflow>(on_underflow))
{}
};
template <class T>
constexpr unsigned base_n =
std::is_integral_v<T> ? std::is_signed_v<T> ? 4 : 3 : 5;
template <class T>
using base_t = base<T, base_n<T>>;
} // detail::xlate::replace_if_conversion_failed_impl
template <class T>
class replace_if_conversion_failed :
public detail::xlate::replace_if_conversion_failed_impl::base_t<T>
{
using replace_mode = detail::replace_mode;
static constexpr unsigned slot_empty =
detail::xlate::replace_if_conversion_failed_impl::slot_empty;
static constexpr unsigned slot_invalid_format =
detail::xlate::replace_if_conversion_failed_impl::
slot_invalid_format;
static constexpr unsigned slot_above_upper_limit =
detail::xlate::replace_if_conversion_failed_impl::
slot_above_upper_limit;
static constexpr unsigned slot_below_lower_limit =
detail::xlate::replace_if_conversion_failed_impl::
slot_below_lower_limit;
static constexpr unsigned slot_underflow =
detail::xlate::replace_if_conversion_failed_impl::slot_underflow;
private:
template <class... As>
replace_if_conversion_failed(detail::generic_args_t, As&&...) = delete;
public:
static_assert(
!std::is_base_of_v<replacement_fail_t, std::remove_cv_t<T>>);
static_assert(
!std::is_base_of_v<replacement_ignore_t, std::remove_cv_t<T>>);
using value_type = T;
static constexpr std::size_t size = detail::xlate::
replace_if_conversion_failed_impl::base_t<T>::store_t::size;
// VS2019/2022 refuses to compile "base_t<T>" here
using detail::xlate::replace_if_conversion_failed_impl::base<T,
detail::xlate::replace_if_conversion_failed_impl::base_n<T>>::
base;
replace_if_conversion_failed(
const replace_if_conversion_failed&) = default;
replace_if_conversion_failed(
replace_if_conversion_failed&&) = default;
~replace_if_conversion_failed() = default;
replace_if_conversion_failed& operator=(
const replace_if_conversion_failed&) = default;
replace_if_conversion_failed& operator=(
replace_if_conversion_failed&&) = default;
template <class Ch, class U = T>
auto operator()(invalid_format_t,
const Ch* begin, const Ch* end, U* = nullptr) const
-> std::enable_if_t<std::is_convertible_v<const T&, U>, std::optional<U>>
{
return unwrap<U>(this->store().get(slot_invalid_format),
[begin, end]() {
fail_if_conversion_failed()(invalid_format_t(),
begin, end, static_cast<T*>(nullptr));
});
}
template <class Ch, class U = T>
auto operator()(out_of_range_t,
const Ch* begin, const Ch* end, int sign, U* = nullptr) const
-> std::enable_if_t<std::is_convertible_v<const T&, U>, std::optional<U>>
{
const auto fail = [begin, end, sign]() {
fail_if_conversion_failed()(out_of_range_t(),
begin, end, sign, static_cast<T*>(nullptr));
};
if (sign > 0) {
return unwrap<U>(this->store().get(slot_above_upper_limit), fail);
} else if (sign < 0) {
return unwrap<U>(this->store().get(slot_below_lower_limit), fail);
} else {
return unwrap<U>(this->store().get(slot_underflow), fail);
}
}
template <class U = T>
auto operator()(empty_t, U* = nullptr) const
-> std::enable_if_t<std::is_convertible_v<const T&, U>, std::optional<U>>
{
return unwrap<U>(this->store().get(slot_empty),
[]() {
fail_if_conversion_failed()(empty_t(),
static_cast<T*>(nullptr));
});
}
void swap(replace_if_conversion_failed& other)
noexcept(std::is_nothrow_swappable_v<T>
&& std::is_nothrow_constructible_v<T>)
{
// There seem to be pairs of a compiler and a standard library
// implementation (at least Clang 7) whose std::swap is not self-safe
// std::swap, which inherently employs move construction, which is not
// required to be self-safe
// (Clang7 seems to employ memcpy for move construction of trivially-
// copyable types, which itself is perfectly correct, and which is not,
// however, suitable for std::swap without self-check)
if (this != std::addressof(other)) {
using std::swap;
swap(this->store(), other.store());
}
}
private:
template <class U, class Fail>
std::optional<U> unwrap(
const std::pair<replace_mode, const T*>& p, Fail fail) const
{
switch (p.first) {
case replace_mode::replace:
return *p.second;
case replace_mode::ignore:
return std::nullopt;
case replace_mode::fail:
default:
break;
}
fail();
assert(false);
return std::nullopt;
}
};
template <class T>
auto swap(
replace_if_conversion_failed<T>& left,
replace_if_conversion_failed<T>& right)
noexcept(noexcept(left.swap(right)))
-> std::enable_if_t<std::is_swappable_v<T>>
{
left.swap(right);
}
template <class... Ts,
std::enable_if_t<
!std::is_same_v<
detail::replaced_type_not_found_t,
detail::replaced_type_from_t<Ts...>>>* = nullptr>
replace_if_conversion_failed(Ts...)
-> replace_if_conversion_failed<detail::replaced_type_from_t<Ts...>>;
namespace detail::xlate {
template <class A>
auto do_c_str(const A& a) -> decltype(a.c_str())
{
return a.c_str();
}
template <class A>
auto do_c_str(const A& a, ...) -> decltype(a->c_str())
{
return a->c_str();
}
template <class A>
auto do_size(const A& a) -> decltype(a.size())
{
return a.size();
}
template <class A>
auto do_size(const A& a, ...) -> decltype(a->size())
{
return a->size();
}
template <class T, class A, class H>
auto do_convert(const A& a, H&& h)
{
const auto* const c_str = do_c_str(a);
const auto size = do_size(a);
using U = std::remove_cv_t<T>;
return converter<U>()(c_str, c_str + size, error_handler<U, H>(h));
}
struct is_default_translatable_arithmetic_type_impl
{
template <class T>
static auto check(T* = nullptr) -> decltype(
numeric_type_traits<std::remove_cv_t<T>>::name, std::true_type());
template <class T>
static auto check(...) -> std::false_type;
};
} // end detail::xlate
template <class T>
struct is_default_translatable_arithmetic_type : decltype(detail::xlate::
is_default_translatable_arithmetic_type_impl::check<T>(nullptr))
{};
template <class T>
inline constexpr bool is_default_translatable_arithmetic_type_v =
is_default_translatable_arithmetic_type<T>::value;
template <class T, class ConversionErrorHandler, class A>
T to_arithmetic(const A& a, ConversionErrorHandler&& handler)
{
if constexpr (detail::is_std_optional_v<T>) {
using U = typename T::value_type;
static_assert(is_default_translatable_arithmetic_type_v<U>);
return detail::xlate::do_convert<U>(
a, std::forward<ConversionErrorHandler>(handler));
} else {
static_assert(is_default_translatable_arithmetic_type_v<T>);
const auto v = detail::xlate::do_convert<T>(
a, std::forward<ConversionErrorHandler>(handler));
if constexpr (std::is_convertible_v<decltype((v)), T>) {
return v;
} else {
return v.value();
}
}
}
template <class T, class A>
T to_arithmetic(const A& a)
{
if constexpr (detail::is_std_optional_v<T>) {
using U = typename T::value_type;
return detail::xlate::do_convert<U>(a, ignore_if_conversion_failed());
} else {
return detail::xlate::do_convert<T>(a, fail_if_conversion_failed());
}
}
class numpunct_replacer_to_c
{
std::locale loc_;
// These are initialized on the first invocation for the character type
wchar_t decimal_point_ = L'\0'; // of specified loc in the ctor
wchar_t thousands_sep_ = L'\0'; // ditto
wchar_t decimal_point_c_ = L'\0'; // of C's global to mimic
// std::strtol and its comrades
wchar_t thousands_sep_c_ = L'\0'; // ditto
bool mimics_ = false;
std::size_t prepared_for_ = 0U;
public:
explicit numpunct_replacer_to_c(const std::locale& loc) noexcept :
loc_(loc)
{}
numpunct_replacer_to_c(const numpunct_replacer_to_c&) noexcept = default;
numpunct_replacer_to_c& operator=(const numpunct_replacer_to_c&) noexcept
= default;
~numpunct_replacer_to_c() = default;
template <class ForwardIterator, class ForwardIteratorEnd>
ForwardIterator operator()(ForwardIterator first, ForwardIteratorEnd last)
{
using char_t =
typename std::iterator_traits<ForwardIterator>::value_type;
if (ensure_prepared<char_t>()) {
return impl(first, last ,first);
} else if constexpr (
std::is_same_v<ForwardIterator, ForwardIteratorEnd>) {
return last;
} else if constexpr (std::is_pointer_v<ForwardIterator>
&& std::is_pointer_v<ForwardIteratorEnd>) {
using f_t = std::remove_pointer_t<ForwardIterator>;
using l_t = std::remove_pointer_t<ForwardIteratorEnd>;
if constexpr (std::is_same_v<l_t, std::remove_cv_t<f_t>>) {
// f_t is cv qualified
return last;
} else if constexpr (std::is_same_v<f_t, std::remove_cv_t<l_t>>) {
// l_t is cv qualified
return const_cast<ForwardIterator>(last);
// last is reachable as first + (last - first), so this
// cast is safe
}
} else {
for (; !(first == last); ++first);
return first;
}
}
template <class InputIterator, class InputIteratorEnd,
class OutputIterator>
OutputIterator operator()(InputIterator first, InputIteratorEnd last,
OutputIterator result)
{
using char_t =
typename std::iterator_traits<InputIterator>::value_type;
if (ensure_prepared<char_t>()) {
return impl(first, last, result);
} else {
for (; !(first == last); ++first, ++result) {
*result = *first;
}
return result;
}
}
private:
template <class Ch>
bool ensure_prepared()
{
constexpr std::size_t now = sizeof(Ch);
if (prepared_for_ != now) {
const auto& lconv = *std::localeconv();
decimal_point_c_ = widen(*lconv.decimal_point, Ch());
thousands_sep_c_ = widen(*lconv.thousands_sep, Ch());
const auto& facet = std::use_facet<std::numpunct<Ch>>(loc_);
thousands_sep_ = facet.grouping().empty() ?
Ch() : facet.thousands_sep();
decimal_point_ = facet.decimal_point();
mimics_ = (decimal_point_ != decimal_point_c_)
|| ((thousands_sep_ != Ch())
&& (thousands_sep_ != thousands_sep_c_));
prepared_for_ = now;
}
return mimics_;
}
template <class InputIterator, class InputIteratorEnd,
class OutputIterator>
OutputIterator impl(InputIterator first, InputIteratorEnd last,
OutputIterator result)
{
using char_t =
typename std::iterator_traits<InputIterator>::value_type;
static_assert(std::is_same_v<char, char_t>
|| std::is_same_v<wchar_t, char_t>);
bool decimal_point_appeared = false;
for (; !(first == last); ++first) {
char_t c = *first;
if (c == static_cast<char_t>(decimal_point_)) {
if (!decimal_point_appeared) {
c = static_cast<char_t>(decimal_point_c_);
decimal_point_appeared = true;
}
} else if (c == static_cast<char_t>(thousands_sep_)) {
continue;
}
*result = c;
++result;
}
return result;
}
static char widen(char c, char)
{
return c;
}
static wchar_t widen(char c, wchar_t)
{
return std::btowc(static_cast<unsigned char>(c));
}
};
}
#endif |
import { usersService } from "../services/index.js";
import { createHash } from "../utils/hashing.js";
import Logger from "../utils/logger.js";
// all controllers use Service's functions. In this case, usersService
export async function getController(req, res, next) {
try {
const user = await usersService.getUserByEmail(req.user.email);
Logger.debug("user found by user get controller:", user);
res.jsonOk(user);
} catch (error) {
Logger.error("Error in getController:", error);
next(error);
}
}
export async function getAllController(req, res, next) {
try {
const users = await usersService.getAllUsers();
const filteredUsers = users.map((user) => ({
email: user.email,
first_name: user.first_name,
last_name: user.last_name,
role: user.role,
}));
Logger.debug("users found by user get controller:", filteredUsers);
res.jsonOk(filteredUsers);
} catch (error) {
Logger.error("Error in getController:", error);
next(error);
}
}
// register
export async function postController(req, res, next) {
try {
Logger.debug("req.body obtained in post controller", req.body);
const user = await usersService.addUser(req.body);
Logger.debug("User created/posted by postController:", user);
req.user = user;
res.created(user);
} catch (error) {
Logger.error("Error in postController:", error);
next(error);
}
}
//update profile:
/**
* This function handles the PUT request to update the user's profile.
* It first extracts the user ID from the request object, then extracts the
* fields to be updated from the request body. It also checks if a profile
* picture is included in the request, and if so, it extracts its path.
*
* If a current password and new password are included in the request, it
* authenticates the user with the current password and hashes the new password.
*
* Finally, it updates the user's profile with the extracted fields and sends a
* response containing the updated user object.
*
* @param {Object} req - The request object.
* @param {Object} res - The response object.
* @param {Function} next - The next middleware function.
*/
export async function putController(req, res, next) {
try {
// Extract user ID from request object
const userId = req.user._id;
// Extract fields from request body
const { first_name, last_name, age, currentPassword, newPassword, repeatNewPassword } = req.body;
// Create an object to hold the fields to be updated
const updateFields = {
first_name,
last_name,
age,
};
// If a profile picture is included in the request, extract its path
if (req.file) {
updateFields.profile_picture = req.file.path;
}
// Check if newPassword matches repeatNewPassword
if (newPassword && repeatNewPassword && newPassword !== repeatNewPassword) {
return res.status(400).json({
message: "The new passwords do not match.",
});
}
// If a current password and new password are included in the request,
// authenticate the user with the current password and hash the new password
if (currentPassword && newPassword) {
await usersService.authenticate({
email: req.user.email,
password: currentPassword,
});
const hashedNewPassword = await createHash(newPassword);
updateFields.password = hashedNewPassword;
}
// Update the user's profile with the extracted fields
const updatedUser = await usersService.updateUser(userId, updateFields);
// Update the request object with the updated user object
req.user = updatedUser;
// Send a response containing the updated user object
res.jsonOk(updatedUser);
} catch (error) {
// If an error occurs, pass it to the next middleware function
next(error);
}
}
export async function deleteController(req, res, next) {
try {
const deletedUser = await usersService.deleteUser(req.params.id);
Logger.debug("user detected to be deleted:", deletedUser);
res.ok();
} catch (error) {
next(error);
}
}
export const inactiveController = async (req, res, next) => {
try {
const deletedUsers = await usersService.clearInactiveUsers();
Logger.debug("deleted users:", deletedUsers);
res.ok();
} catch (error) {
next(error);
}
};
export const resetPasswordController = async (req, res, next) => {
try {
console.log("req.body", req.body);
const { email } = req.body;
console.log(email)
const user = await usersService.getUserByEmail(email);
console.log("user found by email in controller:", user);
if (!user) {
res.status(404).json({ message: "User not found" });
return;
}
Logger.debug("user found by email:", user);
await usersService.resetPassword(user);
res.ok();
} catch (error) {
Logger.error("Error in retrievePasswordController:", error);
next(error);
}
};
export const confirmPasswordResetController = async (req, res, next) => {
try {
console.log(req.params)
const { token }= req.params;
console.log("token got from req.params", token);
const { newPassword } = req.body;
const user = await usersService.updatePassword(null, newPassword, token);
if (!user) {
return res.status(400).json({ message: "Password reset token is invalid or has expired." });
}
console.log("password reset confirmed");
res.ok();
} catch (error) {
next(error);
}
} |
import time
from functools import wraps
def backoff(exceptions=Exception, start_sleep_time=1, factor=2, border_sleep_time=60):
if start_sleep_time <= 0:
raise ValueError("start_sleep_time must be greater than 0")
if factor <= 1:
raise ValueError("factor must be greater than 1")
if border_sleep_time <= 1:
raise ValueError("border_sleep_time must be greater than 1")
def func_wrapper(target):
@wraps(target)
async def inner(*args, **kwargs):
_tries = 0
while True:
try:
value = await target(*args, **kwargs)
if value:
return value
_tries += 1
time.sleep(1)
except exceptions as ex:
_tries -= 1
if _tries == 0:
raise ex
return inner
return func_wrapper |
import requests
from bs4 import BeautifulSoup
import csv
res = requests.get("https://www.91mobiles.com/top-10-mobiles-in-india")
soup = BeautifulSoup(res.text,'html.parser')
title = soup.title.string
#-----------------Phone-Image--------------------------#
ImageLink=[]
box_img = soup.find_all(class_="finder_pro_image fimage gaclick")
for desc in box_img:
if desc.get('src')!= None:
src_value = desc.get('src')
else :
src_value = desc.get('data-src')
ImageLink.append(src_value.replace('//',''))
#-----------------Phone-Name--------------------------#
box_pn = soup.find_all(class_="filter-grey-bar")
#List To Store All The Names of Phone on this Page
phoneName=[]
for x in box_pn :
if x.a == None :
continue
temp=x.a.getText().replace('\n','').lstrip().rstrip()
phoneName.append(temp)
#-----------------Price-----------------------------#
box_pr = soup.find_all(class_="price price_padding")
price = [ x.getText() for x in box_pr ]
#-----------------Expert Comment---------------------#
ExpertComment=[]
box_ec = soup.find_all(class_="exp_comnt_pnl")
for desc in box_ec:
temp = desc.getText().splitlines()
ExpertComment.append(temp[2].lstrip().rstrip())
#-----------------Specification---------------------#
Performance =[]
Display =[]
Camera =[]
Battery =[]
box_sc = soup.find_all(class_="filter-grey-bar filter_gray_bar_margin grey_bar_custpage")
for boxe in box_sc:
sub_box = boxe.find_all(class_="left specs_li")
for x in sub_box:
ans=x.getText()
if 'Performance' in ans:
LI=[]
for a in x.find_all("label"):
LI.append(a.getText())
Performance.append(LI)
if 'Display' in ans:
LI=[]
for a in x.find_all("label"):
LI.append(a.getText())
Display.append(LI)
if 'Camera' in ans:
LI=[]
for a in x.find_all("label"):
LI.append(a.getText())
Camera.append(LI)
if 'Battery' in ans:
LI=[]
for a in x.find_all("label"):
LI.append(a.getText())
Battery.append(LI)
merged_data = list(zip(phoneName, ImageLink, price, ExpertComment,Performance, Display, Camera, Battery))
csv_file_name = f"{title}.csv"
with open(csv_file_name, 'w', newline='', encoding='utf-8') as csvfile:
csv_writer = csv.writer(csvfile)
# Write header row
csv_writer.writerow(['Phone Name', 'Image Link', 'Price', 'Expert Comment', 'Performance', 'Display', 'Camera', 'Battery'])
# Write data rows
csv_writer.writerows(merged_data) |
/*
* Copyright (c) 2022 SAP SE or an SAP affiliate company. All rights reserved.
*/
import {
ConfirmationModalConfig,
EVENT_CONTENT_CATALOG_UPDATE,
IAlertService,
IConfirmationModalService,
IExperienceService,
IPageInfoService,
LogService,
SeDowngradeService,
SystemEventService,
PageVersioningService,
IPageVersion,
PageVersionSelectionService
} from 'smarteditcommons';
/**
* This service is used to rollback a page version from the toolbar context.
*/
@SeDowngradeService()
export class RollbackPageVersionService {
constructor(
private logService: LogService,
private alertService: IAlertService,
private confirmationModalService: IConfirmationModalService,
private experienceService: IExperienceService,
private pageInfoService: IPageInfoService,
private pageVersioningService: PageVersioningService,
private pageVersionSelectionService: PageVersionSelectionService,
private systemEventService: SystemEventService
) {}
public async rollbackPageVersion(version?: IPageVersion): Promise<void> {
const pageVersion = version || this.pageVersionSelectionService.getSelectedPageVersion();
if (!!pageVersion) {
const TRANSLATE_NS = 'se.cms.actionitem.page.version.rollback.confirmation';
const pageUuid = await this.pageInfoService.getPageUUID();
await this.showConfirmationModal(pageVersion.label, TRANSLATE_NS);
await this.performRollback(pageUuid, pageVersion);
}
}
// Warning! This method is patched in personalization module, be careful when modifying it.
private showConfirmationModal(versionLabel: string, translateNs: string): Promise<any> {
return this.confirmationModalService.confirm({
title: `${translateNs}.title`,
description: `${translateNs}.description`,
descriptionPlaceholders: {
versionLabel
}
} as ConfirmationModalConfig);
}
private async performRollback(pageUuid: string, pageVersion: IPageVersion): Promise<void> {
try {
await this.pageVersioningService.rollbackPageVersion(pageUuid, pageVersion.uid);
// invalidate the content catalog cache: a rollback of a page could replace the existing homepage.
this.systemEventService.publishAsync(EVENT_CONTENT_CATALOG_UPDATE);
this.alertService.showSuccess('se.cms.versions.rollback.alert.success');
// reload experience
await this.experienceService.updateExperience({});
this.pageVersionSelectionService.deselectPageVersion(false);
} catch {
this.logService.error(
'RollbackPageVersionService::performRollback - unable to perform page rollback'
);
}
}
} |
import React, {useMemo} from 'react';
import styled from "@emotion/styled";
import {css, keyframes} from "@emotion/react";
interface Props{
width?: number;
height?: number;
circle?: boolean; //원형 스켈레톤
rounded?: boolean; // border radius가 적용되어 모서리가 둥글게됨
count?: number; // width, height을 지정하지 않았을 때 글자의 개수를 제한
unit?: string; //width, height등의 단위 (px, rem)
animation?: boolean; //애니메이션 유무
color?: string;
style?: React.CSSProperties; //추가적인 스타일 객체
}
//pulse animation을 위한 keyframe
const pulseKeyframe = keyframes`
0%{
opacity: 1;
}
50%{
opacity: 0.3;
}
100%{
opacity: 1;
}
`
//계속 깜빡이는 pulse animation
const pulseAnimation = css`
animation: ${pulseKeyframe} 1.5s ease-in-out infinite;
`
//각 요소가 들어왔을 때 알맞은 스타일을 먹여주기
const Base = styled.div<Props>`
${({ color }) => color && `background-color: ${color}`};
${({ rounded }) => rounded && 'border-radius: 8px'};
${({ circle }) => circle && 'border-radius: 50%'};
${({ width, height }) => (width || height) && 'display: block'};
${({animation}) => animation && pulseAnimation};
width: ${({width, unit}) => width && unit && `${width}${unit}`};
height: ${({height, unit}) => height && unit && `${height}${unit}`};
`;
const Content = styled.span`
opacity: 0;
`;
const Skeleton: React.FC<Props> = ({
animation = true,
children,
width,
height,
circle,
rounded,
count,
unit = 'px',
color = '#F4F4F4',
style,
}) => {
//count 숫자만큼 길이의 array를 만들어주고 그 array를 -으로 join (ex. count=6 => 'content:------')
const content = useMemo(() => [...Array({length: count})].map(() => '-').join(''), [count]);
return (
<Base
style={style}
rounded={rounded}
circle={circle}
width={width}
height={height}
animation={animation}
unit={unit}
color={color}
>
<Content>{content}</Content>
</Base>
);
}
export default Skeleton; |
from typing import Union, List, ForwardRef
from pydantic import BaseModel
class MovieBase(BaseModel):
name: str
year: Union[str, None] = None
class MovieCreate(MovieBase):
pass
class Movie(MovieBase):
id: int
class Config:
from_attributes = True
class GenreBase(BaseModel):
name: str
class GenreCreate(GenreBase):
pass
class Genre(GenreBase):
id: int
class Config:
from_attributes = True
class MovieGenreBase(BaseModel):
movie_id: int
genre_id: int
class MovieGenreCreate(MovieGenreBase):
pass
class MovieGenre(MovieGenreBase):
id: int
class Config:
from_attributes = True
class MovieAndRelationships(Movie):
genres: List[GenreBase]
class GenreAndRelationships(Genre):
movies: List[MovieBase] |
<div class="container-fluid">
<div class="card card-title shadow p-3 mb-5">
<h3>Share your favorite quotes below <img src="https://img.icons8.com/material/24/000000/filled-star-filled.png" width="30"></h3>
</div>
<div class="row">
<form (ngSubmit)='submitQuote()' #quoteForm='ngForm' class="shadow p-3 mb-5">
<div class="form-group">
<label for="quote">Enter quote</label>
<textarea class="form-control" id="quote" [(ngModel)]="newQuote.name" name="name" #name=ngModel required></textarea>
<div [hidden]="name.valid || name.pristine" class="alert alert-danger">
<p>Fill in Quote to submit!</p>
</div>
</div>
<!-- Display {{newQuote.name}} -->
<div class="form-group">
<label for="author">Author</label>
<input type="text" class="form-control" placeholder="Author of quote" id="name" [(ngModel)]="newQuote.details" name="details" #details=ngModel required>
<div [hidden]="details.valid || details.pristine" class="alert alert-danger">
<p>Please provide Author of your quote!</p>
</div>
</div>
<div class="form-group">
<label for="name">Your name</label>
<input type="text" id="name" class="form-control" placeholder="Type your name" [(ngModel)]="newQuote.user" name="user" #user=ngModel>
</div>
<div class="form-group">
<label for="date">Date today</label>
<input type="date" id="date" [(ngModel)]="newQuote.completeDate" name="completeDate" #completeDate="ngModel" required>
<div [hidden]="completeDate.valid || completeDate.pristine" class="alert alert-danger" >
<p>Date is important!</p>
</div>
</div>
<button type="submit" class="btn btn-success btn=md">Add Quote</button>
</form>
</div>
</div> |
import Flutter
import UIKit
public class SwiftAppCommunicationPlugin: NSObject, FlutterPlugin {
var resultFlutter: FlutterResult?
var notificationReceived: String?
var receivedValue : Dictionary<String, Any>?
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "app_communication_plugin", binaryMessenger: registrar.messenger())
let instance = SwiftAppCommunicationPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
registrar.addApplicationDelegate(instance)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
resultFlutter = result
if(call.method == "getDataReceivedInSoftpos") {
if(receivedValue == nil) {
result(nil)
} else {
result(receivedValue)
}
} else if(call.method == "sendDataBackToSource") {
if(call.arguments == nil) {
sendDataBackToSource(arguments: nil)
} else {
sendDataBackToSource(arguments: convertArgumentsToDict(arguments: call.arguments as! [String : Any]))
}
} else if(call.method == "openSoftposApp") {
//
// TODO: When data will be received back to source app => please handle to convert int to bool type without fail
openSoftposApp(arguments: convertArgumentsToDict(arguments: call.arguments as! [String : Any]))
} else if(call.method == "throwErrorFromSoftpos") {
// sending in this method because for error it needs to be handled in notification call back
sendDataBackToSource(arguments: convertArgumentsToDict(arguments: call.arguments as! [String : Any]))
}
else {
result(FlutterMethodNotImplemented)
}
}
func openSoftposApp(arguments : [String : Any]) {
NotificationCenter.default.addObserver(self, selector: #selector(self.resultReceivedFromSoftpos(notification:)), name: Notification.Name("OPENSOFTPOSAPP"), object: nil)
var requestData = [URLQueryItem]()
for (key, value) in arguments {
requestData.append(URLQueryItem(name: key, value: String( describing: value) ))
}
var urlComps = URLComponents(string: "interpaymeasoftpos://app")!
urlComps.queryItems = requestData
let appScheme = String(describing: urlComps.url!)
let url : URL! = URL.init(string: appScheme.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)!
if #available(iOS 10.0, *) {
// commenting out because canOpenUrl gives false
if(UIApplication.shared.canOpenURL(url)) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
resultFlutter!(FlutterError(code: "404", message: "App not installed", details: nil))
}
} else {
// Fallback on earlier versions
}
}
@objc func resultReceivedFromSoftpos(notification: Notification) {
let data = getDictionaryFromUrl(url: (notification.userInfo!["url"] as! String).removingPercentEncoding!)
if(data == nil || data.isEmpty) {
resultFlutter!(FlutterError(code: "400", message: "User has cancelled the payment.", details: nil))
} else if(data["errorCode"] != nil) {
resultFlutter!(FlutterError(code:(data["errorCode"] as! String).removingPercentEncoding!, message: (data["errorMessage"] as! String).removingPercentEncoding!, details: (data["errorDetails"] as! String).removingPercentEncoding!))
}
else {
resultFlutter!(data)
}
}
func sendDataBackToSource(arguments :[String : Any]?) {
var responseData = [URLQueryItem]()
if(arguments == nil) {
//
} else {
for (key, value) in arguments! {
responseData.append(URLQueryItem(name: key, value: String( describing: value) ))
}
}
let responseUrl : String = receivedValue!["bundleUrlSchemeName"] as! String
var urlComps = URLComponents(string: "\(responseUrl)://app")!
urlComps.queryItems = responseData
let appScheme = String(describing: urlComps.url!)
let url : URL! = URL.init(string: appScheme.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)!
receivedValue = nil // adding null so that when user comes back to softpos he will not redirect to payment screen
resultFlutter!(true)
if #available(iOS 10.0, *) {
// commenting out because canOpenUrl gives false
// if(UIApplication.shared.canOpenURL(url)) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
// } else {
// resultFlutter!(FlutterError(code: "404", message: "App not installed", details: nil))
// }
} else {
// Fallback on earlier versions
}
}
public func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
print("Response From SourceApp==>\(url.absoluteString)")
notificationReceived = url.absoluteString
guard let query = notificationReceived else { return false}
receivedValue = getDictionaryFromUrl(url: query)
NotificationCenter.default.post(name: Notification.Name("OPENSOFTPOSAPP"), object: nil, userInfo: ["url" : query])
return true
}
func getDictionaryFromUrl(url : String) -> Dictionary<String, Any> {
var queryStrings = [String: Any]()
if(url.contains("&")) {
for pair in url.components(separatedBy: "?")[1].components(separatedBy: "&") {
let key = pair.components(separatedBy: "=")[0]
let value = pair
.components(separatedBy:"=")[1]
.replacingOccurrences(of: "+", with: " ")
.removingPercentEncoding ?? ""
queryStrings[key] = value
}
}
return queryStrings
}
func convertArgumentsToDict(arguments : [String : Any]) -> Dictionary<String, Any> {
var args = [String : Any]()
for (key, value) in arguments {
if(value is Bool) {
args[key] = Bool(value as! NSNumber)
} else {
args[key] = value
}
}
return args
}
} |
!!! question "Lesson: Check User Input Evenness"
=== "Task"
Create a small Python program that reads an integer value from user
input and prints if the input value is even or odd.
=== "Hints"
Find out about the modulo operator or the `divmod(...)` built-in
function.
Remember that the `input()` function returns text - to use number
operations you will need to convert the resulting user input to an
`int`.
=== "Solution"
??? example "*Really* take a peek now?"
``` python title="check_even.py"
--8<-- "training/lessons/check-user-input-evenness/check_even.py"
```
[:material-file-download:](check_even.py) |
/**
* Personium
* Copyright 2022 Personium Project Authors
* - FUJITSU LIMITED
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.personium.common.es.impl;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.personium.common.es.EsMappingConfig;
/**
* Abstract class for loading mapping from resources.
*/
public abstract class EsMappingFromResources implements EsMappingConfig {
private HashMap<String, ObjectNode> mapping;
/**
* Getter of map between type and resource path.
* @return map between type and resource path
*/
abstract Map<String, String> getMapTypeResPath();
/**
* {@inheritDoc}
*/
@Override
public Map<String, ObjectNode> getMapping() {
if (mapping == null) {
loadMappingConfigs();
}
return mapping;
}
/**
* Read mapping data from resources.
*/
synchronized void loadMappingConfigs() {
if (mapping != null) {
return;
}
mapping = new HashMap<String, ObjectNode>();
var mappingConfigs = getMapTypeResPath();
mappingConfigs.entrySet().forEach(entry -> {
mapping.put(entry.getKey(), readJsonResource(entry.getValue()));
});
}
/**
* Read JSON resource and return as ObjectNode.
* @param resPath resource path
* @return ObjectNode
*/
private static ObjectNode readJsonResource(final String resPath) {
ObjectMapper mapper = new ObjectMapper();
try (var is = EsMappingFromResources.class.getClassLoader().getResourceAsStream(resPath)) {
return mapper.readTree(is).deepCopy();
} catch (IOException e) {
throw new RuntimeException("exception while reading " + resPath, e);
}
}
} |
/* Sharon Yang
SMU Mathematics
Math 4370 / 6370 */
// Inclusions
#include "vec2d_b.hpp"
// This file implements the operations defined in the vec2d_b class
///// General class routines /////
// constructor (initializes values to 0.0)
vec2d_b::vec2d_b(long int m, long int n) {
// if m or n is illegal, create an empty vector
if (m < 1 || n < 1) {
this->length = 0;
this->nrow = 0;
this->ncol = 0;
this->data = NULL;
} else {
this->length = m*n;
this->nrow = m;
this->ncol = n;
this->data = new double [m*n]();
}
}
// destructor (frees space associated with a vec2d_b)
vec2d_b::~vec2d_b() {
if (this->data!=NULL)
delete[] this->data;
this->length = 0;
this->nrow = 0;
this->ncol = 0;
}
// write myself to stdout
void vec2d_b::Write() const {
// throw exception if data array isn't allocated
if (this->data == NULL)
throw std::invalid_argument( "vec2d_b::Write error, empty data array" );
// print data to screen
for (long int i=0; i<this->nrow; i++) {
for (long int j=0; j<this->ncol; j++)
std::cout << std::setprecision(17) << " " << this->data[i*this->ncol+j];
std::cout << std::endl;
}
std::cout << std::endl;
}
// write myself to a file
void vec2d_b::Write(const char *outfile) const {
// throw exception if data array isn't allocated
if (this->data == NULL)
throw std::invalid_argument( "vec2d_b::Write error, empty data array" );
// throw exception if 'outfile' is empty
if (strlen(outfile) < 1)
throw std::invalid_argument( "vec2d_b::Write error, empty outfile" );
// open output file
std::ofstream fstr;
fstr.open(outfile);
if (!fstr.is_open())
throw std::invalid_argument( "vec2d_b::Write error, unable to open file for writing" );
// print data to file
for (long int i=0; i<this->nrow; i++) {
for (long int j=0; j<this->ncol; j++)
fstr << std::setprecision(17) << " " << this->data[i*this->ncol+j];
fstr << std::endl;
}
fstr << std::endl;
// close output file
fstr.close();
}
///// Arithmetic operations defined on a given vec2d_b /////
// x = a*y + b*z
void vec2d_b::LinearSum(double a, const vec2d_b& y, double b, const vec2d_b& z) {
// check that array sizes match
if (y.nrow != this->nrow || z.nrow != this->nrow || y.ncol != this->ncol || z.ncol != this->ncol)
throw std::invalid_argument( "vec2d_b::LinearSum error, vector sizes do not match" );
// check that data is not NULL
if (this->data == NULL || y.data == NULL || z.data == NULL)
throw std::invalid_argument( "vec2d_b::LinearSum error: empty data array" );
// perform operation
for (long int i=0; i<this->nrow; i++) {
for (long int j=0; j<this->ncol; j++)
this->data[i*this->ncol+j] = a*y.data[i*this->ncol+j] + b*z.data[i*this->ncol+j];
}
}
// x = x*a (scales my data by scalar a)
void vec2d_b::Scale(double a) {
// check that data is not NULL
if (this->data == NULL)
throw std::invalid_argument( "vec2d_b::Scale error: empty data array" );
// perform operation
for (long int i=0; i<this->nrow; i++) {
for (long int j=0; j<this->ncol; j++)
this->data[i*this->ncol+j] *= a;
}
}
// x = y (copies y into x)
void vec2d_b::Copy(const vec2d_b& y) {
// check that array sizes match
if (y.nrow != this->nrow || y.ncol != this->ncol)
throw std::invalid_argument( "vec2d_b::Copy error, vector sizes do not match" );
// check that data is not NULL
if (this->data == NULL || y.data == NULL)
throw std::invalid_argument( "vec2d_b::Copy error: empty data array" );
// perform operation
for (long int i=0; i<this->nrow; i++) {
for (long int j=0; j<this->ncol; j++)
this->data[i*this->ncol+j] = y.data[i*this->ncol+j];
}
}
// x = a (sets all entries of x to the scalar a)
void vec2d_b::Constant(double a) {
// check that data is not NULL
if (this->data == NULL)
throw std::invalid_argument( "vec2d_b::Copy error: empty data array" );
// perform operation and return
for (long int i=0; i<this->nrow; i++) {
for (long int j=0; j<this->ncol; j++)
this->data[i*this->ncol+j] = a;
}
}
///// scalar quantities derived from vectors /////
// min x_i
double vec2d_b::Min() {
// check that my data is allocated
if (this->data == NULL)
throw std::invalid_argument( "vec2d_b::Min error: empty data array" );
// perform operation and return
double mn = this->data[0];
for (long int i=0; i<this->nrow; i++) {
for (long int j=0; j<this->ncol; j++)
mn = std::min(mn, this->data[i*this->ncol+j]);
}
return mn;
}
// max x_i
double vec2d_b::Max() {
// check that my data is allocated
if (this->data == NULL)
throw std::invalid_argument( "vec2d_b::Max error: empty data array" );
// perform operation and return
double mx = this->data[0];
for (long int i=0; i<this->nrow; i++) {
for (long int j=0; j<this->ncol; j++)
mx = std::max(mx, this->data[i*this->ncol+j]);
}
return mx;
}
///// independent constructor routines /////
// create a vector of linearly spaced data
vec2d_b Linspace(double a, double b, long int m, long int n) {
vec2d_b *x = new vec2d_b(m,n);
double *xd = x->GetData();
double h = (b-a)/(m*n-1);
for (long int i=0; i<m; i++) {
for (long int j=0; j<n; j++)
xd[i*n+j] = a + h*j + h*n*i;
}
return *x;
}
// create a vector of uniformly-distributed random data
vec2d_b Random(long int m, long int n) {
vec2d_b *x = new vec2d_b(m,n);
double *xd = x->GetData();
for (long int i=0; i<m; i++) {
for (long int j=0; j<n; j++)
xd[i*n+j] = random() / (pow(2.0,31.0) - 1.0);
}
return *x;
}
///// independent arithmetic routines /////
// dot-product of x and y
double Dot(const vec2d_b& x, const vec2d_b& y) {
// check that array sizes match
if (y.Length() != x.Length() || y.nRow() != x.nRow())
throw std::invalid_argument( "vec2d_b::Dot error, vector sizes do not match" );
// perform operation and return
double sum = 0.0;
for (long int i=0; i<x.nRow(); i++) {
for (long int j=0; j<x.nCol(); j++)
sum += x(i,j)*y(i,j);
}
return sum;
}
// ||x||_2
double TwoNorm(const vec2d_b& x) {
double sum = 0.0;
for (long int i=0; i<x.nRow(); i++)
for (long int j=0; j<x.nCol(); j++)
sum += x(i,j)*x(i,j);
return sqrt(sum);
}
// ||x||_RMS
double RmsNorm(const vec2d_b& x) {
double sum = 0.0;
for (long int i=0; i<x.nRow(); i++) {
for (long int j=0; j<x.nCol(); j++)
sum += x(i,j)*x(i,j);
}
return sqrt(sum/x.Length());
}
// ||x||_infty
double MaxNorm(const vec2d_b& x) {
double mx = 0.0;
for (long int i=0; i<x.nRow(); i++) {
for (long int j=0; j<x.nCol(); j++)
mx = std::max(mx, std::abs(x(i,j)));
}
return mx;
} |
@extends(getTemplate() . '.layouts.app')
@push('styles_top')
@endpush
@section('content')
@if (
!empty($webinars) and count($webinars) or
!empty($teachers) and count($teachers) or
!empty($organizations) and count($organizations))
<section class="site-top-banner search-top-banner opacity-04 position-relative">
<img src="{{ getPageBackgroundSettings('search') }}" class="img-cover" alt="" />
<div class="container h-100">
<div class="row h-100 align-items-center justify-content-center text-center">
<div class="col-12 col-md-9 col-lg-7">
<div class="top-search-form">
<h1 class="text-white font-30">{!! nl2br(trans('site.result_find', ['count' => $resultCount, 'search' => request()->get('search')])) !!}</h1>
<div class="search-input bg-white p-10 flex-grow-1">
<form action="/search" method="get">
<div class="form-group d-flex align-items-center m-0">
<input type="text" name="search" class="form-control border-0"
value="{{ request()->get('search', '') }}"
placeholder="{{ trans('home.slider_search_placeholder') }}" />
<button type="submit"
class="btn btn-primary rounded-pill">{{ trans('home.find') }}</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</section>
<div class="container">
@if (!empty($webinars) and count($webinars))
<section class="mt-50">
<h2 class="font-24 font-weight-bold text-secondary">{{ trans('webinars.webinars') }}</h2>
<div class="row">
@foreach ($webinars as $webinar)
<div class="col-md-6 col-lg-4 mt-30">
@include(getTemplate() . '.includes.webinar.grid-card', [
'webinar' => $webinar,
])
</div>
@endforeach
</div>
</section>
@endif
@if (!empty($teachers) and count($teachers))
<section class="mt-50">
<h2 class="font-24 font-weight-bold text-secondary">{{ trans('panel.users') }}</h2>
<div class="row">
@foreach ($teachers as $teacher)
<div class="col-6 col-md-3 col-lg-2 mt-30">
<div
class="user-search-card text-center d-flex flex-column align-items-center justify-content-center">
<div class="user-avatar">
<img src="{{ $teacher->getAvatar() }}" class="img-cover rounded-circle"
alt="{{ $teacher->full_name }}">
</div>
<a href="{{ $teacher->getProfileUrl() }}">
<h4 class="font-16 font-weight-bold text-dark-blue mt-10">{{ $teacher->full_name }}
</h4>
<span class="d-block font-14 text-gray mt-5">{{ $teacher->bio }}</span>
</a>
</div>
</div>
@endforeach
</div>
</section>
@endif
@if (!empty($organizations) and count($organizations))
<section class="mt-50">
<h2 class="font-24 font-weight-bold text-secondary">{{ trans('home.organizations') }}</h2>
<div class="row">
@foreach ($organizations as $organization)
<div class="col-md-6 col-lg-3 mt-30">
<a href="{{ $organization->getProfileUrl() }}"
class="home-organizations-card d-flex flex-column align-items-center justify-content-center">
<div class="home-organizations-avatar">
<img src="{{ $organization->getAvatar() }}" class="img-cover rounded-circle"
alt="{{ $organization->full_name }}">
</div>
<div class="mt-25 d-flex flex-column align-items-center justify-content-center">
<h3 class="home-organizations-title">{{ $organization->full_name }}</h3>
<p class="home-organizations-desc mt-10">{{ $organization->bio }}</p>
<span
class="home-organizations-badge badge mt-15">{{ $organization->getActiveWebinars(true) }}
{{ trans('product.courses') }}</span>
</div>
</a>
</div>
@endforeach
</div>
</section>
@endif
</div>
@else
<div class="no-result status-failed my-50 d-flex align-items-center justify-content-center flex-column">
<div class="no-result-logo">
<img src="/assets/default/img/no-results/search.png" alt="">
</div>
<div class="container">
<div class="row h-100 align-items-center justify-content-center text-center">
<div class="col-12 col-md-9 col-lg-7">
<div class="d-flex align-items-center flex-column mt-30 text-center w-100">
<h2>{{ trans('site.no_result_search') }}</h2>
<p class="mt-5 text-center">{!! trans('site.no_result_search_hint', ['search' => request()->get('search')]) !!}</p>
<div class="search-input bg-white p-10 mt-20 flex-grow-1 shadow-sm rounded-pill w-100">
<form action="/search" method="get">
<div class="form-group d-flex align-items-center m-0">
<input type="text" name="search" class="form-control border-0"
value="{{ request()->get('search', '') }}"
placeholder="{{ trans('home.slider_search_placeholder') }}" />
<button type="submit"
class="btn btn-primary rounded-pill">{{ trans('home.find') }}</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
@endif
@endsection |
---
interface Props {
size?: "md" | "lg";
block?: boolean;
style?: "outline" | "primary" | "inverted" | "secondary";
class?: string;
[x: string]: any;
}
const {
size = "md",
style = "primary",
block,
class: className,
...rest
} = Astro.props;
const sizes = {
md: "px-5 py-2.5",
lg: "px-6 py-3",
};
const styles = {
outline: "border-2 border-black hover:bg-black text-black hover:text-white",
primary:
"bg-black text-white hover:bg-slate-900 border-2 border-transparent",
secondary:
"bg-violet-600 text-violet-100 font-semibold rounded-full bg-violet-100 border px-8 focus:outline-none hover:bg-violet-900 hover:text-violet-100 text-lg",
};
---
<button
{...rest}
class:list={[
"rounded text-center transition focus-visible:ring-2 ring-offset-2 ring-gray-200",
block && "w-full",
sizes[size],
styles[style],
className,
]}
><slot />
</button> |
import React, { Component } from "react";
import { connect } from "react-redux";
import { actDatVe } from "./../store/actions";
class DatVe extends Component {
renderGheDaChon = () => {
const { gheDaChon, gheDaDat } = this.props;
return (gheDaChon.length > 0 ? gheDaChon : gheDaDat).map((ghe) => {
return (
<tr key={ghe.soGhe}>
<td>{ghe.soGhe}</td>
<td>{ghe.gia.toLocaleString()}</td>
</tr>
);
});
};
total = () => {
const { gheDaChon, gheDaDat } = this.props;
return (gheDaChon.length > 0 ? gheDaChon : gheDaDat).reduce(
(total, ghe) => (total += ghe.gia),
0
);
};
render() {
return (
<>
<table className="table table-bordered table-dark table-striped tableVe">
<thead>
<tr>
<th>Số Ghế</th>
<th>Giá</th>
</tr>
</thead>
<tbody>{this.renderGheDaChon()}</tbody>
<tfoot>
<tr>
<td>Tổng tiền</td>
<td>{this.total().toLocaleString()}</td>
</tr>
</tfoot>
</table>
<button
data-toggle="modal"
data-target="#modalThongBao"
className="btn btn-success"
onClick={() => {
this.props.datVe(this.props.gheDaChon);
}}
>
Đặt Vé
</button>
</>
);
}
}
const mapStateToProps = (state) => {
return {
gheDaChon: state.seatReducer.gheDaChon,
gheDaDat: state.seatReducer.gheDaDat,
};
};
const mapDispatchToProps = (dispatch) => {
return {
datVe: (ghe) => {
dispatch(actDatVe(ghe));
},
};
};
export default connect(mapStateToProps, mapDispatchToProps)(DatVe); |
CREATE TABLE employees (
id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
department VARCHAR(50),
salary DECIMAL(10, 2)
);
INSERT INTO employees (id, first_name, last_name, department, salary)
VALUES
(1, 'John', 'Doe', 'IT', 50000.00),
(2, 'Jane', 'Smith', 'HR', 60000.00),
(3, 'Alice', 'Johnson', 'Finance', 70000.00);
-- Create a view
CREATE VIEW employee_names AS
SELECT id, CONCAT(first_name, ' ', last_name) AS full_name
FROM employees;
-- Query the view
SELECT * FROM employee_names;
-- Update the view (recreate it)
-- Create a view if didn't exists already, or replace it with this new one.
CREATE OR REPLACE VIEW employee_names AS
SELECT id, CONCAT(first_name, ' ', last_name) AS full_name
FROM employees
WHERE department = 'IT';
SELECT * FROM employee_names;
-- Delete the view
DROP VIEW employee_names; |
import java.util.ArrayList;
import java.util.List;
public class Professor extends Pessoa {
private String titulacao;
private double salario;
private List<Curso> cursos;
public Professor() {
cursos = new ArrayList<>();
}
public void setTitulacao(String titulacao) {
this.titulacao = titulacao;
}
public String getTitulacao() {
return titulacao;
}
public void setSalario(double salario) {
this.salario = salario;
}
public double getSalario() {
return salario;
}
public void setCursos(List<Curso> cursos) {
this.cursos = cursos;
}
public List<Curso> getCursos() {
return cursos;
}
public void imprimir() {
System.out.println("Nome: " + getNome());
System.out.println("CPF: " + getCPF());
System.out.println("E-mail: " + getEmail());
System.out.println("Titulação: " + titulacao);
System.out.println("Salário: " + salario);
System.out.println("Cursos lecionados: ");
for (Curso curso : cursos) {
curso.imprimirCurso();
}
}
} |
package org.aquam.service.impl;
import lombok.RequiredArgsConstructor;
import org.aquam.model.AppUser;
import org.aquam.model.AppUserSettings;
import org.aquam.model.Country;
import org.aquam.model.Language;
import org.aquam.model.SupportLetter;
import org.aquam.model.dto.AppUserDto;
import org.aquam.model.dto.AppUserModel;
import org.aquam.model.dto.SupportLetterDto;
import org.aquam.model.request.RegistrationRequest;
import org.aquam.repository.AppUserRepository;
import org.aquam.repository.SupportLetterRepository;
import org.aquam.service.AppUserService;
import org.aquam.service.CountryService;
import org.aquam.service.LanguageService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import javax.persistence.EntityNotFoundException;
import javax.transaction.Transactional;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Valid;
import java.util.Optional;
import java.util.Set;
@Service
@Transactional
@RequiredArgsConstructor
public class AppUserServiceImpl implements AppUserService, UserDetailsService {
private final AppUserRepository userRepository;
private final CountryService countryService;
private final LanguageService languageService;
private final SupportLetterRepository supportLetterRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return userRepository.findByUsername(username).orElseThrow(
() -> new UsernameNotFoundException(String.format("Username: %d not found", username)));
}
@Override
public Optional<AppUser> findUserByUsername(String username) {
return userRepository.findByUsername(username);
}
@Override
public AppUser findByUsername(String username) {
return userRepository.findByUsername(username).orElseThrow(
() -> new EntityNotFoundException("User with username " + username + " not found"));
}
@Override
public AppUser findById(Long id) {
return userRepository.findById(id).orElseThrow(
() -> new EntityNotFoundException("User with id " + id + " not found"));
}
@Override
public AppUserModel readCurrent(String username) {
AppUser current = findByUsername(username);
AppUserSettings appUserSettings = current.getAppUserSettings();
AppUserModel model = new AppUserModel(
username,
current.getEmail(),
current.getInstagram(),
current.getRegistrationDate()
);
return model;
}
@Override
public Boolean setCountry(String username, Long countryId) {
AppUser current = findByUsername(username);
Country country = countryService.findById(countryId);
current.getAppUserSettings().setCountry(country);
return true;
}
@Override
public Boolean setLanguage(String username, Long languageId) {
AppUser current = findByUsername(username);
Language language = languageService.findById(languageId);
current.getAppUserSettings().setLanguage(language);
return true;
}
@Override
public Boolean saveLetter(SupportLetterDto supportLetterDto) {
AppUser user = findByUsername(getAuthentication().getName());
SupportLetter supportLetter = new SupportLetter();
supportLetter.setEmail(user.getEmail());
supportLetter.setTitle(supportLetterDto.getTitle());
supportLetter.setBody(supportLetterDto.getBody());
SupportLetter save = supportLetterRepository.save(supportLetter);
return true;
}
@Override
public String changeEmail(String email) {
Authentication authentication = getAuthentication();
String username = authentication.getName();
AppUser appUser = findByUsername(username);
appUser.setEmail(email);
AppUser save = userRepository.save(appUser);
return appUser.getEmail();
}
public Authentication getAuthentication() {
return SecurityContextHolder.getContext().getAuthentication();
}
public Boolean delete() {
Authentication authentication = getAuthentication();
AppUser appUser = findByUsername(authentication.getName());
appUser.setEmail(null);
appUser.setPassword(null);
userRepository.save(appUser);
return true;
}
@Override
public Boolean block(String username) {
AppUser appUser = findByUsername(username);
appUser.setLocked(true);
userRepository.save(appUser);
return true;
}
} |
def is_valid_sudoku(board):
# Use sets to keep track of seen numbers in rows, columns, and sub-boxes
rows = [set() for _ in range(9)]
cols = [set() for _ in range(9)]
boxes = [set() for _ in range(9)]
for i in range(9):
for j in range(9):
num = board[i][j]
if num == '.':
continue
# Check rows
if num in rows[i]:
return False
rows[i].add(num)
# Check columns
if num in cols[j]:
return False
cols[j].add(num)
# Check 3x3 sub boxes
box_index = (i // 3) * 3 + (j // 3)
if num in boxes[box_index]:
return False
boxes[box_index].add(num)
return True
# Example usage
board = [
["5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
print(is_valid_sudoku(board)) |
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:khalti_checkout_flutter/khalti_checkout_flutter.dart';
void main() {
runApp(
const MaterialApp(
home: KhaltiSDKDemo(),
),
);
}
class KhaltiSDKDemo extends StatefulWidget {
const KhaltiSDKDemo({super.key});
@override
State<KhaltiSDKDemo> createState() => _KhaltiSDKDemoState();
}
class _KhaltiSDKDemoState extends State<KhaltiSDKDemo> {
late final Future<Khalti?> khalti;
String pidx =
'ZyzCEMLFz2QYFYfERGh8LE'; // Should be generated via a server-side POST request.
PaymentResult? paymentResult;
@override
void initState() {
super.initState();
final payConfig = KhaltiPayConfig(
publicKey:
'live_public_key_979320ffda734d8e9f7758ac39ec775f', // This is a dummy public key for example purpose
pidx: pidx,
returnUrl: Uri.parse('https://docs.khalti.com/khalti-epayment/'),
environment: Environment.test,
);
khalti = Khalti.init(
enableDebugging: true,
payConfig: payConfig,
onPaymentResult: (paymentResult, khalti) {
log(paymentResult.toString());
setState(() {
this.paymentResult = paymentResult;
});
khalti.close(context);
},
onMessage: (
khalti, {
description,
statusCode,
event,
needsPaymentConfirmation,
}) async {
log(
'Description: $description, Status Code: $statusCode, Event: $event, NeedsPaymentConfirmation: $needsPaymentConfirmation',
);
khalti.close(context);
},
onReturn: () => log('Successfully redirected to return_url.'),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: FutureBuilder(
future: khalti,
initialData: null,
builder: (context, snapshot) {
final khaltiSnapshot = snapshot.data;
if (khaltiSnapshot == null) {
return const CircularProgressIndicator.adaptive();
}
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
'assets/seru.png',
height: 200,
width: 200,
),
const SizedBox(height: 120),
const Text(
'Rs. 22',
style: TextStyle(fontSize: 25),
),
const Text('1 day fee'),
OutlinedButton(
onPressed: () => khaltiSnapshot.open(context),
child: const Text('Pay with Khalti'),
),
const SizedBox(height: 120),
paymentResult == null
? Text(
'pidx: $pidx',
style: const TextStyle(fontSize: 15),
)
: Column(
children: [
Text(
'pidx: ${paymentResult!.payload?.pidx}',
),
Text('Status: ${paymentResult!.status}'),
Text(
'Amount Paid: ${paymentResult!.payload?.amount}',
),
Text(
'Transaction ID: ${paymentResult!.payload?.transactionId}',
),
],
),
const SizedBox(height: 120),
const Text(
'This is a demo application developed by some merchant.',
style: TextStyle(fontSize: 12),
)
],
);
},
),
),
);
}
} |
#!/usr/bin/env ruby
require "thor"
class App < Thor
include Thor::Actions
def self.exit_on_failure?
true
end
SERVICE_LIST = %w[db]
private_constant :SERVICE_LIST
class_option :force, type: :boolean, default: false
argument :cmd, type: :string, required: true, desc: "Action to perform"
desc "services", "Administer services"
def services
service_list.each do |service|
run("bin/#{service} #{cmd}", capture: true)
end
end
private
def service_list
SERVICE_LIST
end
end
App.start(ARGV) |
/*
Copyright 2015-Present Entando Inc. (http://www.entando.com) All rights reserved.
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
*/
package org.entando.selenium.tests;
import org.entando.selenium.testHelpers.WidgetsTestBase;
import static java.lang.Thread.sleep;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.entando.selenium.utils.*;
import org.entando.selenium.pages.DTWidgetEditPage;
import org.entando.selenium.pages.DTDashboardPage;
import org.entando.selenium.pages.DTWidgetAddPage;
import org.entando.selenium.pages.DTWidgetPage;
import org.entando.selenium.utils.pageParts.SimpleTable;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebElement;
/**
* This class perform a test of the Edit Widget Page
*
* @version 1.03
*/
@RunWith(Parallelized.class)
public class DTWidgetEditTest extends WidgetsTestBase {
//Constructor
public DTWidgetEditTest(String browserName, String platformName) {
super(browserName, platformName);
}
/*
Test
*/
@Test
public void runTest() throws InterruptedException {
/*
Pages used on this test
*/
DTDashboardPage dTDashboardPage = new DTDashboardPage(driver);
DTWidgetEditPage dTWidgetEditPage = new DTWidgetEditPage(driver);
DTWidgetPage dTWidgetPage = new DTWidgetPage(driver);
DTWidgetAddPage dTWidgetAddPage = new DTWidgetAddPage(driver);
/*
Parameters
*/
//Link menù buttons
String firstLevelLink = "UX Patterns";
String secondLevelLink = "Widgets";
/*
Actions and asserts
*/
//Login
login();
//Navigation to the page
dTDashboardPage.SelectSecondOrderLink(firstLevelLink, secondLevelLink);
Utils.waitUntilIsVisible(driver, dTWidgetPage.getNewButton());
//Add a Standard Widget to edit
Assert.assertTrue("Unable to add a widget",
addWidget(dTWidgetPage, dTWidgetAddPage));
//refresh the page
driver.navigate().refresh();
//Edit the widget
SimpleTable table = new SimpleTable(dTWidgetPage.getTables().get("user"));
WebElement cell = table.getCell(code, expectedHeaderTitles.get(0),
expectedHeaderTitles.get(0));
Assert.assertTrue(cell != null);
cell.findElement(By.xpath(".//a")).click();
//Wait loading the page
Utils.waitUntilIsVisible(driver, dTWidgetEditPage.getPageTitle());
Utils.waitUntilAttributeToBeNotEmpty(driver, dTWidgetEditPage.getEnTitleField(),
"value");
dTWidgetEditPage.getEnTitleField().clear();
dTWidgetEditPage.getItTitleField().click();
Assert.assertTrue("En Title field error not displayed",
dTWidgetEditPage.getEnTitleFieldError().isDisplayed());
Assert.assertFalse("Save Button is enabled",
dTWidgetEditPage.getSaveButton().isEnabled());
dTWidgetEditPage.setEnTitleField(code);
dTWidgetEditPage.getSaveButton().click();
//Wait loading page
try
{
Utils.waitUntilIsPresent(driver, dTWidgetPage.spinnerTag);
}
catch(TimeoutException | NoSuchElementException exception)
{
Assert.assertTrue("The Spinner did not appear after save the changes", false);
}
try
{
Utils.waitUntilIsDisappears(driver, dTWidgetPage.spinnerTag);
}
catch(TimeoutException exception)
{
Assert.assertTrue("The Spinner did not disappear after save the changes", false);
}
//Verify the success message
Assert.assertEquals("Success message content not valid",
editSuccessMessage, dTWidgetPage.getAlertMessageContent());
dTWidgetPage.getCloseAlertMessageButton().click();
//Delete the Widget
Assert.assertTrue("Unable to delete the widget",
deleteWidget(dTWidgetPage, code));
/** Debug code **/
if(Logger.getGlobal().getLevel() == Level.INFO){
sleep(SLEEPTIME);
}
/** End Debug code**/
}
} |
import torch
from torch import nn
import torch.nn.functional as F
class FocalLoss(nn.Module):
def __init__(self, alpha=[1, 1, 1], gamma=2, reduction='mean', device='cpu'):
super(FocalLoss, self).__init__()
self.alpha = torch.tensor(alpha).to(device)
self.gamma = gamma
self.reduction = reduction
def forward(self, inputs, targets):
BCE_loss = F.cross_entropy(inputs, targets, reduction='none')
pt = torch.exp(-BCE_loss)
alpha = self.alpha[targets] if len(self.alpha) > 1 else self.alpha
F_loss = alpha * (1 - pt) ** self.gamma * BCE_loss
if self.reduction == 'mean':
return torch.mean(F_loss)
elif self.reduction == 'sum':
return torch.sum(F_loss)
else:
return F_loss
class MultiClassF1Loss(nn.Module):
def __init__(self, num_classes=3, epsilon=1e-7):
super(MultiClassF1Loss, self).__init__()
self.num_classes = num_classes
self.epsilon = epsilon
def forward(self, y_pred, y_true):
# 원-핫 인코딩 변환
y_true_one_hot = F.one_hot(y_true, num_classes=self.num_classes)
# 소프트맥스 적용하여 확률을 계산
y_pred_softmax = F.softmax(y_pred, dim=1)
# y_pred를 이진 형태로 변환
y_pred_one_hot = y_pred_softmax.round()
# 클래스별 true positive, predicted positive, actual positive 계산
true_positive = torch.sum(y_true_one_hot * y_pred_one_hot, dim=0)
predicted_positive = torch.sum(y_pred_one_hot, dim=0)
actual_positive = torch.sum(y_true_one_hot, dim=0)
# 클래스별 F1 점수 계산
precision = true_positive / (predicted_positive + self.epsilon)
recall = true_positive / (actual_positive + self.epsilon)
f1_score = 2 * precision * recall / (precision + recall + self.epsilon)
f1_score = f1_score[torch.isfinite(f1_score)] # NaN 제거
# 평균 F1 점수 계산
avg_f1_score = torch.mean(f1_score)
# F1 손실 (1 - F1 점수)
f1_loss = 1 - avg_f1_score
# 멀티클래스 교차 엔트로피 손실 추가
cross_entropy_loss = F.cross_entropy(y_pred, y_true)
# 최종 손실: 교차 엔트로피와 F1 손실의 평균
combined_loss = (cross_entropy_loss + f1_loss) / 2
return combined_loss
class SigmoidF1Loss(nn.Module):
def __init__(self, num_classes=3, beta=1.0, eta=0.0):
super(SigmoidF1Loss, self).__init__()
self.beta = beta
self.eta = eta
self.num_classes = num_classes
def forward(self, y_pred, y_true):
y_true_one_hot = F.one_hot(y_true, num_classes=self.num_classes).float()
sig = 1 / (1 + torch.exp(-self.beta * (y_pred + self.eta)))
tp = torch.sum(sig * y_true_one_hot, dim=0)
fp = torch.sum(sig * (1 - y_true_one_hot), dim=0)
fn = torch.sum((1 - sig) * y_true_one_hot, dim=0)
sigmoid_f1 = 2 * tp / (2 * tp + fn + fp + 1e-16)
return 1 - sigmoid_f1.mean() |
<template>
<div class="py-6 pb-[15rem] grid place-items-center" >
<p v-show="state" class="my-4 p-2 bg-gray-50 text-green-600 absolute bottom-0 right-10 font-bold" >{{ msg }}</p>
<form @submit.prevent="updateProduct" class="p-4 border-[1px] border-gray-50/10 rounded-md shadow-xl
flex flex-col gap-4" >
<div class="flex flex-col gap-2" >
<label for="category">Category</label>
<input id="category" type="text" :placeholder="store.product.category" v-model="category"
class="p-2 border-[1px] bg-transparent outline-none border-gray-50/10 focus:border-gray-50" >
</div>
<div class="flex flex-col gap-2" >
<label for="price">Price</label>
<input id="price" type="text" :placeholder="store.product.price" v-model="price"
class="p-2 border-[1px] bg-transparent outline-none border-gray-50/10 focus:border-gray-50" >
</div>
<div class="flex flex-col gap-2" >
<label for="title">Title</label>
<input id="title" type="text" :placeholder="store.product.title" v-model="title"
class="p-2 border-[1px] bg-transparent outline-none border-gray-50/10 focus:border-gray-50">
</div>
<div class="flex flex-col gap-2" >
<label for="desc">Description</label>
<textarea id="desc" cols="30" rows="6" v-model="desc" :placeholder="store.product.description"
class="p-4 outline-none border-[1px] border-gray-50/10 focus:border-gray-50 bg-transparent"></textarea>
</div>
<button class="w-full p-2 bg-gray-800 hover:bg-gray-900" >Update</button>
</form>
</div>
</template>
<script setup>
import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { datas } from '@/stores/datas';
const store = datas();
const route = useRoute();
const category = ref('');
const price = ref('');
const title = ref('');
const desc = ref('');
const state = ref(false);
let msg = '';
onMounted(() => {
store.getProduct(route.params.id);
});
const updateProduct = async () => {
const result = await fetch(`${store.uri}products/${route.params.id}`, {
mode: 'cors',
method: 'PATCH',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json'
},
body: JSON.stringify({
"title": title.value,
"price": price.value,
"description": desc.value,
"category": category.value,
"image": "https://i.pravatar.cc"
})
});
const data = await result.json();
if( data.id.toString() === route.params.id ) {
state.value = true;
msg = 'Updated Successfully!'
}
setTimeout(() => {
state.value = false;
},2000);
}
</script> |
// Calculator class
class Calculator {
// Adds two numbers
add(a, b) {
return a + b;
}
// Subtracts two numbers
subtract(a, b) {
return a - b;
}
// Multiplies two numbers
multiply(a, b) {
return a * b;
}
// Divides two numbers, checking for division by zero
divide(a, b) {
if (b === 0) {
return "Cannot divide by zero";
}
return a / b;
}
}
// ScientificCalculator class extending Calculator
class ScientificCalculator extends Calculator {
// Calculates the square of a number
square(num) {
return num * num;
}
// Calculates the cube of a number
cube(num) {
return num * num * num;
}
// Calculates the power of a number
power(base, exponent) {
return Math.pow(base, exponent);
}
}
const sciCalc = new ScientificCalculator();
// Using call method to invoke add method from Calculator class
const sum = Calculator.prototype.add.call(sciCalc, 10, 5);
console.log("Sum:", sum);
// Using apply method to invoke subtract method from Calculator class
const difference = Calculator.prototype.subtract.apply(sciCalc, [10, 5]);
console.log("Difference:", difference);
// Using bind method to create multiplyByTwo method
const multiplyByTwo = Calculator.prototype.multiply.bind(sciCalc, 2);
console.log("Multiply by 2:", multiplyByTwo(5)); // Optional
// Using bind method to create powerOfThree method
const powerOfThree = ScientificCalculator.prototype.power.bind(sciCalc, 3);
console.log("Power of 3:", powerOfThree(2)); // Optional |
package com.patients.main.features.patient.home_screen.presentation
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.patients.main.PatientRoutes
import com.patients.main.R
import com.patients.main.core.ui.about_button.AboutButton
import com.patients.main.core.ui.survey_card.SurveyCard
import com.patients.main.data.SurveyDTO
import com.patients.main.data.USERS
import com.patients.main.data.UserRole
//@Preview(
// showBackground = true,
//)
@Composable
fun PatientHomeScreen(
modifier: Modifier = Modifier,
navController: NavController,
patientName: String,
surveys: List<SurveyDTO>,
) {
Column(modifier = modifier) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(start = 20.dp, top = 20.dp, end = 20.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(
modifier = Modifier,
text = stringResource(R.string.hello_name, patientName),
fontSize = 24.sp
)
Spacer(modifier = Modifier.weight(1f))
AboutButton(modifier = Modifier)
}
if (surveys.isNotEmpty()) {
LazyColumn {
items(surveys) { item ->
SurveyCard(
title = stringResource(
R.string.survey_from_doctor_name,
USERS.find { it.id == item.doctorID && it.role == UserRole.Doctor }!!.name
),
body = item.title,
) {
navController.navigate(
route = PatientRoutes.TakeSurvey.takeSurveyWithArg(
item.id
)
)
}
}
}
} else {
Text(
modifier = Modifier
.fillMaxWidth()
.padding(top = 10.dp),
textAlign = TextAlign.Center,
text = stringResource(R.string.no_available_survey),
fontSize = 20.sp,
)
}
}
} |
import { useState, useContext } from "react";
import { Link, useNavigate } from "react-router-dom";
import { authContext } from "../context/AuthContext";
function Login() {
const [user, setUser] = useState({
email: "",
password: "",
});
const { login } = useContext(authContext);
const navigate = useNavigate();
const handleSubmit = async (e) => {
e.preventDefault();
try {
await login(user.email, user.password);
navigate("/");
} catch (error) {
console.log(error.message);
}
};
return (
<div className="container py-5 h-100">
<div className="row d-flex justify-content-center align-items-center h-100">
<div className="col-12 col-md-8 col-lg-6 col-xl-5">
<div className="card bg-dark text-white">
<div className="card-body p-5 text-center">
<div className="mb-md-5 mt-md-4 pb-5">
<h1 className="fw-bold mb-2 text-uppercase">Login</h1>
<form onSubmit={handleSubmit}>
<div className="form-outline form-white mb-4">
<label className="form-label" for="typeEmailX">
Email
</label>
<input
type="email"
id="typeEmailX"
className="form-control form-control-lg"
onChange={(e) =>
setUser({ ...user, email: e.target.value })
}
/>
</div>
<div className="form-outline form-white mb-4">
<label className="form-label" for="typePasswordX">
Contraseña
</label>
<input
type="password"
id="typePasswordX"
className="form-control form-control-lg"
onChange={(e) =>
setUser({ ...user, password: e.target.value })
}
/>
</div>
<p className="mb-5 pb-lg-2 btn-link fw-bold text-white-50 pe-">
Olvidaste tu contraseña?
</p>
<button
className="btn btn-outline-success btn-lg px-5"
type="submit"
>
Login
</button>
</form>
</div>
<div>
<p className="mb-0">
No tenes cuenta?
<Link to={"/register"}>
<button className="text-white-50 fw-bold btn btn-link">
Registrate
</button>
</Link>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
export default Login; |
/*
* C implementations of test functions
* CSF Assignment 2 MS1
* Jianan Xu
* jxu147@jhu.edu
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "image.h"
#include "drawing_funcs.h"
#include "tctest.h"
// an expected color identified by a (non-zero) character code
typedef struct {
char c;
uint32_t color;
} ExpectedColor;
// struct representing a "picture" of an expected image
typedef struct {
ExpectedColor colors[20];
const char *pic;
} Picture;
typedef struct {
struct Image small;
struct Image large;
struct Image tilemap;
struct Image spritemap;
} TestObjs;
// dimensions and pixel index computation for "small" test image (objs->small)
#define SMALL_W 8
#define SMALL_H 6
#define SMALL_IDX(x,y) ((y)*SMALL_W + (x))
// dimensions of the "large" test image
#define LARGE_W 24
#define LARGE_H 20
// create test fixture data
TestObjs *setup(void) {
TestObjs *objs = (TestObjs *) malloc(sizeof(TestObjs));
init_image(&objs->small, SMALL_W, SMALL_H);
init_image(&objs->large, LARGE_W, LARGE_H);
objs->tilemap.data = NULL;
objs->spritemap.data = NULL;
return objs;
}
// clean up test fixture data
void cleanup(TestObjs *objs) {
free(objs->small.data);
free(objs->large.data);
free(objs->tilemap.data);
free(objs->spritemap.data);
free(objs);
}
uint32_t lookup_color(char c, const ExpectedColor *colors) {
for (unsigned i = 0; ; i++) {
assert(colors[i].c != 0);
if (colors[i].c == c) {
return colors[i].color;
}
}
}
void check_picture(struct Image *img, Picture *p) {
unsigned num_pixels = img->width * img->height;
assert(strlen(p->pic) == num_pixels);
for (unsigned i = 0; i < num_pixels; i++) {
char c = p->pic[i];
uint32_t expected_color = lookup_color(c, p->colors);
uint32_t actual_color = img->data[i];
ASSERT(actual_color == expected_color);
}
}
// prototypes of test functions
// prototypes of helper functions
void test_in_bounds(TestObjs *objs);
void test_compute_index(TestObjs *objs);
void test_clamp(TestObjs *objs);
void test_get_r(TestObjs *objs);
void test_get_g(TestObjs *objs);
void test_get_b(TestObjs *objs);
void test_get_a(TestObjs *objs);
void test_blend_components(TestObjs *objs);
void test_blend_colors(TestObjs *objs);
void test_set_pixel(TestObjs *objs);
void test_square(TestObjs *objs);
void test_square_dist(TestObjs *objs);
// prototypes of API functions
void test_draw_pixel(TestObjs *objs);
void test_draw_rect(TestObjs *objs);
void test_draw_circle(TestObjs *objs);
void test_draw_circle_clip(TestObjs *objs);
void test_draw_tile(TestObjs *objs);
void test_draw_sprite(TestObjs *objs);
int main(int argc, char **argv) {
if (argc > 1) {
// user specified a specific test function to run
tctest_testname_to_execute = argv[1];
}
TEST_INIT();
// Test help function
TEST(test_in_bounds);
TEST(test_compute_index);
TEST(test_clamp);
TEST(test_get_r);
TEST(test_get_g);
TEST(test_get_b);
TEST(test_get_a);
TEST(test_blend_components);
TEST(test_blend_colors);
TEST(test_set_pixel);
TEST(test_square);
TEST(test_square_dist);
TEST(test_draw_pixel);
TEST(test_draw_rect);
TEST(test_draw_circle);
TEST(test_draw_circle_clip);
TEST(test_draw_tile);
TEST(test_draw_sprite);
TEST_FINI();
}
void test_in_bounds(TestObjs *objs) {
ASSERT(!in_bounds(&objs->small, 8, 6));
ASSERT(in_bounds(&objs->small, 7, 5));
ASSERT(!in_bounds(&objs->small, -7, 5));
ASSERT(!in_bounds(&objs->large, 24, 2));
ASSERT(!in_bounds(&objs->large, 2, 20));
ASSERT(in_bounds(&objs->large, 0, 0));
}
void test_compute_index(TestObjs *objs) {
ASSERT(compute_index(&objs->small, 3, 2) == 19);
ASSERT(compute_index(&objs->small, 0, 0) == 0);
ASSERT(compute_index(&objs->small, 7, 5) == 47);
ASSERT(compute_index(&objs->large, 3, 2) == 51);
ASSERT(compute_index(&objs->large, 23, 19) == 479);
}
void test_clamp(TestObjs *objs) {
ASSERT(clamp(3, 0, 7));
ASSERT(!clamp(6, 0, 5));
ASSERT(clamp(0, 0, 0));
ASSERT(!clamp(19, 20, 23));
ASSERT(clamp(20, 20, 23));
}
void test_get_r(TestObjs *objs) {
ASSERT(get_r(0x000000ff) == 0x00);
ASSERT(get_r(0x800080ef) == 0x80);
ASSERT(get_r(0x9cadc1ac) == 0x9c);
ASSERT(get_r(0xefeae2ee) == 0xef);
ASSERT(get_r(0x10000034) == 0x10);
ASSERT(get_r(0x264c80b6) == 0x26);
ASSERT(get_r(0x314e907a) == 0x31);
}
void test_get_g(TestObjs *objs) {
ASSERT(get_g(0x000000ff) == 0x00);
ASSERT(get_g(0x806d80ef) == 0x6d);
ASSERT(get_g(0x9cadc1ac) == 0xad);
ASSERT(get_g(0xefeae2ee) == 0xea);
ASSERT(get_g(0x10ff0034) == 0xff);
ASSERT(get_g(0x264c80b6) == 0x4c);
ASSERT(get_g(0x314e907a) == 0x4e);
ASSERT(get_g(0x000000ff) == 0x00);
}
void test_get_b(TestObjs *objs) {
ASSERT(get_b(0x000000ff) == 0x00);
ASSERT(get_b(0x800080ef) == 0x80);
ASSERT(get_b(0x9cadc1ac) == 0xc1);
ASSERT(get_b(0xefeae2ee) == 0xe2);
ASSERT(get_b(0x10006d34) == 0x6d);
ASSERT(get_b(0x264cffb6) == 0xff);
ASSERT(get_b(0x314e907a) == 0x90);
}
void test_get_a(TestObjs *objs) {
ASSERT(get_a(0x80008000) == 0x00);
ASSERT(get_a(0x000000ff) == 0xff);
ASSERT(get_a(0x9cadc1ac) == 0xac);
ASSERT(get_a(0xefeae2ee) == 0xee);
ASSERT(get_a(0x10000034) == 0x34);
ASSERT(get_a(0x264c80b6) == 0xb6);
ASSERT(get_a(0x314e907a) == 0x7a);
}
void test_blend_components(TestObjs *objs) {
ASSERT(blend_components(0xff, 0xff, 0xff) == 0xff);
ASSERT(blend_components(0x00, 0x00, 0x00) == 0x00);
ASSERT(blend_components(0xfa, 0xb6, 0x24) == 0xbf);
ASSERT(blend_components(0x73, 0xab, 0xc9) == 0x7e);
}
void test_blend_colors(TestObjs *objs) {
ASSERT(blend_colors(0x00000000, 0x00000000) == 0x000000ff);
ASSERT(blend_colors(0xffffffff, 0xffffffff) == 0xffffffff);
ASSERT(blend_colors(0xfab624bf, 0x73abc97e) == 0xd8b34dff);
ASSERT(blend_colors(0x01234567, 0x76543210) == 0x464039ff);
ASSERT(blend_colors(0x0079acb3, 0x2154eef0) == 0x096dbfff);
}
void test_set_pixel(TestObjs *objs) {
// initially objs->small pixels are opaque black
ASSERT(objs->small.data[SMALL_IDX(3, 2)] == 0x000000FFU);
ASSERT(objs->small.data[SMALL_IDX(5, 4)] == 0x000000FFU);
// test drawing completely opaque pixels
set_pixel(&objs->small, 19, 0xFF0000FF); // opaque red
ASSERT(objs->small.data[SMALL_IDX(3, 2)] == 0xFF0000FF);
set_pixel(&objs->small, 37, 0x800080FF); // opaque magenta (half-intensity)
ASSERT(objs->small.data[SMALL_IDX(5, 4)] == 0x800080FF);
set_pixel(&objs->small, 19, 0x00FF0080); // half-opaque full-intensity green
// test color blending
ASSERT(objs->small.data[SMALL_IDX(3, 2)] == 0x7F8000FF);
set_pixel(&objs->small, 20, 0x0000FF40); // 1/4-opaque full-intensity blue
ASSERT(objs->small.data[SMALL_IDX(4, 2)] == 0x000040FF);
}
void test_square(TestObjs *objs) {
ASSERT(square(2) == 4);
ASSERT(square(0) == 0);
ASSERT(square(9) == 81);
ASSERT(square(100) == 10000);
ASSERT(square(1) == 1);
}
void test_square_dist(TestObjs *objs) {
ASSERT(square_dist(0, 0, 0, 0) == 0);
ASSERT(square_dist(2, 3, 7, 6) == 34);
ASSERT(square_dist(10, 2, 0, 4) == 104);
ASSERT(square_dist(20, 19, 24, 7) == 160);
ASSERT(square_dist(5, 7, 5, 6) == 1);
}
void test_draw_pixel(TestObjs *objs) {
// initially objs->small pixels are opaque black
ASSERT(objs->small.data[SMALL_IDX(3, 2)] == 0x000000FFU);
ASSERT(objs->small.data[SMALL_IDX(5, 4)] == 0x000000FFU);
// test drawing completely opaque pixels
draw_pixel(&objs->small, 3, 2, 0xFF0000FF); // opaque red
ASSERT(objs->small.data[SMALL_IDX(3, 2)] == 0xFF0000FF);
draw_pixel(&objs->small, 5, 4, 0x800080FF); // opaque magenta (half-intensity)
ASSERT(objs->small.data[SMALL_IDX(5, 4)] == 0x800080FF);
// test color blending
draw_pixel(&objs->small, 3, 2, 0x00FF0080); // half-opaque full-intensity green
ASSERT(objs->small.data[SMALL_IDX(3, 2)] == 0x7F8000FF);
draw_pixel(&objs->small, 4, 2, 0x0000FF40); // 1/4-opaque full-intensity blue
ASSERT(objs->small.data[SMALL_IDX(4, 2)] == 0x000040FF);
}
void test_draw_rect(TestObjs *objs) {
struct Rect red_rect = { .x = 2, .y = 2, .width=3, .height=3 };
struct Rect blue_rect = { .x = 3, .y = 3, .width=3, .height=3 };
draw_rect(&objs->small, &red_rect, 0xFF0000FF); // red is full-intensity, full opacity
draw_rect(&objs->small, &blue_rect, 0x0000FF80); // blue is full-intensity, half opacity
const uint32_t red = 0xFF0000FF; // expected full red color
const uint32_t blue = 0x000080FF; // expected full blue color
const uint32_t blend = 0x7F0080FF; // expected red/blue blend color
const uint32_t black = 0x000000FF; // expected black (background) color
Picture expected = {
{ {'r', red}, {'b', blue}, {'n', blend}, {' ', black} },
" "
" "
" rrr "
" rnnb "
" rnnb "
" bbb "
};
check_picture(&objs->small, &expected);
}
void test_draw_circle(TestObjs *objs) {
Picture expected = {
{ {' ', 0x000000FF}, {'x', 0x00FF00FF} },
" x "
" xxx "
" xxxxx "
" xxx "
" x "
" "
};
draw_circle(&objs->small, 3, 2, 2, 0x00FF00FF);
check_picture(&objs->small, &expected);
}
void test_draw_circle_clip(TestObjs *objs) {
Picture expected = {
{ {' ', 0x000000FF}, {'x', 0x00FF00FF} },
" xxxxxxx"
" xxxxxxx"
"xxxxxxxx"
" xxxxxxx"
" xxxxxxx"
" xxxxx "
};
draw_circle(&objs->small, 4, 2, 4, 0x00FF00FF);
check_picture(&objs->small, &expected);
}
void test_draw_tile(TestObjs *objs) {
/*
ASSERT(read_image("img/PrtMimi.png", &objs->tilemap) == IMG_SUCCESS);
struct Rect r = { .x = 4, .y = 2, .width = 16, .height = 18 };
draw_rect(&objs->large, &r, 0x1020D0FF);
struct Rect grass = { .x = 0, .y = 16, .width = 16, .height = 16 };
draw_tile(&objs->large, 3, 2, &objs->tilemap, &grass);
Picture pic = {
{
{ ' ', 0x000000ff },
{ 'a', 0x52ad52ff },
{ 'b', 0x1020d0ff },
{ 'c', 0x257b4aff },
{ 'd', 0x0c523aff },
},
" "
" "
" a b "
" a b "
" a ab "
" ac b "
" ac a b "
" a a ad a b "
" a a aad aa ab "
" a a acd aaacab "
" aa cdacdaddaadb "
" aa cdaddaaddadb "
" da ccaddcaddadb "
" adcaacdaddddcadb "
" aaccacadcaddccaab "
" aacdacddcaadcaaab "
" aaaddddaddaccaacb "
" aaacddcaadacaaadb "
" bbbbbbbbbbbbbbbb "
" bbbbbbbbbbbbbbbb "
};
check_picture(&objs->large, &pic);
*/
}
void test_draw_sprite(TestObjs *objs) {
/*
ASSERT(read_image("img/NpcGuest.png", &objs->spritemap) == IMG_SUCCESS);
struct Rect r = { .x = 1, .y = 1, .width = 14, .height = 14 };
draw_rect(&objs->large, &r, 0x800080FF);
struct Rect sue = { .x = 128, .y = 136, .width = 16, .height = 15 };
draw_sprite(&objs->large, 4, 2, &objs->spritemap, &sue);
Picture pic = {
{
{ ' ', 0x000000ff },
{ 'a', 0x800080ff },
{ 'b', 0x9cadc1ff },
{ 'c', 0xefeae2ff },
{ 'd', 0x100000ff },
{ 'e', 0x264c80ff },
{ 'f', 0x314e90ff },
},
" "
" aaaaaaaaaaaaaa "
" aaaaaaaaaaaaaa "
" aaaaaaaaaaaaaa "
" aaaaaaabccccccbc "
" aaaaacccccccccccc "
" aaaacbddcccddcbccc "
" aaacbbbeccccedbccc "
" aaacbbceccccebbbccc "
" aaabbbccccccccbbccc "
" aaaabbbcccccccb ccb "
" aaaabaaaaabbaa cb "
" aaaaaaaaafffea "
" aaaaaaaaaffeea "
" aaaaaaacffffcc "
" cffffccb "
" bbbbbbb "
" "
" "
" "
};
check_picture(&objs->large, &pic);
*/
} |
/*
* This file is part of CELADRO_3D, Copyright (C) 2019-2021, Siavash Monfared
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "header.hpp"
#include "model.hpp"
#ifdef DEBUG
#include <fenv.h>
#endif
using namespace std;
/** pure eyecandy */
string title = R"(
░█████╗░███████╗██╗░░░░░░█████╗░██████╗░██████╗░░█████╗░░░░░░░██████╗░██████╗░
██╔══██╗██╔════╝██║░░░░░██╔══██╗██╔══██╗██╔══██╗██╔══██╗░░░░░░╚════██╗██╔══██╗
██║░░╚═╝█████╗░░██║░░░░░███████║██║░░██║██████╔╝██║░░██║█████╗░█████╔╝██║░░██║
██║░░██╗██╔══╝░░██║░░░░░██╔══██║██║░░██║██╔══██╗██║░░██║╚════╝░╚═══██╗██║░░██║
╚█████╔╝███████╗███████╗██║░░██║██████╔╝██║░░██║╚█████╔╝░░░░░░██████╔╝██████╔╝
░╚════╝░╚══════╝╚══════╝╚═╝░░╚═╝╚═════╝░╚═╝░░╚═╝░╚════╝░░░░░░░╚═════╝░╚═════╝░
------------------------------------------------------------------------------
Celadro: Cells as active droplets
Romain Mueller (2016-2017) & Siavash Monfared (2020-21)
)";
void Model::Algorithm()
{
// number of steps between two writes
const unsigned streak_length = nsubsteps*ninfo;
for(unsigned t=0; t<nsteps; t+=ninfo)
{
if(!no_write and t>=nstart)
{
const auto start = chrono::steady_clock::now();
try
{
WriteFrame(t);
//Write_COM(t);
//Write_velocities(t);
//Write_forces(t);
//Write_contArea(t);
//Write_Density(t);
}
catch(...) {
cerr << "error" << endl;
throw;
}
write_duration += chrono::steady_clock::now() - start;
}
// some verbose
if(verbose>1) cout << '\n';
if(verbose)
cout << "timesteps t = " << setw(pad) << setfill(' ') << right
<< t << " to "
<< setw(pad) << setfill(' ') << right
<< t+ninfo << endl;
if(verbose>1) cout << string(width, '-') << endl;
// do the computation
for(unsigned s=0; s<streak_length; ++s)
{
// first sweeps produces estimate of values
// subsequent sweeps produce corrected values
for(unsigned i=0; i<=npc; ++i)
Update(i==0);
}
#ifdef _CUDA_ENABLED
// get data from device to host memory
GetFromDevice();
#endif
// runtime stats and checks
try
{
if(runtime_stats and verbose>1) RuntimeStats();
if(runtime_check) RuntimeChecks();
}
catch(const error_msg& e)
{
throw;
}
catch(const warning_msg& e)
{
if(stop_at_warning) throw;
else if(verbose and !no_warning) cerr << "warning: " << e.what() << "\n";
}
}
// finally write final frame
if(!no_write and nsteps>=nstart) WriteFrame(nsteps);
// if(!no_write and nsteps>=nstart) Write_COM(nsteps);
// if(!no_write and nsteps>=nstart) Write_velocities(nsteps);
// if(!no_write and nsteps>=nstart) Write_forces(nsteps);
// if(!no_write and nsteps>=nstart) Write_contArea(nsteps);
// if(!no_write and nsteps>=nstart) Write_Density(nsteps);
}
void Model::Setup(int argc, char **argv)
{
// Setup
if(argc<2) throw error_msg("no argument provided. Type -h for help.");
// parse program options
ParseProgramOptions(argc, argv);
// check that we have a run name
if(runname.empty())
throw error_msg("please specify a file path for this run.");
// print simulation parameters
if(verbose)
{
cout << "Run parameters" << endl;
cout << string(width, '=') << endl;
PrintProgramOptions();
}
// Initialization
if(verbose) cout << endl << "Initialization" << endl << string(width, '=')
<< endl;
// warning and flags
// no output
if(no_write and verbose) cout << "warning: output is not enabled." << endl;
// ----------------------------------------
// model init
if(verbose) cout << "model initialization ..." << flush;
try {
InitializeRandomNumbers();
Initialize();
InitializeNeighbors();
} catch(...) {
if(verbose) cout << " error" << endl;
throw;
}
if(verbose) cout << " done" << endl;
// ----------------------------------------
// parameters init
if(verbose) cout << "system initialisation ..." << flush;
try {
Configure();
ConfigureWalls(BC);
} catch(...) {
if(verbose) cout << " error" << endl;
throw;
}
if(verbose) cout << " done" << endl;
// ----------------------------------------
// multi-threading
#ifdef _OPENMP
if(nthreads)
{
if(verbose) cout << "multi-threading ... " << flush;
SetThreads();
if(verbose) cout << nthreads << " active threads" << endl;
}
#endif
// ----------------------------------------
// cuda, see random numbers section as well
#ifdef _CUDA_ENABLED
if(verbose) cout << "setting up CUDA devices ..." << endl;
QueryDeviceProperties();
InitializeCuda();
if(verbose) cout << "... allocate device memory ...";
AllocDeviceMemory();
if(verbose) cout << " done" << endl;
if(verbose) cout << "... random numbers initialization ..." << flush;
InitializeCUDARandomNumbers();
if(verbose) cout << " done" << endl;
if(verbose) cout << "... copy data to device ...";
PutToDevice();
if(verbose) cout << " done" << endl;
#endif
// ----------------------------------------
// write params to file
if(!no_write)
{
if(verbose) cout << "create output directory " << " ...";
try {
CreateOutputDir();
} catch(...) {
if(verbose) cout << " error" << endl;
throw;
}
if(verbose) cout << " done" << endl;
if(verbose and compress_full)
cout << "create output file " << runname << ".zip ...";
if(verbose and not compress_full)
cout << "write parameters ...";
try {
WriteParams();
} catch(...) {
if(verbose) cout << " error" << endl;
throw;
}
if(verbose) cout << " done" << endl;
}
}
void Model::Run()
{
// preparation
if(verbose) cout << "preparation ... " << flush;
Pre();
if(verbose) cout << " done" << endl;
if(verbose) cout << endl << "Run" << endl << string(width, '=') << "\n\n";
// print some stats
PreRunStats();
// record starting time
const auto start = chrono::steady_clock::now();
// run the thing
Algorithm();
// record end time
const auto duration = chrono::steady_clock::now() - start;
if(verbose) cout << "post-processing ... " << flush;
Post();
if(verbose) cout << "done" << endl;
if(verbose)
{
cout << endl << "Statistics" << endl << string(width, '=') << endl;
cout << "Total run time : "
<< chrono::duration_cast<chrono::milliseconds>(duration).count()
/1000. << " s" << endl;
cout << "Total time spent writing output : "
<< chrono::duration_cast<chrono::milliseconds>(write_duration).count()
/1000. << " s" << endl;
}
}
void Model::Cleanup()
{
#ifdef _CUDA_ENABLED
FreeDeviceMemory();
#endif
}
/** Program entry */
int main(int argc, char **argv)
{
// if in debug mode, catch all arithmetic exceptions
#ifdef DEBUG
feenableexcept(FE_INVALID | FE_OVERFLOW);
#endif
// print that beautiful title
cout << title << endl;
// do the job
try {
Model model;
model.Setup(argc, argv);
model.Run();
model.Cleanup();
}
// custom small messages
catch(const error_msg& e) {
cerr << argv[0] << ": error: " << e.what() << endl;
return 1;
}
// bad alloc (possibly from memory())
catch(const bad_alloc& ba) {
cerr << argv[0] << ": error initializing memory: " << ba.what() << endl;
return 1;
}
// all the rest (mainly from boost)
catch(const exception& e) {
cerr << argv[0] << ": " << e.what() << endl;
return 1;
}
return 0;
} |
/* Home Arduino System v1.0
* learnelectronics
* 01-02-2017
*/
//---------------------------------------------------------------------------------
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);
#define NUMFLAKES 10
#define XPOS 0
#define YPOS 1
#define DELTAY 2
#define LOGO16_GLCD_HEIGHT 16
#define LOGO16_GLCD_WIDTH 16
static const unsigned char PROGMEM logo16_glcd_bmp[] =
{ B00000000, B11000000,
B00000001, B11000000,
B00000001, B11000000,
B00000011, B11100000,
B11110011, B11100000,
B11111110, B11111000,
B01111110, B11111111,
B00110011, B10011111,
B00011111, B11111100,
B00001101, B01110000,
B00011011, B10100000,
B00111111, B11100000,
B00111111, B11110000,
B01111100, B11110000,
B01110000, B01110000,
B00000000, B00110000 };
#define safeLED 2 //green LED for not triggered
#define alertLED 3 //red LED for when alarm is triggered
#define buzzer 4 // buzzer for alarm
#define ldr A0 //Light Dependent Resistor
#define flameAlarm A2
int ldrValue = 0; //Value for LDR
int flameSensor = 0;
int alarmState = 0; //State of Alarm
//----------------------------------------------------------------------------------
void setup() {
pinMode(safeLED, OUTPUT); // Set green LED to OUTPUT
pinMode(alertLED, OUTPUT); // Set red LED to OUTPUT
pinMode(buzzer, OUTPUT); // Set buzzer to OUTPUT
Serial.begin(9600); // turn on serial comms
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.display();
digitalWrite(safeLED,HIGH); // turn on SAFE LED
delay(2000); // delay to arm
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
display.println("System Armed");
display.display();
}
//----------------------------------------------------------------------------------
void alarm(){ //ALARM FUNCTION
alarmState = 1; // set alarm state to 1
digitalWrite(alertLED, HIGH); // turn alert LED on
digitalWrite(safeLED,LOW); // turn safe LED off
tone(buzzer,3000,1000); // make anoying sound
delay(500);
tone(buzzer,1000,1000);
delay(500);
}
//----------------------------------------------------------------------------------
void loop() {
if(alarmState == 1){ //check alarm state, if 1, alarm has been triggered
alarm(); // so keep sounding the alarm
}
ldrValue = analogRead(ldr); //get LDR vale
Serial.print("LDR value ");
Serial.println(ldrValue); // for debugging
if(ldrValue > 100){ // threshold for alarm
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
display.println("LASER Tripped");
display.display();
alarm(); //sound alarm
}
else{
digitalWrite(safeLED,HIGH); // if all is well, re-run the loop
}
flameSensor = analogRead(A2);
Serial.print("Flame value ");
Serial.println(flameSensor);
if(flameSensor <100){
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
display.println("Flame Detected");
display.display();
alarm();
}
else{
digitalWrite(safeLED,HIGH); // if all is well, re-run the loop
}
} |
import React, { useState } from "react";
function TodoList({ todos, updateTodo }) {
const [active, setActive] = useState("");
const [filtered, setFiltered] = useState(todos);
const handleDelete = (name) => {
const updatedTodo = todos.filter((todo) => todo.name !== name);
console.log("deleted", name, updatedTodo);
updateTodo(updatedTodo);
setFiltered(updatedTodo);
};
const handleFinished = (name) => {
const updatedTodo = todos.map((todo) =>
todo.name === name ? { ...todo, finished: !todo.finished } : todo
);
console.log("finished:", name, updatedTodo);
updateTodo(updatedTodo);
setFiltered(updatedTodo);
};
const handleFilters = (e) => {
const filterType = e.target.name;
switch (filterType) {
case "all":
setFiltered(todos);
break;
case "active":
setFiltered(todos.filter((todo) => todo.finished === false));
break;
case "finished":
setFiltered(todos.filter((todo) => todo.finished === true));
break;
default:
setFiltered(todos);
break;
}
setActive(filterType);
};
const handleToggleAll = () => {
const updatedTodo = todos.map((todo) => ({
...todo,
finished: true,
}));
updateTodo([...updatedTodo]);
setFiltered([...updatedTodo]);
};
const handleClearFinished = () =>{
const updatedTodo = todos.filter((todo) => todo.finished !== true);
updateTodo(updatedTodo)
setFiltered(updatedTodo);
}
const unfinished = todos.filter((todo) => !todo.finished);
return (
<div>
<input
type="checkbox"
id="toggleAll"
onClick={() => handleToggleAll()}
/>
<label htmlFor="toggleAll">Mark all as complete</label>
<ul className="list">
{filtered.map((todo, k) => (
<li key={k}>
<span
className={`btn btn-check ${todo.finished ? "" : ""}`}
onClick={() => handleFinished(todo.name)}
>
Done
</span>
<span className={`todo_name ${todo.finished ? "finished" : ""}`}>
{todo.name}
</span>
<span
className="btn btn-delete"
onClick={() => handleDelete(todo.name)}
>
X
</span>
</li>
))}
</ul>
<div className="card-footer">
<span className="">Todos left: {unfinished.length}</span>
<div className="filters">
<button
className={`btn btn-filter ${active === "all" ? "active" : ""}`}
name="all"
onClick={handleFilters}
>
All
</button>
<button
className={`btn btn-filter ${active === "active" ? "active" : ""}`}
name="active"
onClick={handleFilters}
>
Active
</button>
<button
className={`btn btn-filter ${
active === "finished" ? "active" : ""
}`}
name="finished"
onClick={handleFilters}
>
Finished
</button>
</div>
<span className="" onClick={() => handleClearFinished()}>Clear completed</span>
</div>
</div>
);
}
export default TodoList; |
<script lang="ts">
import BaseTextInputVue from "@/components/BaseTextInput.vue";
import BaseButtonVue from "@/components/BaseButton.vue";
import { defineComponent } from "vue";
import Spinner from "@/components/Spinner.vue";
import { useAuthStore } from "@/stores/auth";
import { mapActions, mapState } from "pinia";
import SocialAccountAuth from "@/components/SocialAccountAuth.vue";
export default defineComponent({
name: "AuthView",
components: {
BaseTextInput: BaseTextInputVue,
BaseButton: BaseButtonVue,
Spinner,
SocialAccountAuth,
},
data: () => ({
form: {
email: "",
password: "",
},
//destructure the api response into this variable
apiResponse: {
message: "",
token: "",
},
}),
mounted() {
/**
* check if the user is already logged in and the token is still valid
* if true, go straight to the dashboard, else, stay on the login page
* once on the dashboard, make request for refresh token.
*/
if (this.authorizationToken) {
this.getUserInformation(this.authorizationToken);
// router.push({ name: "home" });
}
},
computed: {
...mapState(useAuthStore, ["isLoading", "apiError", "authorizationToken"]),
//disabled state
disabledState() {
return this.isLoading === true ? true : false;
},
},
methods: {
//import the methods from store
...mapActions(useAuthStore, {
makeLoginRequest: "loginRequest",
getUserInformation: "getUserInformation",
}),
//exec the login action coming from the store mapped actions
login() {
this.makeLoginRequest(this.form);
// this.$router.push({ name: "home" });
},
//go to home, debug only
goToHome() {
this.$router.push({ name: "home" });
},
},
});
</script>
<template>
<div id="login__page">
<div class="container">
<!--bg-->
<div></div>
<!--logon form-->
<div>
<div class="title">
<h1>Login</h1>
<p class="sub__hero__text">Please provide your Credentials.</p>
</div>
<!--social login buttons-->
<SocialAccountAuth class="d-none" />
<!-- <GoogleLogin :callback="callback" /> -->
<form action="" method="post" @submit.prevent="login">
<!--form field email-->
<BaseTextInput
placeholder="example@mailer.com"
label="email"
v-model="form.email"
type="email"
class="field"
/>
<!--form field password-->
<BaseTextInput
placeholder="password"
type="password"
label="password"
class="field"
v-model="form.password"
:reset-password="false"
/>
<!--form field submit, change color to black while waiting for response from server-->
<BaseButton text="" :disabled="disabledState">
<span v-show="!isLoading">Login</span>
<Spinner
:animation-duration="1000"
:size="30"
:color="'#ffffff'"
v-show="isLoading"
/>
</BaseButton>
</form>
<!--custom install script-->
<!-- Install button, hidden by default -->
<small class="goto__page">
Don't have an account?
<RouterLink
:to="{ name: 'sign-up' }"
class="emphasis"
style="font-size: 13px"
>Sign up
</RouterLink>
</small>
<small class="goto__page">
<RouterLink
:to="{ name: 'forgotten-password' }"
class="emphasis"
style="font-size: 13px"
>Forgotten password?
</RouterLink>
</small>
</div>
</div>
</div>
</template>
<style scoped>
.hidden {
display: none !important;
}
.goto__page {
/* font-size: 0.95rem; */
margin-top: 10px;
color: var(--secondary);
text-align: left !important;
display: block;
/* display: none; */
}
.goto__page:first-child {
margin-top: 120px;
}
.goto__sign__up a {
font-size: inherit !important;
text-decoration: none;
}
#login__page .container {
width: 100%;
display: grid;
grid-template-columns: 1fr 1.2fr;
column-gap: 100px;
grid-template-rows: 1fr;
grid-template-areas: "bg form";
min-height: 100vh;
position: relative;
}
/**the background container */
#login__page .container > div:first-child {
background-image: url("@/assets/img/bg/login-bg.svg");
background-size: cover;
background-position: center center;
}
#login__page .container > div:last-child {
padding: 100px 0;
display: flex;
flex-direction: column;
justify-content: center;
align-content: center;
}
#login__page .container > div:last-child h1 + small {
margin-bottom: 30px;
}
input,
button,
.form__field input,
.field {
width: 500px;
}
#login__page .title {
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: center;
margin-bottom: 35px;
}
#login__page .title h1 {
font-style: normal;
font-weight: 500;
font-size: 24px;
line-height: 30px;
}
#login__page .title p {
align-items: center;
justify-content: center;
line-height: 28px;
color: var(--secondary);
margin-top: 3px;
}
/** -----------------------------small devices------------------------ */
@media screen and (max-width: 768px) {
#login__page .container {
display: block;
grid-template-columns: 1fr;
grid-template-rows: 1fr 1fr;
grid-template-areas: "bg" "form";
justify-content: center;
align-items: center;
margin: 0;
padding: 0;
}
#login__page .container > div:first-child {
display: none;
}
#login__page .container > div:last-child {
padding: 50px 30px;
display: flex;
flex-direction: column;
justify-content: center;
align-content: center;
/* padding: 0 30px; */
place-content: center;
/* place-items: center; */
min-height: 90vh;
/* margin: 20px auto; */
}
#login__page .container > div:last-child h1 + small.error {
margin-bottom: 35px;
}
#login__page .container div:last-child form {
display: flex;
flex-direction: column;
justify-content: center;
align-content: center;
margin-bottom: 10px;
column-gap: 15px;
margin-top: .75rem;
}
.form__field,
button {
width: auto;
margin-top: 15px;
}
#login__page .form__field {
margin-bottom: 15px;
}
}
</style> |
package com.example.fbaseauth
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
class LoginActivity : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
auth = Firebase.auth
val registertext: TextView = findViewById(R.id.textView_register_now)
registertext.setOnClickListener {
val intent = Intent(this, RegisterActivity::class.java)
startActivity(intent)
}
val loginButton: Button = findViewById(R.id.btn_login)
loginButton.setOnClickListener {
performLogin()
}
}
private fun performLogin() {
val email: EditText = findViewById(R.id.editText_email_login)
val password: EditText = findViewById(R.id.editText_password_login)
if (email.text.isEmpty() || password.text.isEmpty()) {
Toast.makeText(this, "username & passoword kosong", Toast.LENGTH_SHORT)
.show()
return
}
val emailInput = email.text.toString()
val passwordInput = password.text.toString()
auth.signInWithEmailAndPassword(emailInput, passwordInput)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
// Log.d(TAG, "signInWithEmail:success")
// val user = auth.currentUser
// updateUI(user)
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
Toast.makeText(
baseContext,
"Authentication success.",
Toast.LENGTH_SHORT,
).show()
} else {
// If sign in fails, display a message to the user.
// Log.w(TAG, "signInWithEmail:failure", task.exception)
Toast.makeText(
baseContext,
"Authentication failed.",
Toast.LENGTH_SHORT,
).show()
// updateUI(null)
}
}
.addOnFailureListener {
Toast.makeText(this, "Error", Toast.LENGTH_SHORT)
.show()
}
}
} |
from __future__ import division
from __future__ import print_function
from torch_geometric.utils import convert
import time
import argparse
import numpy as np
import torch
import torch.nn.functional as F
import torch.optim as optim
from utils import load_bail, load_income, load_pokec_renewed
from GNNs import GCN, GAT, SAGE
from scipy.stats import wasserstein_distance
from tqdm import tqdm
# from influence_computation_and_save_2 import part2
# from removing_and_testing_3 import part3
# from debiasing_gnns import part4
import optuna
import csv
# /home/joyce/BIND_2/implementations/2_influence_computation_and_save.py
import warnings
warnings.filterwarnings('ignore')
# Training settings
parser = argparse.ArgumentParser()
parser.add_argument('--no-cuda', action='store_true', default=False,
help='Disables CUDA training.')
parser.add_argument('--fastmode', action='store_true', default=False,
help='Validate during training pass.')
parser.add_argument('--model', type=str, default='gcn')
parser.add_argument('--seed', type=int, default=1)
parser.add_argument('--epochs', type=int, default=1000,
help='Number of epochs to train.')
parser.add_argument('--dataset', type=str, default="income", help='One dataset from income, bail, pokec1, and pokec2.')
parser.add_argument('--lr', type=float, default=0.001)
parser.add_argument('--weight_decay', type=float, default=0.0001)
parser.add_argument('--hidden', type=int, default=16)
parser.add_argument('--dropout', type=float, default=0.5)
parser.add_argument('--ap', type=float, default=25)
args = parser.parse_args()
args.cuda = not args.no_cuda and torch.cuda.is_available()
dataset_name = args.dataset
# args.seed = 1
def feature_norm(features):
min_values = features.min(axis=0)[0]
max_values = features.max(axis=0)[0]
return 2*(features - min_values).div(max_values-min_values) - 1
def part1(dataset,
pnum_hidden,
pdropout,
plr,
pweight_decay,
epochs,
model, pseed):
dataset_name = dataset
args.hidden = pnum_hidden
args.lr = plr
args.dropout = pdropout
args.weight_decay = pweight_decay
args.epoch = epochs
args.model = model
seed = pseed
args.seed = pseed
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.cuda:
torch.cuda.manual_seed(args.seed)
if dataset_name == 'bail':
adj, features, labels, idx_train, idx_val, idx_test, sens = load_bail('bail', args.seed)
norm_features = feature_norm(features)
norm_features[:, 0] = features[:, 0]
features = feature_norm(features)
elif dataset_name == 'income':
adj, features, labels, idx_train, idx_val, idx_test, sens = load_income('income', args.seed)
norm_features = feature_norm(features)
norm_features[:, 8] = features[:, 8]
features = feature_norm(features)
elif dataset_name == 'pokec1':
adj, features, labels, idx_train, idx_val, idx_test, sens = load_pokec_renewed(1, args.seed)
elif dataset_name == 'pokec2':
adj, features, labels, idx_train, idx_val, idx_test, sens = load_pokec_renewed(2, args.seed)
if dataset_name == 'nba':
adj, features, labels, idx_train, idx_val, idx_test, sens = load_pokec_renewed(2, args.seed)
edge_index = convert.from_scipy_sparse_matrix(adj)[0]
if args.model == "gcn":
model = GCN(nfeat=features.shape[1], nhid=args.hidden, nclass=labels.unique().shape[0]-1, dropout=args.dropout)
elif args.model == "gat":
model = GAT(nfeat=features.shape[1], nhid=args.hidden, nclass=labels.unique().shape[0]-1, dropout=args.dropout)
elif args.model == "sage":
model = SAGE(nfeat=features.shape[1], nhid=args.hidden, nclass=labels.unique().shape[0]-1, dropout=args.dropout)
optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)
if args.cuda:
model.cuda()
features = features.cuda()
edge_index = edge_index.cuda()
labels = labels.cuda()
idx_train = idx_train.cuda()
idx_val = idx_val.cuda()
idx_test = idx_test.cuda()
def accuracy_new(output, labels):
correct = output.eq(labels).double()
correct = correct.sum()
return correct / len(labels)
def fair_metric(pred, labels, sens):
idx_s0 = sens==0
idx_s1 = sens==1
idx_s0_y1 = np.bitwise_and(idx_s0, labels==1)
idx_s1_y1 = np.bitwise_and(idx_s1, labels==1)
parity = abs(sum(pred[idx_s0])/sum(idx_s0)-sum(pred[idx_s1])/sum(idx_s1))
equality = abs(sum(pred[idx_s0_y1])/sum(idx_s0_y1)-sum(pred[idx_s1_y1])/sum(idx_s1_y1))
return parity.item(), equality.item()
def train(epoch):
t = time.time()
model.train()
optimizer.zero_grad()
output = model(features, edge_index)
loss_train = F.binary_cross_entropy_with_logits(output[idx_train], labels[idx_train].unsqueeze(1).float())
preds = (output.squeeze() > 0).type_as(labels)
acc_train = accuracy_new(preds[idx_train], labels[idx_train])
loss_train.backward()
optimizer.step()
if not args.fastmode:
model.eval()
output = model(features, edge_index)
loss_val = F.binary_cross_entropy_with_logits(output[idx_val], labels[idx_val].unsqueeze(1).float())
acc_val = accuracy_new(preds[idx_val], labels[idx_val])
return loss_val.item()
def tst():
model.eval()
output = model(features, edge_index)
preds = (output.squeeze() > 0).type_as(labels)
loss_test = F.binary_cross_entropy_with_logits(output[idx_test], labels[idx_test].unsqueeze(1).float())
acc_test = accuracy_new(preds[idx_test], labels[idx_test])
print("***************** Cost ********************")
print("SP cost:")
idx_sens_test = sens[idx_test]
idx_output_test = output[idx_test]
print(wasserstein_distance(idx_output_test[idx_sens_test==0].squeeze().cpu().detach().numpy(), idx_output_test[idx_sens_test==1].squeeze().cpu().detach().numpy()))
print("EO cost:")
idx_sens_test = sens[idx_test][labels[idx_test]==1]
idx_output_test = output[idx_test][labels[idx_test]==1]
print(wasserstein_distance(idx_output_test[idx_sens_test==0].squeeze().cpu().detach().numpy(), idx_output_test[idx_sens_test==1].squeeze().cpu().detach().numpy()))
print("**********************************************")
parity, equality = fair_metric(preds[idx_test].cpu().numpy(), labels[idx_test].cpu().numpy(),
sens[idx_test].cpu().numpy())
print("Test set results:",
"loss= {:.4f}".format(loss_test.item()),
"accuracy= {:.4f}".format(acc_test.item()))
print("Statistical Parity: " + str(parity))
print("Equality: " + str(equality))
t_total = time.time()
final_epochs = 0
loss_val_global = 1e10
starting = time.time()
for epoch in tqdm(range(args.epochs)):
loss_mid = train(epoch)
if loss_mid < loss_val_global:
loss_val_global = loss_mid
torch.save(model, str(args.model) + '_' + dataset_name + '_' + str(args.seed) + '.pth')
final_epochs = epoch
torch.save(model, str(args.model) + '_' + dataset_name + '_' + str(args.seed) + '.pth')
ending = time.time()
print("Time:", ending - starting, "s")
model = torch.load(str(args.model) + '_' + dataset_name + '_' + str(args.seed) + '.pth')
print("ERROR FIX: ", model)
tst() |
/*
** client.c -- a stream socket client demo
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <pthread.h>
#include <arpa/inet.h>
#define PORT "3490" // the port client will be connecting to
#define MAXDATASIZE 2048 // max number of bytes we can get at once
// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
void *recv_messages(void *vargp) {
//recv in thread
while (1)
{
int sockfd = *((int *)vargp);
char *buf = (char *)malloc(MAXDATASIZE);
if(recv(sockfd, buf, MAXDATASIZE, 0) == -1) {
perror("recv");
exit(1);
}
//if buf starts with OUTPUT, print the rest of the string
if (strncmp(buf, "OUTPUT", 6) == 0) {
printf("\n%s\n", buf);
}
}
return NULL;
}
int main(int argc, char *argv[])
{
int sockfd;
char buf[MAXDATASIZE];
struct addrinfo hints, *servinfo, *p;
int rv;
char s[INET6_ADDRSTRLEN];
if (argc != 2) {
fprintf(stderr,"usage: client hostname\n");
exit(1);
}
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo(argv[1], PORT, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and connect to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("client: socket");
continue;
}
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("client: connect");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "client: failed to connect\n");
return 2;
}
inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),
s, sizeof s);
printf("client: connecting to %s\n", s);
freeaddrinfo(servinfo); // all done with this structure
//start recv thread
pthread_t thread;
int *sockfd_ptr = (int *)malloc(sizeof(int));
*sockfd_ptr = sockfd;
pthread_create(&thread, NULL, recv_messages, (void *)sockfd_ptr);
//send input to server
while(1) {
printf("client: enter message to send to server: ");
memset(buf, 0, MAXDATASIZE);
fgets(buf, MAXDATASIZE, stdin);
if (send(sockfd, buf, strlen(buf), 0) == -1) {
perror("send");
exit(1);
}
//receive message from server to a thread
}
close(sockfd);
return 0;
} |
<%= render partial: 'layouts/page_header', locals: {ransack_q: @ransack_q, user_cart_product_num: @user_cart_product_num} %>
<%# 標題區 %>
<div class="flex items-center w-full rounded bg-marche_orange sm:mx-auto sm:w-10/12 mt-36">
<%# 標題 %>
<div class="w-10 my-2 ml-2 mr-4 border rounded-full">
<%= logo(@shop, size: [80, 80]) %>
</div>
<h1 class="py-2 text-xl font-bold text-gray-50"><%= @shop.name %></h1>
</div>
<div class="w-full px-2 py-4 border-b-2 sm:mx-auto sm:w-10/12"><%= @shop.description %></div>
<%# 分類區 %>
<div class="flex w-full mx-auto sm:w-10/12">
<div class="flex flex-col my-4 ml-2 w-30 sm:ml-0">
<p class="p-1 font-bold">分類</p>
<span class="h-px w-28 bg-marche_pearl"></span>
<ul>
<li>
<%= link_to '所有商品', shop_path, class: "p-1 mr-4 text-sm border-b cursor-pointer w-24 sm:w-28 hover:bg-marche_pearl block" %>
</li>
<%= render partial:'shops/category_list', collection: @sub_categories, as: :sub_category %>
</ul>
</div>
<%# 商品區 %>
<section class="w-full pb-20">
<%# 上方篩選器 %>
<div class="flex items-center justify-center p-2 mx-auto my-4 border bg-marche_white">
<span class="px-2 py-1 mx-1 text-xs sm:px-4 sm:text-base sm:mx-2">篩選</span>
<%= form_with url: shop_path, method: :get, data:{ controller: 'shop--product' } do %>
<%= hidden_field_tag :category, params[:category] %>
<%= select_tag :sort, options_for_select([
['創建時間 (最新)', 'new'],
['價格 (由高到低)', 'price_high'],
['價格 (由低到高)', 'price_low']
], params[:sort]),
class:"max-w-xs ml-2 w-36 sm:w-44 select select-bordered",
data: { action: 'change->shop--product#submitOnChange' }%>
<% end %>
</div>
<%# 商品顯示區 %>
<div class="grid grid-cols-2 gap-4 mx-auto sm:grid-cols-3 lg:grid-cols-5 md:grid-cols-4 xl:grid-cols-6">
<%= render partial:'products/product',collection: @products, as: :product %>
</div>
</section>
</div> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.