text
stringlengths
184
4.48M
import torch import torch.nn as nn # define the CNN architecture class MyModel(nn.Module): def __init__(self, num_classes: int = 1000, dropout: float = 0.5): super().__init__() self.features = nn.Sequential( nn.Conv2d(3, 64, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.BatchNorm2d(64), # Batch normalization after activation nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(64, 128, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.BatchNorm2d(128), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(128, 256, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.BatchNorm2d(256), nn.MaxPool2d(kernel_size=2, stride=2) ) self.avgpool = nn.AdaptiveAvgPool2d((7, 7)) self.classifier = nn.Sequential( nn.Linear(256 * 7 * 7, 512), nn.ReLU(inplace=True), nn.Dropout(p=dropout), nn.Linear(512, num_classes) ) def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.features(x) x = self.avgpool(x) x = x.view(x.size(0), -1) x = self.classifier(x) return x ###################################################################################### # TESTS ###################################################################################### import pytest @pytest.fixture(scope="session") def data_loaders(): from .data import get_data_loaders return get_data_loaders(batch_size=2) def test_model_construction(data_loaders): model = MyModel(num_classes=23, dropout=0.3) dataiter = iter(data_loaders["train"]) images, labels = dataiter.next() out = model(images) assert isinstance( out, torch.Tensor ), "The output of the .forward method should be a Tensor of size ([batch_size], [n_classes])" assert out.shape == torch.Size( [2, 23] ), f"Expected an output tensor of size (2, 23), got {out.shape}"
<!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"/> <meta content="width=device-width, initial-scale=1, shrink-to-fit=no" name="viewport" /> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous"> <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700&display=swap" rel="stylesheet"> <style> body { font-family: Montserrat !important; } h1, label { font-weight: bold; } .form-control { border: 2px solid #1c154a; } .form-control:focus { border: 2px solid #1c154a; outline: black !important; box-shadow: 2px 3px 4px black; } .bolder tr, th { font-weight: bold; } .orange { color: #d9644d; } h1 { color: #1c154a; } .btn-dark, .btn-dark:focus, .btn-dark:hover { background-color: #1c154a; font-weight: 300; } .tracking-in-expand { -webkit-animation: tracking-in-expand 0.7s cubic-bezier(0.215, 0.610, 0.355, 1.000) both; animation: tracking-in-expand 0.7s cubic-bezier(0.215, 0.610, 0.355, 1.000) both; } @-webkit-keyframes tracking-in-expand { 0% { letter-spacing: -0.5em; opacity: 0; } 40% { opacity: 0.6; } 100% { opacity: 1; } } @keyframes tracking-in-expand { 0% { letter-spacing: -0.5em; opacity: 0; } 40% { opacity: 0.6; } 100% { opacity: 1; } } </style> <title>Lease Calculator</title> </head> <body> <div class="container"> <h1 style="text-align: center;font-weight: bold"><span class="orange">Lease </span> Calculator</h1> <div class="row mt-2"> <div class="col-md-6 col-sm-12 mb-3"> <div class="card"> <div class="card-body pb-0"> <table class="table"> <thead> <tr> <h1 class="text-center bold"><span class="orange">Enter </span> Information</h1> </tr> </thead> <tbody> <tr> <td><label for="equipmentAmount">Equipment Amount </label></td> <td><input class="form-control" id="equipmentAmount" name="" onkeyup="format(this)" placeholder="e.g 10000" type="text" value="50,000"/></td> </tr> <tr> <td><label for="months">How Many Months? </label></td> <td><input class="form-control" id="months" name="" onkeyup="format(this)" placeholder="e.g 1000" type="text" value="60"/></td> </tr> <tr style="display: none"> <td><label for="interestRate">Annual Interest Rate </label></td> <td><input class="form-control" id="interestRate" type="number" value="8.50"/></td> </tr> <tr style="display: none"> <td><label for="brokerFee"> Broker Fee</label></td> <td><input class="form-control" id="brokerFee" type="number" value="4"/></td> </tr> </tbody> </table> <button class="btn mb-2 btn-dark btn-lg float-right" onclick="checkCookie()">Calculate </button> </div> </div> </div> <!-- modal for email and name form--> <div class="col-md-6 col-sm-12 tracking-in-expand" id="result" style="display: none;"> <div class="card"> <div class="card-body pb-0"> <table class="table table-striped"> <thead> <tr> <h1 class="text-center orange">Summary</h1> </tr> </thead> <tbody class="bolder"> <tr> <td>Monthly Payment</td> <td id="monthlyPayment"></td> </tr> <tr> <td>12 Months Tax Write Off</td> <td id="taxWriteOff"></td> </tr> </tbody> </table> </div> </div> </div> </div> <!-- Modal --> <div aria-hidden="true" aria-labelledby="exampleModalCenterTitle" class="modal fade" id="exampleModalCenter" role="dialog" tabindex="-1"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <button aria-label="Close" class="close" data-dismiss="modal" type="button"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <h3>Please fill in your details to continue</h3> <label for="name">Name</label> <input class="form-control" id="name" name="name" type="text"> <label for="email">Email</label> <input class="form-control" id="email" name="email" type="email"> </div> <div class="modal-footer"> <button class="btn btn-secondary" data-dismiss="modal" type="button">Close</button> <button class="btn btn-secondary" onclick="setCookie('existingUser','existingUser')" type="button">Submit!</button> </div> </div> </div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script> <script type="text/javascript"> function setCookie(cname,cvalue) { let name = document.getElementById('name').value; let email = document.getElementById('email').value; if (name == '' || email == '') { alert('Please fill in all the details'); return false; } else{ document.cookie = cname + "=" + cvalue + ";path=/"; checkCookie(); } } function getCookie(cname) { let name = cname + "="; let decodedCookie = decodeURIComponent(document.cookie); let ca = decodedCookie.split(';'); for(let i = 0; i < ca.length; i++) { let c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } function checkCookie() { let user = getCookie("existingUser"); if (user != "") { getResult(); } else { $('#exampleModalCenter').modal('show'); } } function PMT(rate, nper, pv, fv, type) { if (!fv) fv = 0; if (!type) type = 0; if (rate == 0) return -(pv + fv) / nper; var pvif = Math.pow(1 + rate, nper); var pmt = rate / (pvif - 1) * -(pv * pvif + fv); if (type == 1) { pmt /= (1 + rate); } return pmt; } let toComma = (x) => "$ " + x.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); function format(input) { var nStr = input.value + ''; nStr = nStr.replace(/\,/g, ""); x = nStr.split('.'); x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } input.value = x1 + x2; } function getResult() { // show result //close modal $('#exampleModalCenter').modal('hide'); document.getElementById("result").style.display = "block"; let equipmentAmount = parseFloat(document.getElementById("equipmentAmount").value.replace(/,/g, '')); let months = parseFloat(document.getElementById("months").value); let brokerFee = parseFloat(document.getElementById("brokerFee").value); let interestRate = parseFloat(document.getElementById("interestRate").value); let pv = equipmentAmount + (equipmentAmount * (brokerFee / 100)); let result = PMT(interestRate / 100 / 12, months, -pv, 1, 1); let taxWriteOff = result * 12; document.getElementById("result").style.display = "block"; document.getElementById("monthlyPayment").innerHTML = toComma(result); document.getElementById("taxWriteOff").innerHTML = toComma(taxWriteOff); // ajax call $.ajax({ type: "POST", url: "./mail.php", data: { name: name, email: email, equipmentAmount: equipmentAmount, months: months, brokerFee: brokerFee, interestRate: interestRate, result: result, taxWriteOff: taxWriteOff }, success: function (data) { console.log(data); } }); } </script> <script src="./iframeResizer.contentWindow.min.js"></script> </body> </html>
import requests from config import PAYMENTS_PATH, URL class Payments: def __init__(self, selected_project): self.selected_project_id = selected_project self.url_path = f"{URL}/{self.selected_project_id}" def fetch_due_receivable_by_date(self, payment_date): print( f"Retrieving receivables from {self.url_path}{PAYMENTS_PATH}/{payment_date}/receivable" ) receivable = requests.get( f"{self.url_path}{PAYMENTS_PATH}/{payment_date}/receivable" ).json() print(f"Retrieved {receivable}") return receivable def fetch_due_payable_by_date(self, payment_date): print( f"Retrieving payables from {self.url_path}{PAYMENTS_PATH}/{payment_date}/payable" ) payable = requests.get( f"{self.url_path}{PAYMENTS_PATH}/{payment_date}/payable" ).json() print(f"Retrieved {payable}") return payable def fetch_all_payments_by_date(self, payment_date): print( f"Retrieving payments from {self.url_path}{PAYMENTS_PATH}/{payment_date}/all" ) payments = requests.get( f"{self.url_path}{PAYMENTS_PATH}/{payment_date}/all" ).json() print(f"Retrieved {payments}") return payments def solve_payment(self, payment_id, amount, installment_type): print(f"Solving payment for invoice {payment_id}") requests.put( f"{self.url_path}{PAYMENTS_PATH}/{payment_id}/pay", json={"amount": amount, "installment_type": installment_type}, ) def create_payment(self, payment_data): print(f"Creating payment with the following data: {payment_data}") return requests.post(f"{self.url_path}{PAYMENTS_PATH}", json=payment_data) def fetch_available_payment_dates(self): return requests.get(f"{self.url_path}{PAYMENTS_PATH}/available-dates").json() def fetch_payments_journal_by_date(self, payment_date): print( f"Retrieving payments from {self.url_path}{PAYMENTS_PATH}/{payment_date}/payment-journal" ) payments = requests.get( f"{self.url_path}{PAYMENTS_PATH}/{payment_date}/payment-journal" ).json() print(f"Retrieved {payments}") return payments
NB.%microkanren.ijs - a MicroKanren with rank-polymorphic unification NB.-This script is an attempt at a mostly verbatim implementation of [scheme microkanren](https://github.com/jasonhemann/microKanren-DLS-16).\ NB.- NB.-* Trees are represented by nested boxed arrays.\ NB.-* Variables are integers and are considered in scope if lying between zero and 1-length of the state array.\ NB.-* Promises are boxed strings, and are forced by the *execute* verb (`".`).\ NB.-* The indeterminate value (`_.`) was chosen as initial value in the state array because of its limited usefulness in the J language, and to allow unification with the empty array (`''`). `_.` is therefore a marker of the freshness of a variable. NB.- NB.-**CAUTION: there certainly are major bugs and misunderstandings in this, due to my inexpertise in both logic and J!** NB.*var m var NB.+scheme: var? NB.+example: var 3 NB.-This predicate test whether y is of type integer and is not a vector.\ NB.*get d get NB.+scheme: find NB.+example: (_.;'a') get 1 NB.-Walks the state x to find the substitution of y.\ NB.-Tests whether the position y in x is `<_.`. NB.-If `<_.` is found or the verb fails, y is returned. NB.-Otherwise the y-th element is returned. NB.-Walking the state is done by executing until the result stops changing. NB.*occ d occ NB.+scheme: occurs? NB.+example: (<2) occ <<2 NB.-Tests x & y for identity, and returns zero in that case. If x & y are different, we flatten the tree y to a list of leaves and check for x membership in the flattened tree. NB.*ext d ext NB.+scheme: ext-s NB.+example: (<_.) ext 0;'a' NB.-Replaces the values of y by their substitutions according to x, and stores that in a. NB.-For unification to occur, the pair must NB.-1.pass the occurs check and NB.-2.the substituted values must be either identical to themselves (i.e. fresh variables) or identical to the values pointed to in the substitution. NB.-Unification then occurs by amending the positions pointed to in x by those in a. NB.*uni c uni NB.+scheme: unify NB.+example: (_ _) 0 uni 'a' (<_.) NB.-We test u & v for identity, and return the substitution y unchanged if true. NB.-We then check that all variables in the terms to be unified are in scope by flattening the tree and comparing to the length of y. NB.-Rank polymorphism is then achieved by splitting the terms according to the desired left and right ranks given in x. NB.-We map the tree in paths to obtain a list of paths, and then filter the variable paths into vp. NB.-Substitution paths are obtained in vs by negating the first element of each variable path. NB.-We check that all substitution paths are present in the paths in fp by checking for membership in all prefixes of the path list. NB.-We rearrange into 2 columns with variables on the left, and values to be unified on the right. NB.-Rows of the table t are then filtered to eliminate identical values and cycles in ft. NB.-Finally, the state is updated. NB.*equ c equ NB.+scheme: == NB.+example: 0 equ 'a' (<_.) NB.-The equivalence constraint. u and v are values to be unified. y is the state array. NB.-All constraints must define an optional default rank in x. NB.*fsh a fsh NB.+scheme: call/fresh NB.+example: ] fsh '' NB.-Introduces a new variable by extending the state array y with an indeterminate value. NB.*app d app NB.+scheme: $append NB.-Test x, and if a promise makes a new promise with reversed arguments (line 4). NB.-Otherwise appends and recurs (line 5). The depth of recursion is usually not too great, so it seems ok. NB.*apm c apm NB.+scheme: $append-map NB.-Works similarly to app. apm is a conjunction only because it has to handle functions as arguments. NB.*dis c dis NB.+scheme: disj NB.-Disjunction. NB.*con c con NB.+scheme: conj NB.-Conjunction. NB.*cis c cis NB.+scheme: call/initial-state NB.-Notice the initial state is a boxed indeterminate value, in our case. NB.-We 'fold' over the initial promise a user-defined number of times. Since this actually does not map over a sequence but only produces one as we go, this is more akin to a loop.
"use client"; import { z } from "zod"; import Activation from "@/components/Activation"; import { LoadingButton } from "@/components/LoaderButton"; import { Button } from "@/components/ui/button"; import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, } from "@/components/ui/card"; import { Form, FormControl, FormField, FormItem, FormMessage, } from "@/components/ui/form"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { useRegisterMutation } from "@/redux/features/auth/authApi"; import { zodResolver } from "@hookform/resolvers/zod"; import Link from "next/link"; import { useEffect, useState } from "react"; import { useForm } from "react-hook-form"; import toast from "react-hot-toast"; const registerFormSchema = z .object({ fullName: z.string().min(1, "Enter Your Full Name"), email: z .string() .min(1, "Enter Your Email Address") .email("Invalid Email Address"), phone: z .string() .min(1, "Enter Your Phone Number") .regex(/^(\+88)?(01[3-9]\d{8})$/, "Invalid Phone Number"), address: z.string().min(1, "Address is required"), password: z .string() .min(1, "Password is required") .min(6, "Password should be at least 6 characters"), confirmPassword: z .string() .min(1, "Password is required") .min(6, "Password should be at least 6 characters"), }) .refine((data) => data.password === data.confirmPassword, { message: "Password do not match", path: ["confirmPassword"], }); const Register = () => { const [open, setOpen] = useState(false); const form = useForm<z.infer<typeof registerFormSchema>>({ resolver: zodResolver(registerFormSchema), defaultValues: { fullName: "", email: "", password: "", confirmPassword: "", address: "", phone: "", }, }); const [register, { isLoading, error, isSuccess, data }] = useRegisterMutation(); const handleSubmit = (value: z.infer<typeof registerFormSchema>) => { let { confirmPassword, ...data } = value; register(data); }; useEffect(() => { if (isSuccess) { toast.success("Send Activation Code in you mail"); setOpen(true); form.reset(); } else if (error) { const newError = error as any; toast.error(newError.data?.message); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [error, isSuccess]); return ( <div className="min-h-screen flex flex-col items-center justify-center"> <Card className="max-w-[500px] w-full"> <CardHeader> <CardTitle>Register</CardTitle> <CardDescription> If you dont have an account register now. else login </CardDescription> </CardHeader> <CardContent className="space-y-2"> <Form {...form}> <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-5" > <FormField name="fullName" control={form.control} render={({ field }) => ( <FormItem> <Label className="text-primary">Full Name</Label> <FormControl> <Input disabled={isLoading} placeholder="MD. Taifur islam" {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <FormField name="email" control={form.control} render={({ field }) => ( <FormItem> <Label className="text-primary">Email</Label> <FormControl> <Input disabled={isLoading} placeholder="Enter Your Email" {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <FormField name="phone" control={form.control} render={({ field }) => ( <FormItem> <Label className="text-primary">Phone Number</Label> <FormControl> <Input disabled={isLoading} placeholder="Enter Your Phone Number" {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <FormField name="address" control={form.control} render={({ field }) => ( <FormItem> <Label className="text-primary">Address</Label> <FormControl> <Input disabled={isLoading} placeholder="Enter Your Full Address" {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <FormField name="password" control={form.control} render={({ field }) => ( <FormItem> <Label className="text-primary">Password</Label> <FormControl> <Input disabled={isLoading} placeholder="Enter Your password" {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <FormField name="confirmPassword" control={form.control} render={({ field }) => ( <FormItem> <Label className="text-primary">Confirm Password</Label> <FormControl> <Input disabled={isLoading} placeholder="Enter Your confirm password" {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> {isLoading ? ( <LoadingButton className="w-full" /> ) : ( <Button className="w-full" type="submit"> Sign Up </Button> )} </form> </Form> </CardContent> <CardFooter className="gap-1 font-semibold"> <h2>You alredy have an account?</h2> <Link href={"/login"} className="hover:underline text-blue-500"> login </Link> </CardFooter> </Card> <Activation message={data?.message} setOpen={setOpen} open={open} /> </div> ); }; export default Register;
unit CD.Core.CodingStateMachine; interface uses CD.Model.StateMachine; type ICodingStateMachine = interface ['{1A69EE7F-F9EA-4B30-9244-F5393F4BB249}'] function NextState(AByte: Byte): Integer; function ModelName: string; function CurrentCharLen: Integer; procedure Reset; end; /// <summary> /// Parallel state machine for the Coding Scheme Method /// </summary> TCodingStateMachine = class(TInterfacedObject, ICodingStateMachine) private FCurrentState: Integer; FModel: ISMModel; FCurrentCharLen: Integer; FCurrentBytePos: Integer; public constructor Create(AModel: ISMModel); function NextState(AByte: Byte): Integer; procedure Reset; function CurrentCharLen: Integer; function ModelName: string; end; implementation { TCodingStateMachine } constructor TCodingStateMachine.Create(AModel: ISMModel); begin FCurrentState := TSMModel.START; FModel := AModel; end; function TCodingStateMachine.CurrentCharLen: Integer; begin Result := FCurrentCharLen; end; function TCodingStateMachine.ModelName: string; begin Result := FModel.name; end; function TCodingStateMachine.NextState(AByte: Byte): Integer; var byteCls: Integer; begin // for each byte we get its class, if it is first byte, // we also get byte length byteCls := FModel.GetClass(AByte); if (FCurrentState = TSMModel.START) then begin FCurrentBytePos := 0; FCurrentCharLen := FModel.charLenTable[byteCls]; end; // from byte's class and stateTable, we get its next state FCurrentState := FModel.stateTable.Unpack(FCurrentState * FModel.ClassFactor + byteCls); Inc(FCurrentBytePos); Result := FCurrentState; end; procedure TCodingStateMachine.Reset; begin FCurrentState := TSMModel.START; end; end.
//*************************************************************************************** // Shadows.hlsl by Frank Luna (C) 2015 All Rights Reserved. //*************************************************************************************** // Include common HLSL code. //*************************************************************************************** // Common.hlsl by Frank Luna (C) 2015 All Rights Reserved. //*************************************************************************************** // Defaults for number of lights. #ifndef NUM_DIR_LIGHTS #define NUM_DIR_LIGHTS 3 #endif #ifndef NUM_POINT_LIGHTS #define NUM_POINT_LIGHTS 0 #endif #ifndef NUM_SPOT_LIGHTS #define NUM_SPOT_LIGHTS 0 #endif // Include structures and functions for lighting. //*************************************************************************************** // LightingUtil.hlsl by Frank Luna (C) 2015 All Rights Reserved. // // Contains API for shader lighting. //*************************************************************************************** #define MaxLights 16 struct Light { float3 Strength; float FalloffStart; // point/spot light only float3 Direction; // directional/spot light only float FalloffEnd; // point/spot light only float3 Position; // point light only float SpotPower; // spot light only }; struct Material { float4 DiffuseAlbedo; float3 FresnelR0; float Shininess; }; float CalcAttenuation(float d, float falloffStart, float falloffEnd) { // Linear falloff. return saturate((falloffEnd-d) / (falloffEnd - falloffStart)); } // Schlick gives an approximation to Fresnel reflectance (see pg. 233 "Real-Time Rendering 3rd Ed."). // R0 = ( (n-1)/(n+1) )^2, where n is the index of refraction. float3 SchlickFresnel(float3 R0, float3 normal, float3 lightVec) { float cosIncidentAngle = saturate(dot(normal, lightVec)); float f0 = 1.0f - cosIncidentAngle; float3 reflectPercent = R0 + (1.0f - R0)*(f0*f0*f0*f0*f0); return reflectPercent; } float3 BlinnPhong(float3 lightStrength, float3 lightVec, float3 normal, float3 toEye, Material mat) { const float m = mat.Shininess * 256.0f; float3 halfVec = normalize(toEye + lightVec); float roughnessFactor = (m + 8.0f)*pow(max(dot(halfVec, normal), 0.0f), m) / 8.0f; float3 fresnelFactor = SchlickFresnel(mat.FresnelR0, halfVec, lightVec); float3 specAlbedo = fresnelFactor*roughnessFactor; // Our spec formula goes outside [0,1] range, but we are // doing LDR rendering. So scale it down a bit. specAlbedo = specAlbedo / (specAlbedo + 1.0f); return (mat.DiffuseAlbedo.rgb + specAlbedo) * lightStrength; } //--------------------------------------------------------------------------------------- // Evaluates the lighting equation for directional lights. //--------------------------------------------------------------------------------------- float3 ComputeDirectionalLight(Light L, Material mat, float3 normal, float3 toEye) { // The light vector aims opposite the direction the light rays travel. float3 lightVec = -L.Direction; // Scale light down by Lambert's cosine law. float ndotl = max(dot(lightVec, normal), 0.0f); float3 lightStrength = L.Strength * ndotl; return BlinnPhong(lightStrength, lightVec, normal, toEye, mat); } //--------------------------------------------------------------------------------------- // Evaluates the lighting equation for point lights. //--------------------------------------------------------------------------------------- float3 ComputePointLight(Light L, Material mat, float3 pos, float3 normal, float3 toEye) { // The vector from the surface to the light. float3 lightVec = L.Position - pos; // The distance from surface to light. float d = length(lightVec); // Range test. if(d > L.FalloffEnd) return 0.0f; // Normalize the light vector. lightVec /= d; // Scale light down by Lambert's cosine law. float ndotl = max(dot(lightVec, normal), 0.0f); float3 lightStrength = L.Strength * ndotl; // Attenuate light by distance. float att = CalcAttenuation(d, L.FalloffStart, L.FalloffEnd); lightStrength *= att; return BlinnPhong(lightStrength, lightVec, normal, toEye, mat); } //--------------------------------------------------------------------------------------- // Evaluates the lighting equation for spot lights. //--------------------------------------------------------------------------------------- float3 ComputeSpotLight(Light L, Material mat, float3 pos, float3 normal, float3 toEye) { // The vector from the surface to the light. float3 lightVec = L.Position - pos; // The distance from surface to light. float d = length(lightVec); // Range test. if(d > L.FalloffEnd) return 0.0f; // Normalize the light vector. lightVec /= d; // Scale light down by Lambert's cosine law. float ndotl = max(dot(lightVec, normal), 0.0f); float3 lightStrength = L.Strength * ndotl; // Attenuate light by distance. float att = CalcAttenuation(d, L.FalloffStart, L.FalloffEnd); lightStrength *= att; // Scale by spotlight float spotFactor = pow(max(dot(-lightVec, L.Direction), 0.0f), L.SpotPower); lightStrength *= spotFactor; return BlinnPhong(lightStrength, lightVec, normal, toEye, mat); } float4 ComputeLighting(Light gLights[MaxLights], Material mat, float3 pos, float3 normal, float3 toEye, float3 shadowFactor) { float3 result = 0.0f; int i = 0; #if (NUM_DIR_LIGHTS > 0) for(i = 0; i < NUM_DIR_LIGHTS; ++i) { result += shadowFactor[i] * ComputeDirectionalLight(gLights[i], mat, normal, toEye); } #endif #if (NUM_POINT_LIGHTS > 0) for(i = NUM_DIR_LIGHTS; i < NUM_DIR_LIGHTS+NUM_POINT_LIGHTS; ++i) { result += ComputePointLight(gLights[i], mat, pos, normal, toEye); } #endif #if (NUM_SPOT_LIGHTS > 0) for(i = NUM_DIR_LIGHTS + NUM_POINT_LIGHTS; i < NUM_DIR_LIGHTS + NUM_POINT_LIGHTS + NUM_SPOT_LIGHTS; ++i) { result += ComputeSpotLight(gLights[i], mat, pos, normal, toEye); } #endif return float4(result, 0.0f); } struct MaterialData { float4 DiffuseAlbedo; float3 FresnelR0; float Roughness; float4x4 MatTransform; uint DiffuseMapIndex; uint NormalMapIndex; uint MatPad1; uint MatPad2; }; TextureCube gCubeMap : register(t0); Texture2D gShadowMap : register(t1); // An array of textures, which is only supported in shader model 5.1+. Unlike Texture2DArray, the textures // in this array can be different sizes and formats, making it more flexible than texture arrays. Texture2D gTextureMaps[10] : register(t2); // Put in space1, so the texture array does not overlap with these resources. // The texture array will occupy registers t0, t1, ..., t3 in space0. StructuredBuffer<MaterialData> gMaterialData : register(t0, space1); SamplerState gsamPointWrap : register(s0); SamplerState gsamPointClamp : register(s1); SamplerState gsamLinearWrap : register(s2); SamplerState gsamLinearClamp : register(s3); SamplerState gsamAnisotropicWrap : register(s4); SamplerState gsamAnisotropicClamp : register(s5); SamplerComparisonState gsamShadow : register(s6); // Constant data that varies per frame. cbuffer cbPerObject : register(b0) { float4x4 gWorld; float4x4 gTexTransform; uint gMaterialIndex; uint gObjPad0; uint gObjPad1; uint gObjPad2; }; cbuffer cbPass : register(b1) { float4x4 gView; float4x4 gInvView; float4x4 gProj; float4x4 gInvProj; float4x4 gViewProj; float4x4 gInvViewProj; float4x4 gShadowTransform; float3 gEyePosW; float cbPerObjectPad1; float2 gRenderTargetSize; float2 gInvRenderTargetSize; float gNearZ; float gFarZ; float gTotalTime; float gDeltaTime; float4 gAmbientLight; // Indices [0, NUM_DIR_LIGHTS) are directional lights; // indices [NUM_DIR_LIGHTS, NUM_DIR_LIGHTS+NUM_POINT_LIGHTS) are point lights; // indices [NUM_DIR_LIGHTS+NUM_POINT_LIGHTS, NUM_DIR_LIGHTS+NUM_POINT_LIGHT+NUM_SPOT_LIGHTS) // are spot lights for a maximum of MaxLights per object. Light gLights[MaxLights]; }; //--------------------------------------------------------------------------------------- // Transforms a normal map sample to world space. //--------------------------------------------------------------------------------------- float3 NormalSampleToWorldSpace(float3 normalMapSample, float3 unitNormalW, float3 tangentW) { // Uncompress each component from [0,1] to [-1,1]. float3 normalT = 2.0f*normalMapSample - 1.0f; // Build orthonormal basis. float3 N = unitNormalW; float3 T = normalize(tangentW - dot(tangentW, N)*N); float3 B = cross(N, T); float3x3 TBN = float3x3(T, B, N); // Transform from tangent space to world space. float3 bumpedNormalW = mul(normalT, TBN); return bumpedNormalW; } //--------------------------------------------------------------------------------------- // PCF for shadow mapping. //--------------------------------------------------------------------------------------- float CalcShadowFactor(float4 shadowPosH) { // Complete projection by doing division by w. shadowPosH.xyz /= shadowPosH.w; // Depth in NDC space. float depth = shadowPosH.z; uint width, height, numMips; gShadowMap.GetDimensions(0, width, height, numMips); // Texel size. float dx = 1.0f / (float)width; float percentLit = 0.0f; const float2 offsets[9] = { float2(-dx, -dx), float2(0.0f, -dx), float2(dx, -dx), float2(-dx, 0.0f), float2(0.0f, 0.0f), float2(dx, 0.0f), float2(-dx, +dx), float2(0.0f, +dx), float2(dx, +dx) }; [unroll] for(int i = 0; i < 9; ++i) { percentLit += gShadowMap.SampleCmpLevelZero(gsamShadow, shadowPosH.xy + offsets[i], depth).r; } return percentLit / 9.0f; } struct VertexIn { float3 PosL : POSITION; float2 TexC : TEXCOORD; }; struct VertexOut { float4 PosH : SV_POSITION; float2 TexC : TEXCOORD; }; // This is only used for alpha cut out geometry, so that shadows // show up correctly. Geometry that does not need to sample a // texture can use a NULL pixel shader for depth pass. void PSMain(VertexOut pin) { // Fetch the material data. MaterialData matData = gMaterialData[gMaterialIndex]; float4 diffuseAlbedo = matData.DiffuseAlbedo; uint diffuseMapIndex = matData.DiffuseMapIndex; // Dynamically look up the texture in the array. diffuseAlbedo *= gTextureMaps[diffuseMapIndex].Sample(gsamAnisotropicWrap, pin.TexC); #ifdef ALPHA_TEST // Discard pixel if texture alpha < 0.1. We do this test as soon // as possible in the shader so that we can potentially exit the // shader early, thereby skipping the rest of the shader code. clip(diffuseAlbedo.a - 0.1f); #endif }
z xmlrpc.server zaimportuj DocXMLRPCServer zaimportuj http.client zaimportuj sys z test zaimportuj support threading = support.import_module('threading') zaimportuj time zaimportuj socket zaimportuj unittest PORT = Nic def make_request_and_skipIf(condition, reason): # If we skip the test, we have to make a request because # the server created w setUp blocks expecting one to come in. jeżeli nie condition: zwróć lambda func: func def decorator(func): def make_request_and_skip(self): self.client.request("GET", "/") self.client.getresponse() podnieś unittest.SkipTest(reason) zwróć make_request_and_skip zwróć decorator def server(evt, numrequests): serv = DocXMLRPCServer(("localhost", 0), logRequests=Nieprawda) spróbuj: global PORT PORT = serv.socket.getsockname()[1] # Add some documentation serv.set_server_title("DocXMLRPCServer Test Documentation") serv.set_server_name("DocXMLRPCServer Test Docs") serv.set_server_documentation( "This jest an XML-RPC server's documentation, but the server " "can be used by POSTing to /RPC2. Try self.add, too.") # Create oraz register classes oraz functions klasa TestClass(object): def test_method(self, arg): """Test method's docs. This method truly does very little.""" self.arg = arg serv.register_introspection_functions() serv.register_instance(TestClass()) def add(x, y): """Add two instances together. This follows PEP008, but has nothing to do przy RFC1952. Case should matter: pEp008 oraz rFC1952. Things that start przy http oraz ftp should be auto-linked, too: http://google.com. """ zwróć x + y def annotation(x: int): """ Use function annotations. """ zwróć x klasa ClassWithAnnotation: def method_annotation(self, x: bytes): zwróć x.decode() serv.register_function(add) serv.register_function(lambda x, y: x-y) serv.register_function(annotation) serv.register_instance(ClassWithAnnotation()) dopóki numrequests > 0: serv.handle_request() numrequests -= 1 wyjąwszy socket.timeout: dalej w_końcu: serv.server_close() PORT = Nic evt.set() klasa DocXMLRPCHTTPGETServer(unittest.TestCase): def setUp(self): self._threads = support.threading_setup() # Enable server feedback DocXMLRPCServer._send_traceback_header = Prawda self.evt = threading.Event() threading.Thread(target=server, args=(self.evt, 1)).start() # wait dla port to be assigned deadline = time.monotonic() + 10.0 dopóki PORT jest Nic: time.sleep(0.010) jeżeli time.monotonic() > deadline: przerwij self.client = http.client.HTTPConnection("localhost:%d" % PORT) def tearDown(self): self.client.close() self.evt.wait() # Disable server feedback DocXMLRPCServer._send_traceback_header = Nieprawda support.threading_cleanup(*self._threads) def test_valid_get_response(self): self.client.request("GET", "/") response = self.client.getresponse() self.assertEqual(response.status, 200) self.assertEqual(response.getheader("Content-type"), "text/html") # Server podnieśs an exception jeżeli we don't start to read the data response.read() def test_invalid_get_response(self): self.client.request("GET", "/spam") response = self.client.getresponse() self.assertEqual(response.status, 404) self.assertEqual(response.getheader("Content-type"), "text/plain") response.read() def test_lambda(self): """Test that lambda functionality stays the same. The output produced currently is, I suspect invalid because of the unencoded brackets w the HTML, "<lambda>". The subtraction lambda method jest tested. """ self.client.request("GET", "/") response = self.client.getresponse() self.assertIn((b'<dl><dt><a name="-&lt;lambda&gt;"><strong>' b'&lt;lambda&gt;</strong></a>(x, y)</dt></dl>'), response.read()) @make_request_and_skipIf(sys.flags.optimize >= 2, "Docstrings are omitted przy -O2 oraz above") def test_autolinking(self): """Test that the server correctly automatically wraps references to PEPS oraz RFCs przy links, oraz that it linkifies text starting with http albo ftp protocol prefixes. The documentation dla the "add" method contains the test material. """ self.client.request("GET", "/") response = self.client.getresponse().read() self.assertIn( (b'<dl><dt><a name="-add"><strong>add</strong></a>(x, y)</dt><dd>' b'<tt>Add&nbsp;two&nbsp;instances&nbsp;together.&nbsp;This&nbsp;' b'follows&nbsp;<a href="http://www.python.org/dev/peps/pep-0008/">' b'PEP008</a>,&nbsp;but&nbsp;has&nbsp;nothing<br>\nto&nbsp;do&nbsp;' b'with&nbsp;<a href="http://www.rfc-editor.org/rfc/rfc1952.txt">' b'RFC1952</a>.&nbsp;Case&nbsp;should&nbsp;matter:&nbsp;pEp008&nbsp;' b'and&nbsp;rFC1952.&nbsp;&nbsp;Things<br>\nthat&nbsp;start&nbsp;' b'with&nbsp;http&nbsp;and&nbsp;ftp&nbsp;should&nbsp;be&nbsp;' b'auto-linked,&nbsp;too:<br>\n<a href="http://google.com">' b'http://google.com</a>.</tt></dd></dl>'), response) @make_request_and_skipIf(sys.flags.optimize >= 2, "Docstrings are omitted przy -O2 oraz above") def test_system_methods(self): """Test the precense of three consecutive system.* methods. This also tests their use of parameter type recognition oraz the systems related to that process. """ self.client.request("GET", "/") response = self.client.getresponse().read() self.assertIn( (b'<dl><dt><a name="-system.methodHelp"><strong>system.methodHelp' b'</strong></a>(method_name)</dt><dd><tt><a href="#-system.method' b'Help">system.methodHelp</a>(\'add\')&nbsp;=&gt;&nbsp;"Adds&nbsp;' b'two&nbsp;integers&nbsp;together"<br>\n&nbsp;<br>\nReturns&nbsp;a' b'&nbsp;string&nbsp;containing&nbsp;documentation&nbsp;for&nbsp;' b'the&nbsp;specified&nbsp;method.</tt></dd></dl>\n<dl><dt><a name' b'="-system.methodSignature"><strong>system.methodSignature</strong>' b'</a>(method_name)</dt><dd><tt><a href="#-system.methodSignature">' b'system.methodSignature</a>(\'add\')&nbsp;=&gt;&nbsp;[double,&nbsp;' b'int,&nbsp;int]<br>\n&nbsp;<br>\nReturns&nbsp;a&nbsp;list&nbsp;' b'describing&nbsp;the&nbsp;signature&nbsp;of&nbsp;the&nbsp;method.' b'&nbsp;In&nbsp;the<br>\nabove&nbsp;example,&nbsp;the&nbsp;add&nbsp;' b'method&nbsp;takes&nbsp;two&nbsp;integers&nbsp;as&nbsp;arguments' b'<br>\nand&nbsp;returns&nbsp;a&nbsp;double&nbsp;result.<br>\n&nbsp;' b'<br>\nThis&nbsp;server&nbsp;does&nbsp;NOT&nbsp;support&nbsp;system' b'.methodSignature.</tt></dd></dl>'), response) def test_autolink_dotted_methods(self): """Test that selfdot values are made strong automatically w the documentation.""" self.client.request("GET", "/") response = self.client.getresponse() self.assertIn(b"""Try&nbsp;self.<strong>add</strong>,&nbsp;too.""", response.read()) def test_annotations(self): """ Test that annotations works jako expected """ self.client.request("GET", "/") response = self.client.getresponse() docstring = (b'' jeżeli sys.flags.optimize >= 2 inaczej b'<dd><tt>Use&nbsp;function&nbsp;annotations.</tt></dd>') self.assertIn( (b'<dl><dt><a name="-annotation"><strong>annotation</strong></a>' b'(x: int)</dt>' + docstring + b'</dl>\n' b'<dl><dt><a name="-method_annotation"><strong>' b'method_annotation</strong></a>(x: bytes)</dt></dl>'), response.read()) jeżeli __name__ == '__main__': unittest.main()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Shop</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous"> <link rel="stylesheet" href="shop.css"> </head> <body> <div id="app"> <div class="shop container mt-4"> <div class="products"> <h2>Our Products</h2> <div class="product" v-for="product in products"> <div class="product__properties"> <div class="product__title"> {{product.name}} </div> <div class="product__price"> {{product.price}} </div> </div> <div class="product__buttons"> <button class="btn btn-primary" @click="addToCart(product)">Add to Cart</button> </div> </div> </div> <div class="cart"> <h2>Your Cart</h2> <div class="product" v-for="product in cart"> <div class="product__properties"> <div class="product__title"> {{product.product}} </div> <div class="product__price"> {{product.price}} </div> </div> <div class="product__buttons"> <button class="btn btn-danger" @click="discard(product)">Discard</button> </div> </div> </div> </div> <div class="comments container mt-5"> <h3>Comments</h3> <div class="comment" v-for="comment in comments"> <div class="comment__text">{{comment.text}}</div> <div class="comment__info"> <div class="comment__likes"> <i class="fas fa-thumbs-up" @click="likeComment(comment)"></i>{{comment.likes}}</div> <div class="comment__delete"> <i class="fas fa-trash-alt" @click="deleteComment(comment)"></i> </div> </div> </div> <h3>Add Comment</h3> <div class="comment-form"> <textarea name="" id="" cols="30" rows="7" v-model="text"></textarea> <button class="btn btn-secondary" @click="addComment(text)">Submit</button> </div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script> <script src="https://unpkg.com/vue-async-computed"></script> <script src="shop.js"></script> </body> </html>
import {Component, OnDestroy, OnInit} from '@angular/core'; import { Store } from '@ngrx/store'; import { Observable, Subscription } from 'rxjs'; import { AppState, selectDashboardState, selectProjectState } from '../../store/app.states'; import { Router } from '@angular/router'; import { ProjectExport } from '../../store/actions/project.actions'; import {GetProjects, Init} from '../../store/actions/dashboard.actions'; import { SegmentService } from 'ngx-segment-analytics'; import { environment } from '../../../environments/environment'; import {TrialService} from "../../_services/trial.service"; @Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html', styleUrls: ['./dashboard.component.scss'] }) export class DashboardComponent implements OnInit, OnDestroy { file; exportedTitle = ''; format = ''; menuOpen = true; projects = []; exportPopup = false; trialExpired = false; dashboardSubscription: Subscription; getDashboardState: Observable<any>; projectSubscription: Subscription; getProjectState: Observable<any>; projectId: string; constructor( private store: Store<AppState>, private router: Router, private segment: SegmentService, private trailService: TrialService ) { this.getDashboardState = this.store.select(selectDashboardState); this.getProjectState = this.store.select(selectProjectState); this.trailService.openTrialGet().subscribe((res: any) => { if (this.router.url !== '/dashboard/profile'){ this.trialExpired = res.trialExpired; } localStorage.paymentStatus = 'inactive'; }); } ngOnInit(): void { this.segment.identify(localStorage.getItem('userId'), { environment: environment.NAME, userId: localStorage.getItem('userId'), }); this.checkExpired(); const regexp = /\/dashboard\/projects\/.+/; this.menuOpen = !(regexp.test(this.router.url)); this.store.dispatch(new Init({})); this.dashboardSubscription = this.getDashboardState.subscribe(state => { if (state.projects) this.projects = state.projects || []; else this.projects = []; }); this.projectSubscription = this.getProjectState.subscribe(state => { if (state.project) this.projectId = state.project.id; if (state.file) { this.file = state.file; this.saveExportedFile(); } }); } ngOnDestroy(): void { this.dashboardSubscription.unsubscribe(); this.projectSubscription.unsubscribe(); } routeChange(): void { this.checkExpired(); const regexp = /\/dashboard\/projects\/.+/; this.menuOpen = !(regexp.test(this.router.url)); } checkExpired(): void { if (localStorage.paymentStatus === 'inactive') { this.trialExpired = !(this.router.url === '/dashboard/profile'); } } exportProject(project, format): void { this.segment.track('Export project', { environment: environment.NAME, userId: localStorage.getItem('userId'), projectId: project.id }); this.exportedTitle = project.title; this.format = format; this.store.dispatch(new ProjectExport({ id: project.uuid, format })); } saveExportedFile(): void { const url = window.URL.createObjectURL(this.file); const a = document.createElement('a'); document.body.appendChild(a); a.setAttribute('style', 'display: none'); a.href = url; a.download = `${this.exportedTitle ? this.exportedTitle : 'project'}.${this.format}`; a.click(); window.URL.revokeObjectURL(url); a.remove(); this.exportedTitle = ''; this.format = ''; this.segment.track('Export project saved', { environment: environment.NAME, userId: localStorage.getItem('userId'), projectId: this.projectId, projectTitle: this.exportedTitle, projectFileFormat: this.format }); } clickOnElement(elementName, pageName): void { this.segment.track(`Click on ${elementName}:${pageName}`, { environment: environment.NAME, userId: localStorage.getItem('userId'), projectId: this.projectId }); } }
import 'dart:convert'; import 'dart:developer'; import 'dart:ui'; import 'package:country_picker/country_picker.dart'; import 'package:flutter/material.dart'; import 'package:flutter_datetime_picker/flutter_datetime_picker.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:flutter_picker/flutter_picker.dart'; import 'package:get/get.dart'; import 'package:intl/intl.dart'; import 'package:carkee/components/TextFieldPhungNoBorder.dart'; import 'package:carkee/components/bottom_next_back_register.dart'; import 'package:carkee/config/app_configs.dart'; import 'package:carkee/components/network_api.dart'; import 'package:dio/dio.dart' as Dioo; import 'package:carkee/controllers/controllers.dart'; import 'package:carkee/models/ModelMemberOptionsResult.dart'; import 'package:carkee/screen/update_part2_company.dart'; import 'package:carkee/screen/update_part2_personal.dart'; class UpdatePart1CompanyScreen extends StatelessWidget { final UpdatePart1CompanyController controller = Get.put(UpdatePart1CompanyController()); @override Widget build(BuildContext context) { print('Start build'); return image_background(context); } Widget image_background(BuildContext context) { //return Center(child: CircularProgressIndicator()); return Material( child: Container( // color: Colors.red, decoration: BoxDecoration( image: DecorationImage( image: AssetImage("assets/images/bg_2.png"), fit: BoxFit.cover), ), child : blur_background(context) ), ); } Widget blur_background(BuildContext context) { //return Center(child: CircularProgressIndicator()); return BackdropFilter( filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5), child: Container( decoration: BoxDecoration( color: Colors.white.withOpacity(0.8), ), child: body_view(context), ), ); } Widget body_view(BuildContext context) { print('Start build'); return Scaffold( backgroundColor: Colors.transparent, body: SafeArea( child: Container( child: Column(children: [ // LineStepRegister(totalStep: 4, currentStep: 1), AppNavigationV2( closeClicked: () { print("close clicked"); Session.shared.changeRootViewToGuest(); }, title: "Tell us more about you!", subTitle: 'We’ll need some additional details before we complete the registration process.', totalStep: 4, currentStep: 1, ), Expanded( child: ListView( children: [ //section1 builGenderPart(), section1(context), section2(context), section3(context) // buildFormBuilder(context) // buildBody(context) ], ), ), BottomNextBackRegister( isShowBack: false, nextClicked: () => controller.callAPIUpdate(), ) ]), // children: [], ), ), ); } // _showPickerDate(BuildContext context) { // Picker( // hideHeader: true, // adapter: DateTimePickerAdapter( // yearBegin: 1900, yearEnd: Session.shared.getMinAllowYear()), // selectedTextStyle: TextStyle(color: Config.secondColor), // onConfirm: (Picker picker, List value) { // DateTime chooseDate = (picker.adapter as DateTimePickerAdapter).value; // print(chooseDate); // controller.handleAfterPickerDate(chooseDate); // }).showDialog(context); // } // _showPickerDate(BuildContext context) { // DatePicker.showDatePicker(context, // showTitleActions: true, // minTime: DateTime(1900, 1, 1), // maxTime: DateTime(Session.shared.getMinAllowYear(), 31, 12), // // theme: DatePickerTheme( // // // headerColor: Colors.orange, // // // backgroundColor: Colors.blue, // // // itemStyle: TextStyle( // // // color: Colors.white, fontWeight: FontWeight.bold, fontSize: 18), // // // doneStyle: TextStyle(color: Colors.white, fontSize: 16) // // ), // onChanged: (date) { // print('change $date in time zone ' + date.timeZoneOffset.inHours.toString()); // // controller.handleAfterPickerDate(date); // }, onConfirm: (date) { // print('confirm $date'); // controller.handleAfterPickerDate(date); // }, currentTime: DateTime.now(), locale: LocaleType.en); // } Widget section1(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: Config.kDefaultPadding * 2 ), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ //Date of birth Picker PickerMclub( // initialValue : controller.birthday, controller: controller.birthdayController, titleValue: 'Date of Birth', onTap: () { Session.shared.showPickerDate(context, (date) { controller.handleAfterPickerDate(date); }); // _showPickerDate(context); }, ), TextFieldPhungNoBorder( controller: controller.nric, labelText: "NRIC", hintText: "", onChange: (value) { print(value); controller.nric.text = value; }, ), // Text( // 'Company Contact Details', // style: Styles.mclub_Tilte, // ), // // // //PHONE CODE // Row( // crossAxisAlignment: CrossAxisAlignment.end, // children: [ // SizedBox( // width: 100, // child: PickerMclub( // controller: controller.telephone_code, // titleValue: 'Country Code', // onTap: () { // _showPickerTelephoneCode(context); // }, // ), // ), // SizedBox( // width: 5, // ), // Flexible( // child: SizedBox( // child: TextFieldPhungNoBorder( // controller: controller.telephone_no, // labelText: "Representative Mobile No.", // hintText: "", // onChange: (value) { // print(value); // controller.telephone_no.text = value; // }, // ), // ), // ), // ]), // // TextFieldPhungNoBorder( // controller: controller.company_email, // labelText: "Email Address", // hintText: "", // onChange: (value) { // print(value); // controller.company_email.text = value; // }, // notAllowEmpty: true, // requiredEmail: true, // keyboardType: TextInputType.emailAddress, // ), //country picker ] ), ); } Widget section2(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: Config.kDefaultPadding * 2 ), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.only(top: Config.kDefaultPadding), child: Text( 'About your club/company', style: Styles.mclub_Tilte, ), ), //Date of birth Picker // PickerMclub( // // initialValue : controller.birthday, // controller: controller.birthdayController, // titleValue: 'Date of Birth', // onTap: () { // _showPickerDate(context); // }, // ), TextFieldPhungNoBorder( controller: controller.company_name, labelText: "Club / company name", hintText: "", onChange: (value) { print(value); controller.company_name.text = value; }, ), TextFieldPhungNoBorder( controller: controller.company_uen, labelText: "Company Registration No. (UEN)", hintText: "", onChange: (value) { print(value); controller.company_uen.text = value; }, ), TextFieldPhungNoBorder( controller: controller.company_about, labelText: "Tell us more about your club / company", hintText: "", onChange: (value) { print(value); controller.company_about.text = value; }, ), TextFieldPhungNoBorder( controller: controller.company_number_members, labelText: "No. of members", hintText: "", onChange: (value) { print(value); controller.company_number_members.text = value; }, keyboardType: TextInputType.number, ), // Text( // 'Company Contact Details', // style: Styles.mclub_Tilte, // ), // // // //PHONE CODE // Row( // crossAxisAlignment: CrossAxisAlignment.end, // children: [ // SizedBox( // width: 100, // child: PickerMclub( // controller: controller.telephone_code, // titleValue: 'Country Code', // onTap: () { // _showPickerTelephoneCode(context); // }, // ), // ), // SizedBox( // width: 5, // ), // Flexible( // child: SizedBox( // child: TextFieldPhungNoBorder( // controller: controller.telephone_no, // labelText: "Representative Mobile No.", // hintText: "", // onChange: (value) { // print(value); // controller.telephone_no.text = value; // }, // ), // ), // ), // ]), // // TextFieldPhungNoBorder( // controller: controller.company_email, // labelText: "Email Address", // hintText: "", // onChange: (value) { // print(value); // controller.company_email.text = value; // }, // notAllowEmpty: true, // requiredEmail: true, // keyboardType: TextInputType.emailAddress, // ), //country picker ] ), ); } Widget section3(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: Config.kDefaultPadding * 2 ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.only(top: Config.kDefaultPadding), child: Text( 'Club / Company address', style: Styles.mclub_Tilte, ), ), //Date of birth Picker PickerMclub( // initialValue : controller.birthday, controller: controller.company_country, titleValue: 'Country', onTap: () { _showPickerCountry(context); }, ), Row( children: [ Expanded( child: TextFieldPhungNoBorder( controller: controller.company_postal_code, labelText: "Postal Code", hintText: "", onChange: (value) { print(value); controller.company_postal_code.text = value; }, keyboardType: TextInputType.number, ), ), SizedBox( width: 5, ), Expanded( child: TextFieldPhungNoBorder( controller: controller.company_unit_no, labelText: "Unit No", hintText: "", onChange: (value) { print(value); controller.company_unit_no.text = value; }, ), ), ], ), TextFieldPhungNoBorder( controller: controller.company_add_1, labelText: "Address Line 1", hintText: "", onChange: (value) { print(value); controller.company_add_1.text = value; }, ), TextFieldPhungNoBorder( controller: controller.company_add_2, labelText: "Address Line 2", hintText: "", onChange: (value) { print(value); controller.company_add_2.text = value; }, ), ]), ); } Widget builGenderPart() { print('buildBody buildgenderPart'); return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 10,), Padding( padding: const EdgeInsets.only(left: Config.kDefaultPadding * 2, right: Config.kDefaultPadding * 2, top: 0,bottom: 10), child: Text( 'Club/Company Representative’s Details', style: Styles.mclub_Tilte, ), ), Padding( padding: const EdgeInsets.symmetric( horizontal: Config.kDefaultPadding * 2, vertical: 0), child: Text( 'Gender', style: Styles.mclub_normalText, ), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 0), child: FormBuilderRadioGroup( decoration: InputDecoration( contentPadding: EdgeInsets.all(0), border: InputBorder.none,), initialValue: controller.gender == 'm' ? 'Male' : (controller.gender == 'f' ? 'Female' : ""), // name: 'gender', onChanged: (currentValue) { print(currentValue); if (currentValue == 'Male') { controller.gender = 'm'; } else if (currentValue == 'Female') { controller.gender = 'f'; } }, options: [ 'Male', 'Female', ] .map((lang) => FormBuilderFieldOption(value: lang)) .toList(growable: false), ), ), ], ); } _showPickerCountry(BuildContext context) { showCountryPicker( //Có thể sau này dùng lại loic showCountryPicker xem trong source và chôm lại ý tưởng! context: context, showPhoneCode: true, // optional. Shows phone code before the country name. onSelect: (Country country) { print('Select country: ${country.displayName}'); print('Select Code: ${country.countryCode}'); var contrySelected = country.name; controller.company_country.text = contrySelected; // controller.country = contrySelected; // print('codeMobile $codeMobile'); }, ); } // // _showPickerTelephoneCode(BuildContext context) { // showCountryPicker( // //Có thể sau này dùng lại loic showCountryPicker xem trong source và chôm lại ý tưởng! // context: context, // showPhoneCode: // true, // optional. Shows phone code before the country name. // onSelect: (Country country) { // print('Select country: ${country.displayName}'); // print('Select Code: ${country.countryCode}'); // var codeSelected = country.phoneCode; // controller.telephone_code.text = '+$codeSelected';; // }, // ); // } } class UpdatePart1CompanyController extends GetxController { final ProfileController profileController = Get.find(); // var telephone_code = TextEditingController(); // var telephone_no = TextEditingController(); var company_email = TextEditingController(); //Company Registration No. (UEN) var company_name = TextEditingController(); var company_uen = TextEditingController(); //Tell us more about your club / company var company_about = TextEditingController(); //No. of members var company_number_members = TextEditingController(); var company_country = TextEditingController(); var company_postal_code = TextEditingController(); var company_unit_no = TextEditingController(); var company_add_1 = TextEditingController(); var company_add_2 = TextEditingController(); var gender = ''; var nric = TextEditingController(); var birthdayController = TextEditingController(); final GlobalKey<FormBuilderState> _fbKey = GlobalKey<FormBuilderState>(); @override void onInit() { super.onInit(); loadOldData(); } loadOldData() { // telephone_code.text = profileController.getCompanyTelePhoneCode(); // telephone_no.text = profileController.userProfile.value.telephoneNo; //section 1 gender = profileController.userProfile.value.gender; birthdayController.text = profileController.userProfile.value.birthday; nric.text = profileController.userProfile.value.nric; // company_email.text = profileController.userProfile.value.companyEmail; company_name.text = profileController.userProfile.value.company; company_uen.text = profileController.userProfile.value.eun; company_about.text = profileController.userProfile.value.about; company_number_members.text = profileController.userProfile.value.numberOfEmployees; company_country.text = profileController.getCompanyCountry(); company_postal_code.text = profileController.userProfile.value.companyPostalCode; company_unit_no.text = profileController.userProfile.value.companyUnitNo; company_add_1.text = profileController.userProfile.value.companyAdd1; company_add_2.text = profileController.userProfile.value.companyAdd2; print(profileController.userProfile.value.toJson()); } handleAfterPickerDate(DateTime chooseDate) { var formatter = new DateFormat('yyyy-MM-dd'); String formattedDate = formatter.format(chooseDate); birthdayController.text = formattedDate; // birthday = formattedDate; } callAPIUpdate() async { Session.shared.showLoading(); print("start callAPIUpdate"); //hide keyboard! Dioo.FormData formData = new Dioo.FormData.fromMap({ //section1 Club/Company // Representative’s Details 'step': 1, "gender": gender, "birthday": birthdayController.text, "nric": nric.text.toUpperCase(), //section2 About your club/company 'company': company_name.text, 'eun' : company_uen.text, 'about' : company_about.text, 'number_of_employees' : company_number_members.text, //section 3 Club/company address "company_country": company_country.text, 'company_postal_code': company_postal_code.text, 'company_unit_no': company_unit_no.text, 'company_add_1': company_add_1.text, "company_add_2": company_add_2.text, // 'telephone_code' : telephone_code.text, // 'telephone_no' : telephone_no.text, // 'company_email' : company_email.text }); Map<String, dynamic> jsonQuery = {"access-token": await Session.shared.getToken()}; var network = NetworkAPI( endpoint: url_update_company_onboarding, formData: formData, jsonQuery: jsonQuery); var jsonBody = await network.callAPIPOST(); Session.shared.hideLoading(); if (jsonBody["code"] == 100) { print("success "); await profileController.callAPIGetProfile(); Get.offAll(() =>UpdatePart2CompanyScreen()); } else { Session.shared.showAlertPopupOneButtonNoCallBack( title: "Error", content: jsonBody["message"]); } } @override void onClose() { super.onClose(); } }
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ //inorder traversal class Solution { public: vector<int> inorderTraversal(TreeNode* root) { vector<int> inorder; TreeNode* cur = root; while(cur != NULL) { if(cur->left == NULL) { inorder.push_back(cur->val); cur = cur->right; } else { TreeNode* prev = cur->left; while(prev->right != NULL && prev->right != cur) { prev = prev->right; } if(prev->right == NULL) { prev->right = cur; cur = cur->left; } else { prev->right = NULL; inorder.push_back(cur->val); cur = cur->right; } } } return inorder; } }; //preorder traversal class Solution { public: vector<int> inorderTraversal(TreeNode* root) { vector<int> preorder; TreeNode* cur = root; while(cur != NULL) { if(cur->left == NULL) { preorder.push_back(cur->val); cur = cur->right; } else { TreeNode* prev = cur->left; while(prev->right != NULL && prev->right != cur) { prev = prev->right; } if(prev->right == NULL) { prev->right = cur; preorder.push_back(cur->val); cur = cur->left; } else { prev->right = NULL; cur = cur->right; } } } return preorder; } };
import {useRecoilState} from 'recoil'; import { useNavigate } from 'react-router-dom'; import HeaderUI from "./header.presenter"; import { loginState } from "../../store/recoilAtoms"; import { userState } from '../../store/recoilAtoms'; import axios from 'axios'; export default function Headers() { const [isLogged, setIsLogged] = useRecoilState(loginState); const [user, setUser] = useRecoilState(userState); const navigate = useNavigate(); const onClickLogin = () => { navigate("/login") } const onClickMain = () => { navigate("/") } const handleLogout = async () => { try{ const response = await axios.post('http://localhost:8080/user/logout') if (response.status === 200){ console.log('로그아웃 완료') setIsLogged(false) setUser((prevUser) => ({ ...prevUser, email: '', nickName: '', })) }else{ console.log('로그아웃 실패s') } }catch(error){ console.log('error', error) } } const moveCategories = () => { navigate("/categories") } return ( <HeaderUI onClickMain = {onClickMain} onClickLogin = {onClickLogin} handleLogout = {handleLogout} moveCategories = {moveCategories} isLogged = {isLogged} /> ) }
import React, { ChangeEvent, useState } from 'react' import { useEffect } from 'react'; import { fetchPokemon } from '../../../store/PokemonRedux'; import { StyledSection } from "../../Layout/MainNavigationStyle"; import { useDispatch } from 'react-redux'; import { RootStateOrAny, useSelector } from 'react-redux'; import { FullPokemon } from '../../../service/types'; import SinglePokemon from '../SinglePokemon/SinglePokemon'; import { FramedDiv, StyledButtonSection } from './AllPokemonsStyle' import { fetchSinglePokemon, mapSinglePokemon, reducePokemons } from '../../../service/service'; import FullSinglePokemon from '../FullSinglePokemon/FullSinglepokemon'; const AllPokemons = () => { const dispatch = useDispatch(); const pokemonsData = useSelector((state: RootStateOrAny) => state.data.value); const nextPokemon = useSelector((state: RootStateOrAny) => state.data.next); const prevPokemon = useSelector((state: RootStateOrAny) => state.data.prev); const hasChanged = useSelector((state: RootStateOrAny) => state.data.changed); const [userInput, setUserInput] = useState(''); const [showSingle, setShowSingle] = useState(false); const [pokeaArray, setPokeArray] = useState(pokemonsData) useEffect(() => { const addr = hasChanged ? null : 'https://pokeapi.co/api/v2/pokemon?limit=12&offset=0' dispatch(fetchPokemon(addr)); }, []); useEffect(() => { setPokeArray(pokemonsData) }, [showSingle]); useEffect(() => { setPokeArray(pokemonsData) dispatch(fetchPokemon(pokemonsData)); }, [pokemonsData]); const pokemonMenu = () => { return pokeaArray.map((pokemon: FullPokemon) => <SinglePokemon key={pokemon.id} pokemon={pokemon} />); } const nextClickedHandler = () => { dispatch(fetchPokemon(nextPokemon)); setPokeArray(pokemonsData) } const prevClickedHandler = () => { dispatch(fetchPokemon(prevPokemon)); setPokeArray(pokemonsData) } const clickHandler = async () => { setShowSingle(true); const pokeData = await fetchSinglePokemon(userInput); const formattedPokemon: any | FullPokemon = mapSinglePokemon(pokeData); setPokeArray([formattedPokemon]); } const changeHandler = (e: ChangeEvent<HTMLInputElement>) => { setUserInput(e.currentTarget.value); let allPokemons: string | null | FullPokemon[] = window.localStorage.getItem('all-pokemons'); const formattedAllPokemons = allPokemons ? JSON.parse(allPokemons) : ''; const newArray = reducePokemons(formattedAllPokemons, e.currentTarget.value); setPokeArray(newArray) } return ( <> <StyledSection> <input type="text" placeholder="enter a pokemon's name..." onChange={changeHandler} /> <button type='submit' onClick={clickHandler}>Search</button> </StyledSection> <FramedDiv> {pokemonMenu()} </FramedDiv> <StyledButtonSection> <button onClick={prevClickedHandler}>{`←previous`}</button> <button onClick={nextClickedHandler}>{`next→`}</button> </StyledButtonSection> </> ); } export default AllPokemons;
1. 이 포스트는 Email Client를 작성하는 시리즈의 일부이다 1-1 여기서는 지금 하드코딩된 메일목록 대신 실제 데이터를 읽어와서 목록을 보여주는 코드를 작성한다. 2. 구현 방법 2-1 우선 url이 /inbox 으로 검색이 되는 경우 현재 email 모듈의 home 컴포넌트가 로딩이된다. 2-2 이 home 컴포넌트가 생성 시 email 서비스로 접근하여 데이터를 가지고 와서 email-list 컴포넌트로 넘겨준다. 3. email 서버는 수신한 이메일에 대한 목록을 보내주는 api가 있다 3-1 get 메소드로 https://api.angular-email.com/emails 로 접근하면 된다. 3-2 회신 시 아래와 같은 구조로 넘어오기 때문에 별도의 클래스를 생성하였다. export class EmailListItem { id: string = '' subject: string = '' from: string = '' } 4. 코드를 작성한다. 4-1 이메일 서비스 파일을 작성한다. 4-1-1 이메일 목록을 요청하는 메소드를 getEmailList로 하였고 반환결과는 EmailListItem 배열로 받고 있다. import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { EmailListItem } from './email-list-item'; @Injectable({ providedIn: 'root' }) export class EmailService { url = 'https://api.angular-email.com/emails' constructor(private http: HttpClient) { } getEmailList(): Observable<EmailListItem[]> { return this.http.get<EmailListItem[]>(`${this.url}`) } } 4-2 이메일을 데이터를 요청하는 home 컴포넌트의 코드 4-2-1 template에서 email-list 컴포넌트로 이메일 목록 데이터를 전달한다. <div class="row"> <div class="col-sm-4"> <app-email-compose></app-email-compose> <app-email-list [emailList]="emailList"></app-email-list> </div> <div class="col-sm-8"> <router-outlet></router-outlet> </div> </div> 4-2-2 home 컴포넌트는 이메일 목록을 컴포넌트 생성 시 요청한다. import { Component, OnInit, Input } from '@angular/core'; import { EmailService } from '../email.service'; import { EmailListItem } from '../email-list-item'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { @Input() emailList: EmailListItem[] = [] constructor(private emailService: EmailService) { } ngOnInit(): void { this.emailService.getEmailList().subscribe( list => this.emailList = list ) } } 4-3 email-list 컴포넌트 코드 4-3-1 실제로 내용을 보여주는 email-list의 template <div class="card"> <div class="card-body py-1" *ngFor="let email of emailList"> <h6 class="card-title mb-0 trim">{{ email.subject }}</h6> <small class="card-text trim">{{ email.from }}</small> <hr class="mt-1 mb-0"> </div> </div> 4-3-2 위에서 보여줄 emailList를 받아오는 email-list 컴포넌트 클래스 import { Component, OnInit, Input } from '@angular/core'; import { EmailListItem } from '../email-list-item'; @Component({ selector: 'app-email-list', templateUrl: './email-list.component.html', styleUrls: ['./email-list.component.css'] }) export class EmailListComponent implements OnInit { @Input() emailList: EmailListItem[] = [] constructor() { } ngOnInit(): void { } } 4-3-3 이메일 리스트가 표시될 공간 보다 이메일 제목이 길 경우 ... 로 처리하는 css를 추가한다. 4-3-3-1 email-list.component.css 파일 .content { width: 90% } .trim { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; width: 100% } 5. 결과화면
/* * Ejemplo de componente de tipo clase que dispone de los métodos de ciclo de vida */ import React from 'react' import PropTypes from 'prop-types' class LifeCycleExample extends React.Component { constructor(props) { super(props) console.log('CONSTRUCTOR: Cuando se instancia el componente') } componentWillMount() { console.log('WILLMOUNT: Antes del montaje del componente') } componentDidMount() { console.log('DIDMOUNT: Cuando se monta el componente') } componentWillReceiveProps(nextProps) { console.log('WILLRECEIVEPROPS: Si va a recibir nuevas props') } shouldComponentUpdate(nextProps, nextState) { /* Sirve para controlar si el componente debe o no actualizarse */ // return true o false console.log('') } componentWillUpdate(nextProps, nextState) { console.log('WILLUPDATE: Antes de actualizarse') } componentDidUpdate(prevProps, prevState) { console.log('DIDUPDATE: Después de actualizarse') } componentWillUnmount() { console.log('WILLUNMOUNT: Antes de desaparecer') } } LifeCycleExample.propTypes = { }
from django.db.models import Sum from django.http import HttpResponse from django.shortcuts import get_object_or_404 from django_filters.rest_framework import DjangoFilterBackend from djoser import views as djoser_views from rest_framework import status, viewsets from rest_framework.decorators import action from rest_framework.permissions import SAFE_METHODS, IsAuthenticated from rest_framework.response import Response from api.paginations import ApiPagination from api.permissions import AdminOrReadOnlyPermission from recipes.models import Ingredient, IngredientInRecipe, Recipe, Tag from users.models import User from .filters import IngredientFilter, RecipeFilter from .serializers import ( FavoritedSerializer, FollowSerializer, FollowUserSerializer, IngredientSerializer, RecipeReadSerializer, RecipeWriteSerializer, ShoppingCartSerializer, TagSerializer, ) class CustomUserViewSet(djoser_views.UserViewSet): """Работа с пользователями.""" http_method_names = ['get', 'post', 'delete'] @action( detail=True, methods=['post'], permission_classes=(IsAuthenticated,)) def subscribe(self, request, id): """Создаёт связь между пользователями.""" user_to_subscribe = get_object_or_404(User, pk=id) user = request.user serializer = FollowSerializer( data={ 'user': user.username, 'following': user_to_subscribe.username, }, context={'request': request}, ) serializer.is_valid(raise_exception=True) serializer.save() return Response( {'detail': 'Подписка успешно создана.'}, status=status.HTTP_201_CREATED,) @subscribe.mapping.delete def unsubscribe(self, request, id): """Удалет связь между пользователями.""" user_to_unsubscribe = get_object_or_404(User, pk=id) user = request.user serializer = FollowSerializer( data={ 'user': user.username, 'following': user_to_unsubscribe.username, }, context={'request': request}, ) serializer.is_valid(raise_exception=True) follow = user_to_unsubscribe.following.filter(user=user) follow.delete() return Response(status=status.HTTP_204_NO_CONTENT) @action( detail=False, methods=['get'], permission_classes=(IsAuthenticated,), serializer_class=FollowUserSerializer,) def subscriptions(self, request): """Отображает все подписки пользователя.""" followed_users = User.objects.filter(following__user=self.request.user) page = self.paginate_queryset(followed_users) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(followed_users, many=True) return Response(serializer.data) class RecipeViewSet(viewsets.ModelViewSet): """Работа с рецептами: [GET, POST, DELETE, PATCH].""" queryset = Recipe.objects.all() pagination_class = ApiPagination filter_backends = (DjangoFilterBackend,) filterset_class = RecipeFilter def get_serializer_class(self): """Выбор сериализатора при безопасных и не безопасных методах.""" if self.request.method in SAFE_METHODS: return RecipeReadSerializer return RecipeWriteSerializer @action( detail=True, methods=['post'], permission_classes=(IsAuthenticated,),) def favorite(self, request, pk): """ Получить/добавить рецепт из/в избранного/е у текущего пользоватля. """ serializer = FavoritedSerializer( data={ 'author': request.user.pk, 'recipe': pk, }, context={'request': request}, ) serializer.is_valid(raise_exception=True) serializer.save() return Response( {'detail': 'Рецепт успешно добавлен в избранное.'}, status=status.HTTP_201_CREATED,) @favorite.mapping.delete def unfavorite(self, request, pk): """ Удалить рецепт из избранного у текущего пользоватля. """ serializer = FavoritedSerializer( data={ 'author': request.user.pk, 'recipe': pk, }, context={'request': request}, ) serializer.is_valid(raise_exception=True) recipe = get_object_or_404(Recipe, pk=pk) favorites = recipe.favorites.filter(author=request.user) favorites.delete() return Response(status=status.HTTP_204_NO_CONTENT) @action( detail=True, methods=['post'], permission_classes=[IsAuthenticated],) def shopping_cart(self, request, pk): """ Получить/добавить рецепт из/в избранного/е из списка покупок у текущего пользователя. """ serializer = ShoppingCartSerializer( data={ 'author': request.user.pk, 'recipe': pk, }, context={'request': request}, ) serializer.is_valid(raise_exception=True) serializer.save() return Response( {'detail': 'Рецепт успешно добавлен в список покупок.'}, status=status.HTTP_201_CREATED,) @shopping_cart.mapping.delete def unshopping_cart(self, request, pk): """ Удалить рецепт из списка покупок у текущего пользоватля. """ serializer = ShoppingCartSerializer( data={ 'author': request.user.pk, 'recipe': pk, }, context={'request': request}, ) serializer.is_valid(raise_exception=True) recipe = get_object_or_404(Recipe, pk=pk) shopping_cart = recipe.shopping_cart.filter(author=request.user) shopping_cart.delete() return Response(status=status.HTTP_204_NO_CONTENT) @action( detail=False, methods=['get'], url_path='download_shopping_cart', url_name='download_shopping_cart', permission_classes=(IsAuthenticated,),) def download_shopping_cart(self, request): """ Скачать список покупок для выбранных рецептов, данные которых суммируются. """ user = request.user ingredients = ( IngredientInRecipe.objects.filter( recipe__shopping_cart__author=request.user ) .values('ingredient__name', 'ingredient__measurement_unit') .annotate(amount=Sum('amount'))) shopping_list = [ f'{ingredient["ingredient__name"]}:' f'{ingredient["ingredient__measurement_unit"]}' f' {ingredient["amount"]}' for ingredient in ingredients ] if not shopping_list: shopping_list = ['Корзина пуста.'] filename = f'{user.username}_shopping_cart.txt' response = HttpResponse( '\n'.join(shopping_list), content_type='text/plain') response['Content-Disposition'] = f'attachment; filename={filename}' return response class TagViewSet(viewsets.ModelViewSet): """Работа с тегами.""" queryset = Tag.objects.all() serializer_class = TagSerializer permission_classes = (AdminOrReadOnlyPermission,) pagination_class = None class IngredientViewSet(viewsets.ModelViewSet): """Работа с ингредиентами.""" queryset = Ingredient.objects.all() serializer_class = IngredientSerializer permission_classes = (AdminOrReadOnlyPermission,) pagination_class = None filter_backends = (DjangoFilterBackend,) filterset_class = IngredientFilter
package com.radityarin.gamelogue.domain.usecases.games import androidx.paging.PagingData import com.radityarin.gamelogue.data.source.remote.network.Status import com.radityarin.gamelogue.domain.model.Game import kotlinx.coroutines.flow.Flow interface GamesUseCase { fun getAllGames(): Flow<Status<List<Game>>> fun getAllGamesWithPagination(page: Int, pageSize: Int): Flow<Status<List<Game>>> fun searchGames(query: String): Flow<Status<List<Game>>> fun getGamesDetail(id: Int): Flow<Status<Game>> fun getFavoriteGames(): Flow<Status<List<Game>>> fun insertFavoriteGame(game: Game) fun deleteFavoriteGame(game: Game) fun getGamesPagination(): Flow<PagingData<Game>> }
import { useSearchParams } from "react-router-dom"; import useDebounce from "./useDebounce"; import { useQuery } from "@tanstack/react-query"; import { getBooks } from "../utils/openlibrary-api"; const SEARCH_INPUT_DEBOUNCE_MS = 1000; type Props = { limit: number; }; export function useSearchResults({ limit }: Props) { const [searchParams] = useSearchParams(); const searchTerm = searchParams.get("search"); const debouncedSearchTerm = useDebounce(searchTerm, SEARCH_INPUT_DEBOUNCE_MS); const hasSearchTerm = !!debouncedSearchTerm; return useQuery({ queryKey: ["books", { searchTerm: debouncedSearchTerm, limit }], queryFn: () => getBooks({ ...(hasSearchTerm && { searchTerm: debouncedSearchTerm }), limit, }), enabled: hasSearchTerm, }); }
QueryReference: A Query is a request we make to firestone to give us something from the db firestone returns us 2 types of object: refernces and snapshots Of these objects, they can be either Document or Collection versions firestone will always return us these objects, even if nothin exists from that Query A QueryReference object is an object that represents the "current" place in the db that we are quering. We get them by calling either: firestone.doc('/user/:userId'); firestone.collections('/users'); The QueryReference object does not have the actual data of the collection or Document. It instead has properties that tell us details about it, or the method to get the snapshot object which gives us te data we are looking for. ////// useEffect Cheat Sheet ComponentDidMount //Class componentDidMount() { console.log('I just mounted!'); } //Hooks useEffect(() => { console.log('I just mounted!'); }, []) ComponentWillUnmount //Class componentWillUnmount() { console.log('I am unmounting'); } //Hooks useEffect(() => { return () => console.log('I am unmounting'); }, []) ComponentWillReceiveProps //Class componentWillReceiveProps(nextProps) { if (nextProps.count !== this.props.count) { console.log('count changed', nextProps.count); } } //Hooks useEffect(() => { console.log('count changed', props.count); }, [props.count])
import React, { useContext, useRef, useState } from 'react'; import './Navbar.css'; import logo from '../Assets/logo.png'; import cart_icon from '../Assets/cart_icon.png'; import { Link } from 'react-router-dom'; import { ShopContext } from '../../Context/ShopContext'; import nav_dropdown from '../Assets/nav_dropdown1.png'; const Navbar = () => { const [menu, setMenu] = useState("shop"); const {getTotalCartItem} = useContext(ShopContext); const menuRef = useRef(); const dropdown_toggle = (e) => { menuRef.current.classList.toggle('nav-menu-visible'); e.target.classList.toggle('open'); } return ( <div className='navbar'> <div className='nav-logo'> <img src={logo} alt='logo' /> <p>ECOMMERCE</p> </div> <img className='nav-dropdown' src={nav_dropdown} alt='drop_down-icon' onClick={dropdown_toggle}/> <ul ref={menuRef} className='nav-menu'> <li onClick={() => {setMenu("shop")}} className={menu === "shop" ? "active" : ""} > <Link to='/' style={{textDecoration : 'none'}}> Shop</Link></li> <li onClick={() => {setMenu("mens")}} className={menu === "mens" ? "active" : ""}> <Link to='/mens' style={{textDecoration : 'none'}}> Men</Link></li> <li onClick={() => {setMenu("womens")}} className={menu === "womens" ? "active" : ""}> <Link to='/womens' style={{textDecoration : 'none'}}>Women</Link> </li> <li onClick={() => {setMenu("kids")}} className={menu === "kids" ? "active" : ""}> <Link to='/kids' style={{textDecoration : 'none'}}>Kids</Link> </li> </ul> <div className='nav-login-cart'> {localStorage.getItem('auth-token') ? <button onClick={()=>{localStorage.removeItem('auth-token'); window.location.replace('/') }} >Logout</button> : <Link to='/login'> <button>Sign In</button></Link>} <Link to='/cart'> <img src={cart_icon} alt='cart'/></Link> <div className='nav-cart-count'>{getTotalCartItem()}</div> </div> </div> ) } export default Navbar;
`v.1.0 - Diciembre 2023` ![[Pasted image 20231214021434.png]] Ref: https://flask.palletsprojects.com/en/3.0.x/ Mínima Aplicación ```python from flask import Flask app = Flask(__name__) @app.route("/") def hello_world(): return "<p>Hello, World!</p>" ``` ## 5 EJERCICIOS BÁSICOS ### Ejercicio 1: "Hola Mundo" con Flask **Objetivo**: Crear una API simple que responda con "Hola Mundo" cuando se acceda a la raíz. ```python from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hola Mundo' if __name__ == '__main__': app.run(debug=True) ``` **Tarea**: Ejecuta este script en tu entorno local y visita `http://localhost:5000` en tu navegador para ver el mensaje "Hola Mundo". ### Ejercicio 2: "Endpoint de Saludo Personalizado" **Objetivo**: Expandir la API para aceptar un nombre a través de la ruta y devolver un saludo personalizado. ```python from flask import Flask app = Flask(__name__) @app.route('/saludo/<nombre>') def saludo_personalizado(nombre): return f'Hola, {nombre}!' if __name__ == '__main__': app.run(debug=True) ``` **Tarea**: Accede `http://localhost:5000/saludo/<tu_nombre>` con tu propio nombre para recibir un saludo personalizado. ### Ejercicio 3: "Lista de Tareas Simple" **Objetivo:** Crear una API que permita al usuario obtener una lista de tareas. ```python from flask import Flask, jsonify app = Flask(__name__) tareas = [ {"id": 1, "titulo": "Comprar leche"}, {"id": 2, "titulo": "Estudiar Flask"} ] @app.route('/tareas', methods=['GET']) def get_tareas(): return jsonify({'tareas': tareas}) if __name__ == '__main__': app.run(debug=True) ``` **Tarea:** Usa `http://localhost:5000/tareas` para obtener la lista de tareas en formato JSON. ### Ejercicio 4: "Agregar Tarea" **Objetivo:** Permitir al usuario agregar una nueva tarea a la lista a través de un endpoint POST. ```python from flask import Flask, jsonify, request app = Flask(__name__) tareas = [ {"id": 1, "titulo": "Comprar leche"}, {"id": 2, "titulo": "Estudiar Flask"} ] @app.route('/tareas', methods=['GET']) def get_tareas(): return jsonify({'tareas': tareas}) @app.route('/tareas', methods=['POST']) def add_tarea(): if not request.json or not 'titulo' in request.json: abort(400) tarea = { 'id': tareas[-1]['id'] + 1, 'titulo': request.json['titulo'] } tareas.append(tarea) return jsonify({'tarea': tarea}), 201 if __name__ == '__main__': app.run(debug=True) ``` **Tarea:** Utiliza una herramienta como `curl` o Postman para enviar una solicitud POST a `http://localhost:5000/tareas` con un cuerpo JSON que incluya el título de la nueva tarea. Estos ejercicios cubren conceptos básicos de Flask y API REST, desde una ruta simple hasta la manipulación de datos con GET y POST. Son adecuados para principiantes y proporcionan una base sólida para construir aplicaciones más complejas.
import pandas as pd import time import cvxpy as cp import numpy as np from math import ceil from deap import base, creator, tools, algorithms from functools import partial from datetime import datetime import multiprocessing import os from sklearn.preprocessing import StandardScaler from sklearn.cluster import KMeans def cluster_map(cluster_df, n_clusters): # Apply KMeans clustering kmeans = KMeans(n_clusters=n_clusters) cluster_df['cluster'] = kmeans.fit_predict(cluster_df[['Lat', 'Long']]) return cluster_df def cluster_lob(pred_df,SELECTED_YEAR): lob_mass = pred_df[SELECTED_YEAR].sum()*0.2 cluster_df = pred_df[["Latitude","Longitude",SELECTED_YEAR]] grid_points_df = cluster_df[["Latitude","Longitude"]] scaler = StandardScaler() cluster_df[['Lat', 'Long']] = scaler.fit_transform(cluster_df[['Latitude', 'Longitude']]) n_clusters = 2 lob_cluster = 0 while True: cluster_df = cluster_map(cluster_df,n_clusters) test_df = cluster_df.groupby('cluster')[SELECTED_YEAR].sum().reset_index() test_df = test_df.sort_values(by=SELECTED_YEAR).reset_index() #display_clusters(cluster_df, n_clusters) if lob_mass>=test_df[SELECTED_YEAR][0]: lob_cluster = test_df["cluster"][0] #display_clusters(cluster_df,n_clusters) break n_clusters += 1 cluster_df = cluster_df[cluster_df['cluster']!=lob_cluster] old_to_new_map = cluster_df.reset_index() old_to_new_map = old_to_new_map.rename(columns = {'index' : 'Old'}) old_to_new_map = old_to_new_map.reset_index() old_to_new_map = old_to_new_map.rename(columns = {'index' : 'New'}) old_to_new_map = old_to_new_map[['Old','New']] return old_to_new_map def gen_depo_pos(length, n_depos): """ Generates a numpy vector of given 'length' with 'n_ones' ones placed at random positions. """ if n_depos > length: raise ValueError("Number of ones requested exceeds vector length.") vec = np.zeros(length, dtype=bool) random_positions = np.random.choice(length, n_depos, replace=False) vec[random_positions] = 1 return vec def gen_depo_service(length, n_depos): """ Generates a numpy vector of given 'length' with 'n_ones' ones placed at random positions. """ if n_depos > length: raise ValueError("Number of ones requested exceeds vector length.") vec = np.random.randint(0, n_depos, length) matrix = np.zeros((n_depos, length), dtype=bool) for col, value in enumerate(vec): matrix[value, col] = 1 return matrix def create_individual(n_postions,n_depos, toolbox): depo_pos = toolbox.depo_pos(length = n_postions,n_depos = n_depos) depo_serv_pre = toolbox.depo_serv(length = n_postions,n_depos = n_depos) indices = np.where(depo_pos == 1)[0] depo_serv = np.zeros((n_postions, n_postions), dtype=bool) for i,index in enumerate(indices): depo_serv[index] = depo_serv_pre[i] individual = np.column_stack((depo_pos, depo_serv)) # Make the individual an instance of creator.Individual individual = creator.Individual(individual) return individual # Fitness function def evaluate(individual, bio_vec, distance_mat,depo_cap): """Objective function.""" # Extracting depo_pos and depo_serv from individual depo_pos = individual[:, 0] depo_serv = individual[:, 1:] biomass_per_depo = depo_serv @ bio_vec penalty_vec = biomass_per_depo[biomass_per_depo>depo_cap] penalty_vec = penalty_vec ** 2 penalty_term = np.sum(penalty_vec) obj = 0.001*np.sum((distance_mat * depo_serv) @ bio_vec) - np.sum(biomass_per_depo) + penalty_term obj = float(obj) return (obj,) # Mutation Function def mutate(ind, n_postions): # Randomly select mutation type (1 for depot position, 2 for depot service) mutation_type = np.random.randint(1, 15) # Random depo pos switch (row) if mutation_type == 1: switch_1 = np.random.choice(np.where(ind[:, 0] > 0)[0]) switch_2 = np.random.randint(0, n_postions) ind[[switch_1, switch_2]] = ind[[switch_2, switch_1]] # Random depo serv switch (column) else: depo_pos = ind[:, 0] depo_serv = ind[:, 1:] pos_indices = np.where(depo_pos == 1) selected_pos = np.random.choice(pos_indices[0]) move_service = np.random.randint(0, n_postions) depo_serv[:, move_service] = 0 depo_serv[selected_pos, move_service] = 1 ind = np.column_stack((depo_pos, depo_serv)) ind = creator.Individual(ind) return ind, # Cross Overfunction def mate(ind1, ind2, n_postions): parent_pos_1 = ind1[:, 0] parent_serv_1 = ind1[:, 1:] parent_pos_2 = ind2[:, 0] parent_serv_2 = ind2[:, 1:] #choose child parent_pos_idx_1 = np.where(parent_pos_1) parent_pos_idx_2 = np.where(parent_pos_2) common_depo = np.intersect1d(parent_pos_idx_1, parent_pos_idx_2) child_pos_idx_1 = common_depo child_pos_idx_2 = common_depo pos_choice = np.vstack((np.setdiff1d(parent_pos_idx_1, parent_pos_idx_2), np.setdiff1d(parent_pos_idx_2, parent_pos_idx_1))) if len(pos_choice) > 0: for j in range(pos_choice.shape[1]): switch = np.random.randint(0, 2) choice_child_1 = pos_choice[switch,j] choice_child_2 = pos_choice[1-switch,j] child_pos_idx_1 = np.append(child_pos_idx_1, choice_child_1) child_pos_idx_1.sort() child_pos_idx_2 = np.append(child_pos_idx_2, choice_child_2) child_pos_idx_2.sort() child_pos_1 = np.zeros_like(parent_pos_1) child_pos_1[child_pos_idx_1] = 1 child_pos_2 = np.zeros_like(parent_pos_2) child_pos_2[child_pos_idx_2] = 1 combined_serv = np.logical_or(parent_serv_1, parent_serv_2).astype(bool) # Build child 1 serv child_serv_1 = np.zeros((n_postions,n_postions), dtype=bool) for row_idx in child_pos_idx_1: child_serv_1[row_idx] = combined_serv[row_idx] check_sum_1 = np.sum(child_serv_1, axis=0) for col, service_sum in enumerate(check_sum_1): if service_sum == 1: continue elif service_sum == 0: switch_on_choice = np.random.choice(child_pos_idx_1) child_serv_1[switch_on_choice,col] = 1 elif service_sum == 2: switch_off_choices = np.where(child_serv_1[:,col])[0] switch_off_choice = np.random.choice(switch_off_choices) child_serv_1[switch_off_choice,col] = 0 # Build child 2 serv child_serv_2 = np.zeros((n_postions,n_postions), dtype=bool) for row_idx in child_pos_idx_2: child_serv_2[row_idx] = combined_serv[row_idx] check_sum_2 = np.sum(child_serv_2, axis=0) for col, service_sum in enumerate(check_sum_2): if service_sum == 1: continue elif service_sum == 0: switch_on_choice = np.random.choice(child_pos_idx_2) child_serv_2[switch_on_choice,col] = 1 elif service_sum == 2: switch_off_choices = np.where(child_serv_2[:,col])[0] switch_off_choice = np.random.choice(switch_off_choices) child_serv_2[switch_off_choice,col] = 0 # Build children child1 = creator.Individual(np.column_stack((child_pos_1, child_serv_1))) child2 = creator.Individual(np.column_stack((child_pos_2, child_serv_2))) return child1, child2 def optimal_MILP_solve(n_depos, bio_vec, distance_mat,DEPO_CAP): n = len(bio_vec) # Create the variable depot matrix of 1485x1485 elements depo_service = cp.Variable((n, n), nonneg=True) # Binary decision variable for whether a depot is placed at a location i depo_pos = cp.Variable(n, boolean=True) # Add the objective function obj = cp.Minimize(0.001*cp.sum(cp.multiply(distance_mat, depo_service) @ bio_vec) - cp.sum(depo_service @ bio_vec)) #+ DEPO_CAP*cp.sum(depo_pos) # Add the amount of biomass procured per harvesting site = biomass forecated for harvesting site # This case is stricter than the problem statement constraint. It has to be because I've already dropped 20% of the biomass. This can be improved in the next iter. col_summer = np.ones(n) constraints = [depo_service.T @ col_summer == 1] # Ensure the allocation to a depot is zero if the depot is not active for i in range(n): constraints.append(depo_service[i,:] <= depo_pos[i]) # Add the depot processing capacity constraint constraints.append(depo_service @ bio_vec <= 20000) # Add the total processing constraint constraints.append(cp.sum(depo_service @ bio_vec) >= 0.8*np.sum(bio_vec)) # Add max depot constraint constraints.append(cp.sum(depo_pos) == n_depos) # Solve the problem prob = cp.Problem(obj, constraints) prob.solve(solver=cp.MOSEK,verbose=False) optimal_indv = np.column_stack((depo_pos.value, depo_service.value)) optimal_fitness = prob.value return optimal_indv,optimal_fitness def main(toolbox): #######PARAMETERS####### export_dir = "../optim_files" SELECTED_YEAR = "2018" DEPO_CAP = 20000 ##Load Opt Data dist_df = pd.read_csv("Distance_Matrix.csv") dist_df = dist_df.drop(columns="Unnamed: 0") predection_values = pd.read_feather("predictions_for_2018_2019.ftr") # Do cluster reduction old_to_new_map = cluster_lob(predection_values,SELECTED_YEAR) old_to_new_map.to_feather(os.path.join(export_dir,"old_to_new_map.ftr")) keep_values = old_to_new_map["Old"].values # Create Distance Matrix distance_mat = dist_df.values distance_mat = distance_mat[keep_values][:, keep_values] # Create Bio Vec bio_vec = predection_values[SELECTED_YEAR].values bio_vec = bio_vec[keep_values] # Calculate number of depos bio_total = np.sum(predection_values[SELECTED_YEAR].values)*0.8 n_depos = ceil(bio_total/DEPO_CAP) # Set number of locations n_postions = len(bio_vec) #Population Size pop_size = 1000 #Number Generations n_gen = 150 # Probability of mating prob_mating = 0.7 # Probability of mutating prob_mutating = 0.2 ######################### # Individual setup creator.create("FitnessMin", base.Fitness, weights=(-1.0,)) creator.create("Individual", np.ndarray, fitness=creator.FitnessMin) # Register the depot service attribute generator toolbox.register("depo_serv", gen_depo_service, length=n_postions, n_depos=n_depos) # Register the depot position attribute generator toolbox.register("depo_pos", gen_depo_pos, length=n_postions, n_depos=n_depos) # Individual generator create_individual_fixed = partial(create_individual, n_postions=n_postions, n_depos=n_depos, toolbox=toolbox) toolbox.register("individual", tools.initIterate, creator.Individual, create_individual_fixed) toolbox.register("population", tools.initRepeat, list, toolbox.individual) # Register Fitness function toolbox.register("evaluate", partial(evaluate, bio_vec=bio_vec, distance_mat=distance_mat, depo_cap=DEPO_CAP)) # Register the mustate function toolbox.register("mutate", mutate, n_postions=n_postions) # Register the crossover function toolbox.register("mate", mate, n_postions=n_postions) # Register the selection function toolbox.register("select", tools.selBest) # Configure HOF for numpy array hof = tools.HallOfFame(1, similar=np.array_equal) pop = toolbox.population(n=pop_size) start_fit = map(toolbox.evaluate, pop) fitnesses_list = list(start_fit) mean_fitness_start = sum(fit[0] for fit in fitnesses_list) / len(fitnesses_list) # Benchmark Start start_time = time.time() print(f"Starting Optimization: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") final_pop = algorithms.eaMuPlusLambda(pop, toolbox, 300, 700, prob_mating, prob_mutating, ngen=n_gen, stats=None, halloffame=hof, verbose=True) #Benchmark End end_time = time.time() elapsed_time = end_time - start_time print(f"Elapsed Time: {elapsed_time:.6f} seconds") #pool.close() best_individual = hof[0] #Print Random Fitness print(f"Random Fitness: {mean_fitness_start}") print(f"Best individual is:\n {best_individual}\nwith fitness: {best_individual.fitness}") #Export date_string = datetime.now().strftime('%Y-%m-%d %H_%M_%S') np.save(os.path.join(export_dir,f'depo_pos_ga_opt.npy'), best_individual) if __name__ == '__main__': #pool = multiprocessing.Pool(4) # Create toolbox toolbox = base.Toolbox() #toolbox.register("map", pool.map) main(toolbox)
# libreria que incluye algunos conjuntos de datos # y asociada al libro de igual titulo library(AppliedPredictiveModeling) library(caret) # se selecciona el conjunto de datos de interes: mtcars. Contiene # 32 instancias y 11 variables: todas son numericas data(mtcars) # se obtiene resumen de los datos summary(mtcars) # se fija la semilla para el generador de numeros aleatorios, # con lo que el experimento es reproducible. Para comportamiento # normal deberia desactivarse esta opcion set.seed(1) # se genera un vector con tantos indices como instancias haya en # el conjunto de datos indices <- seq(1,nrow(mtcars),by=1) # se pasa como argumento el vector de indices y de el se van # seleccionando valores, con la probabilidad indicada. De esta # forma, el vector resultante deberia tener aproximadamente # el 80% de valores del pasado como primer argumento indicesEntrenamiento <- caret::createDataPartition(indices, p=0.8, list = FALSE) # ahora se seleccionan los indices de los datos del conjunto de test indicesTest <-indices[-indicesEntrenamiento] # con esto es facil ahora seleccionar los conjuntos de datos datosEntrenamiento <- mtcars[indicesEntrenamiento, ] datosTest <- mtcars[indicesTest, ] # si necesitamos obtener varias particiones, por ejemplo, para hacer # validacion cruzada mediante metodo Montecarlo, podemos repetir # el proceso el numero de veces que deseemos. Ahora el resultado # sera una matriz con tantas filas como muestras y tantas columnas # como repeticiones se hayan indicado particionadosEntrenamiento <- caret::createDataPartition(indices, p = .80, list= FALSE, times = 10) # De esta forma, cada columna contiene los indices de las instancias # seleccionada de una de las particiones particion1 <- particionadosEntrenamiento[,1] particion10 <- particionadosEntrenamiento[,10] # ahora podemos obtener los indices de las instancias de test para # cada caso. En primer lugar se calcula el numero de instancias en # el conjunto test. El objetivo es crear una matriz con tantas # filas como tenga el conjunto de test y tantas columnas como # variantes del particionado se hayan generado (en este caso 10). # De esta forma, cada columna servira para almacenar un conjunto # de test. En primer lugar se determina el tam. del conjunto # de test tamConjuntoTest <- nrow(mtcars) - nrow(particionadosEntrenamiento) # se crea una matriz para almacenar las sentencias de test de # todas las particiones particionadosTest <- matrix(nrow=tamConjuntoTest, ncol = 10) # se obtienen de forma iterativa considerando las particiones de # entrenamiento for(i in 1:10){ particionadosTest[,i] <- indices[-particionadosEntrenamiento[,i]] } # tambien es posible usar createResamples (para bootstrap), # createFolds (para k-fold cross-validation) y createMultiFolds # (para repeticiones de cross-validation). Por ejemplo, imaginemos # deseamos crear 10 particiones para validacion cruzada: el siguiente # metodo me ofrece las particiones de forma que pueda usarlas # posteriormente set.seed(8) particionesEntrenamiento <- caret::createFolds(indices, k = 10, list = TRUE, returnTrain = TRUE) # el objeto devuelto ahora por R es una lista con tantas entradas # como indique k. Cada una de las entradas es un vector con los # indices de las instancias generadas particion1 <- particionesEntrenamiento[[1]] particion10 <- particionesEntrenamiento[[10]] # de nuevo podemos usar la misma estrategia de antes para generar los # indices de las correspondientes particiones de test particionesTest <- list() for(i in 1:10){ particionesTest[[i]] <- indices[-particionesEntrenamiento[[i]]] } # para que sea mas visible, vamos a considerar que tenemos 10 # instancias indices <- seq(1,10) particionesEntrenamiento <- caret::createFolds(indices, k = 10, returnTrain = TRUE) # e igual para los indices de test particionesTest <- list() for(i in 1:10){ particionesTest[[i]] <- indices[-particionesEntrenamiento[[i]]] } # probamos el uso de la tecnica de bootstrap: ahora habra # muestras repetidas y ademas todas las particiones tienen # el mismo numero de muestras que el conjunto de datos original particionBootstrap <- caret::createResample(indices, times=10) # tambien podemos probar la creacion de multiplesParticiones: en este # caso 3 particionados completos, de 10 particiones cada una de ellas multiplesParticiones <- caret::createMultiFolds(indices, k=10, times=3)
import { Box, Button, Grid, Modal, TextField } from "@mui/material"; import React, { useEffect, useState } from "react"; import { socket } from "../../graphql"; import productsService from "../../services/productsService"; import { Toast } from "../../utils/alerts"; import { errorInput, validateForm } from "../../utils/hooks/useValidate"; import useProductCreate from "../ProductCreate/useProductCreate"; const ProductUpdate = ({ open, handleClose, inputData }: any) => { const { style, initialState } = useProductCreate(); const [input, setInput] = React.useState(initialState); const [errorInput, setErrorInput] = useState<errorInput>({}); useEffect(() => { if (Object.keys(inputData).length) { setInput(inputData); } }, [inputData]); const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); try { let newProduct = await productsService.updateProduct({ ...input }); if (newProduct) { setInput(initialState); socket.emit("updateProduct"); handleClose(); Toast.fire({ icon: "success", title: "Producto modificado correctamente!", }); } } catch (error) { Toast.fire({ icon: "error", title: "Se produjo un error al modificar el producto!", }); console.log("error", error); } }; const handleInputChange = ({ target, }: React.ChangeEvent<HTMLInputElement>) => { setInput({ ...input, [target.name]: target.value }); setErrorInput(validateForm({ ...input, [target.name]: target.value })); }; return ( <div> <Modal open={open} onClose={handleClose} aria-labelledby="modal-modal-title" aria-describedby="modal-modal-description" > <Box sx={style}> <form onSubmit={handleSubmit}> <Grid container spacing={1}> <Grid xs={12} sm={6} item> <TextField error={!errorInput.name ? false : true} helperText={errorInput.name} label="Nombre" name="name" type="text" id="name" placeholder="Nombre del producto" className="input-field" onChange={handleInputChange} value={input.name} variant="outlined" fullWidth required /> </Grid> <Grid xs={12} item sm={6}> <TextField label="Precio" name="price" type="number" id="price" placeholder="Precio del producto" className="input-field" onChange={handleInputChange} value={input.price} variant="outlined" fullWidth required error={!errorInput.price ? false : true} helperText={errorInput.price} /> </Grid> <Grid xs={12} item> <TextField label="Descripción" name="description" type="text" id="description" placeholder="Descripción del producto" className="input-field" onChange={handleInputChange} value={input.description} variant="outlined" fullWidth required error={!errorInput.description ? false : true} helperText={errorInput.description} /> </Grid> <Grid xs={12} item> <TextField label="Imagen" name="image" type="text" id="image" placeholder="image del producto" className="input-field" onChange={handleInputChange} value={input.image} variant="outlined" fullWidth required error={!errorInput.image ? false : true} helperText={errorInput.image} /> </Grid> <Grid xs={12} item> <Button color="primary" variant="outlined" type="submit" className="btn-primary" > Aceptar </Button> <Button color="primary" variant="outlined" className="btn-primary" onClick={handleClose} > Cancelar </Button> </Grid> </Grid> </form> </Box> </Modal> </div> ); }; export default ProductUpdate;
/* * BSD 3-Clause License * * Copyright (c) 2021-2022, InterlockLedger * 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. * * 3. 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. */ package io.il2.iltags.ilint; import static io.il2.iltags.ilint.ILIntBase.*; import java.io.DataOutput; import java.io.IOException; /** * This class contains the static methods required to encode values using the * ILInt format. * * @author Fabio Jun Takada Chino * @since 2022.05.26 */ public class ILIntEncoder { /** * Returns the ILInt encoded size. The value of v will be viewed as an unsigned * value. * * @param u The value. * @return The number of bytes required to encode the value. */ public static int encodedSize(long u) { // Do not forget to treat u as an unsigned value. if (Long.compareUnsigned(u, ILINT_BASE64) < 0) { return 1; } else if (Long.compareUnsigned(u, (0xFFl + ILINT_BASE64)) <= 0) { return 2; } else if (Long.compareUnsigned(u, (0xFFFFl + ILINT_BASE64)) <= 0) { return 3; } else if (Long.compareUnsigned(u, (0x00FF_FFFFl + ILINT_BASE64)) <= 0) { return 4; } else if (Long.compareUnsigned(u, (0xFFFF_FFFFl + ILINT_BASE64)) <= 0) { return 5; } else if (Long.compareUnsigned(u, (0x00FF_FFFF_FFFFl + ILINT_BASE64)) <= 0) { return 6; } else if (Long.compareUnsigned(u, (0xFFFF_FFFF_FFFFl + ILINT_BASE64)) <= 0) { return 7; } else if (Long.compareUnsigned(u, (0x00FF_FFFF_FFFF_FFFFl + ILINT_BASE64)) <= 0) { return 8; } else { return 9; } } /** * Returns the signed ILInt encoded size. * * @param s The value. * @return The number of bytes required to encode the value. */ public static int signedEncodedSize(long s) { return encodedSize(Signed.pack(s)); } /** * Encodes the given unsigned 64-bit integer using the ILInt format. * * @param u The value to encode. * @param out The data output. * @return The number of bytes used. * @throws IOException In case of error. */ public static int encode(long u, DataOutput out) throws IOException { int encodedSize = encodedSize(u); if (encodedSize == 1) { out.write((int) (u & 0xFF)); return encodedSize; } else { byte[] tmp = new byte[9]; tmp[0] = (byte) (ILINT_BASE + encodedSize - 2); u -= ILINT_BASE64; for (int i = encodedSize - 1; i > 0; i--) { tmp[i] = (byte) (u & 0xFF); u = u >>> 8; } out.write(tmp, 0, encodedSize); return encodedSize; } } /** * Encodes the given signed 64-bit integer using the signed ILInt format. * * @param s The signed value to encode. * @param out The data output. * @return The number of bytes used. * @throws IOException In case of error. */ public static int encodeSigned(long s, DataOutput out) throws IOException { return encode(Signed.pack(s), out); } }
import type { HTMLAttributes } from "react"; import config from "config/site.json"; import NextHead from "next/head"; import { useRouter } from "next/router"; export type ContainerProps = HTMLAttributes<HTMLElement>; export type HeadProps = { title?: string; description?: string; image?: string; type?: "website" | "article"; publishDate?: string; }; const Head = ({ title, description, image, type, publishDate }: HeadProps) => { const router = useRouter(); const titleWithSiteName = title ? `${title} - ${config.name}` : config.name; return ( <NextHead> <title>{titleWithSiteName}</title> <meta content={description || config.defaults.description} name="description" /> {publishDate && ( <meta property="article:published_time" content={publishDate} /> )} <link rel="canonical" href={`${config.url}${router.asPath}`} /> <meta name="robots" content="follow, index" /> <meta key="googlebot" name="googlebot" content="follow, index" /> <meta property="og:type" content={type || config.defaults.type} /> <meta property="og:site_name" content={config.name} /> <meta property="og:title" content={titleWithSiteName} /> <meta property="og:description" content={description || config.defaults.description} /> <meta property="og:url" content={`${config.url}${router.asPath}`} /> <meta property="og:image" content={image || config.defaults.image} /> <meta name="twitter:card" content="summary_large_image" /> <meta name="twitter:site" content={config.twitter} /> <link rel="icon" type="image/x-icon" sizes="48x48" href="/favicons/favicon.ico" /> <link rel="icon" type="image/png" sizes="16x16" href="/favicons/favicon-16x16.png" /> <link rel="icon" type="image/png" sizes="32x32" href="/favicons/favicon-32x32.png" /> <link rel="apple-touch-icon" sizes="180x180" href="/favicons/apple-touch-icon.png" /> <link rel="icon" type="image/png" sizes="512x512" href="/favicons/favicon-512x512.png" /> <link rel="manifest" href="/site.webmanifest" /> <link rel="mask-icon" href="/favicons/safari-pinned-tab.svg" color="#ffffff" /> <meta name="msapplication-TileColor" content="#b91d47" /> <meta content="#ffffff" name="theme-color" /> </NextHead> ); }; export default Head;
#include <bits/stdc++.h> using namespace std; #define ll long long int class Node { public: int data; Node *next; Node(int data) { this->data = data; this->next = NULL; } ~Node() { if (this->next != NULL) { delete next; this->next = NULL; } } }; void insertAtHead(Node *&head, int d) { Node *temp = new Node(d); temp->next = head; head = temp; } void insertAtTail(Node *&tail, int d) { Node *temp = new Node(d); tail->next = temp; tail = temp; } void insertAtPosition(Node *&head, Node *&tail, int position, int d) { Node *temp = head; int cnt = 1; if (position == 1) { insertAtHead(head, d); return; } while (cnt < position - 1) { temp = temp->next; cnt++; } if (temp->next == NULL) { insertAtTail(tail, d); return; } Node *nodeToInsert = new Node(d); nodeToInsert->next = temp->next; temp->next = nodeToInsert; } void print(Node *&head) { Node *temp = head; while (temp != NULL) { cout << temp->data << " "; temp = temp->next; } cout << endl; } void deleteNode(int position, Node *&head) { if (position == 1) { Node *temp = head; head = head->next; temp->next = NULL; delete temp; } else { Node *curr = head; Node *prev = NULL; int cnt = 1; while (cnt < position) { prev = curr; curr = curr->next; cnt++; } prev->next = curr->next; curr->next = NULL; delete curr; } } bool isCircular(Node *head) { if (head == NULL) { return true; } Node *temp = head->next; while (temp != NULL && temp != head) { temp = temp->next; } if (temp == head) { return true; } else { return false; } } int main() { Node *node1 = new Node(4); // cout << node1->data << endl; Node *head = node1; Node *tail = node1; // print(head); // insertAtHead(head, 12); // print(head); insertAtTail(tail, 20); insertAtTail(tail, 25); // print(head); insertAtPosition(head, tail, 3, 22); print(head); deleteNode(3, head); print(head); print(tail); return 0; }
// Ong, Camron (S13) | Tan, Arvin (S13) // CALLER FOR C AND ASM KERNELS #include <stdio.h> #include <stdlib.h> #include <time.h> #include "C_Kernel.h" extern void asm_domath(long long int n, float a, float x[], float y[], float z[]); //extern float asm_domath(float a, float x, float y); #define RANDMAX 100 int main(int argc, char* argv[]) { int m[3] = { 20, 24, 30 }; for (int j = 0; j < 3; j++) { //int m[1] = { 20 }; //for (int j = 0; j < 1; j++) { long long n = 1LL << m[j]; int correct[30]; int max = 30; int count = 0; int temp; int time[30][2]; do { float A = 0.0f; A = (float)rand(); float* X = (float*)malloc(n * sizeof(float)); float* Y = (float*)malloc(n * sizeof(float)); float* Z = (float*)malloc(n * sizeof(float)); float* Z2 = (float*)malloc(n * sizeof(float)); clock_t start, end, total = 0; printf("Generating random numbers...\n"); start = clock(); for (long long i = 0; i < n; i++) { X[i] = (float)rand() / (RANDMAX * 100); Y[i] = (float)rand() / (RANDMAX * 100); Z[i] = 0.0f; Z2[i] = 0.0f; } end = clock(); printf("Done generating random numbers\n"); printf("Generated in %ld ms\n\n", (end - start) * 1000 / CLOCKS_PER_SEC); printf("Processing C kernel\n"); start = clock(); /* for (long long i = 0; i < n; i++) { Z[i] = c_domath2(A, X[i], Y[i]); } */ c_domath(n, A, X, Y, Z); end = clock(); printf("Total C Kernel time: %ld ms\n\n", (end - start) * 1000 / CLOCKS_PER_SEC); time[count][0] = end - start; printf("Processing ASM kernel\n"); start = clock(); /* for (long long i = 0; i < n; i++) { Z2[i] = asm_domath(A, X[i], Y[i]); } */ asm_domath(n, A, X, Y, Z2); end = clock(); printf("Total ASM Kernel time: %ld ms\n\n", (end - start) * 1000 / CLOCKS_PER_SEC); time[count][1] = end - start; int error = -1; // check if correct for (long long i = 0; i < n; i++) { if (Z[i] != Z2[i]) { printf("Error: Z[%lld] = %f, Z2[%lld] = %f\n", i, Z[i], i, Z2[i]); correct[count] = 0; error = 1; break; } } if (error == -1) { printf("No error found\n"); for (int i = 0; i < 10; i++) { printf("Z[%d] = %f, Z2[%d] = %f\n", i, Z[i], i, Z2[i]); } correct[count] = 1; } printf("\n"); free(X); free(Y); free(Z); free(Z2); count++; } while (count < max); long aveTime1 = 0; long aveTime2 = 0; char filename_c[20]; char filename_asm[20]; snprintf(filename_c, sizeof(filename_c), "R_C_Kernel_%d.txt", m[j]); snprintf(filename_asm, sizeof(filename_asm), "RR_ASM_Kernel_%d.txt", m[j]); for (int i = 0; i < max; i++) { aveTime1 += time[i][0]; aveTime2 += time[i][1]; FILE* file_c = fopen(filename_c, "a"); FILE* file_asm = fopen(filename_asm, "a"); fprintf(file_c, "%d,%d,%d\n", i, correct[i], time[i][0]); fclose(file_c); fprintf(file_asm, "%d,%d\n",i, time[i][1]); fclose(file_asm); } aveTime1 = (aveTime1 * 1000) / (max * CLOCKS_PER_SEC); aveTime2 = (aveTime2 * 1000) / (max * CLOCKS_PER_SEC); FILE* file_c = fopen(filename_c, "a"); FILE* file_asm = fopen(filename_asm, "a"); fprintf(file_c, "\nAverage time: %ld ms\n", aveTime1); fclose(file_c); fprintf(file_asm, "\nAverage time: %ld ms\n", aveTime2); fclose(file_asm); printf("Average time for C kernel: %ld ms\n", aveTime1); printf("Average time for ASM kernel: %ld ms\n", aveTime2); } return 0; }
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { LoginComponent } from './login/login.component'; import { SignUpComponent } from './sign-up/sign-up.component'; import { ValidateComponent } from './validate/validate.component'; import { Error1Component } from './error-1/error-1.component'; import { Error2Component } from './error-2/error-2.component'; const routes: Routes = [ { path: 'login', component: LoginComponent, data: { title: 'Login' } }, { path: 'validate', component: ValidateComponent, data: { title: 'Validate Code' } }, { path: 'sign-up', component: SignUpComponent, data: { title: 'Sign Up 1' } }, { path: 'error-1', component: Error1Component, data: { title: 'Error 1' } }, { path: 'error-2', component: Error2Component, data: { title: 'Error 2' } } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule], }) export class AuthenticationRoutingModule { }
import React from 'react'; import { useSelector } from 'react-redux'; import { Redirect, Route, Switch } from 'react-router-dom'; import { privateRoutes, publicRoutes, ROUTE_NAMES } from '../router'; const AppRouter = () => { const isAuth = useSelector((state) => state.auth.isLoggedIn); return isAuth ? ( <Switch> {privateRoutes.map((route) => ( <Route path={route.path} component={route.component} exact={route.exact} key={route.path} /> ))} <Redirect to={ROUTE_NAMES.MAP} /> </Switch> ) : ( <Switch> {publicRoutes.map((route) => ( <Route path={route.path} component={route.component} exact={route.exact} key={route.path} /> ))} <Redirect to={ROUTE_NAMES.LOGIN} /> </Switch> ); }; export default AppRouter;
<template> <div class="vaw-side-bar-wrapper" :class="[!state.isCollapse ? 'open-status' : 'close-status']" > <transition name="logo"> <Logo v-if="showLogo"/> </transition> <ScrollerMenu> <template #default> <SideBarItem v-for="item in menuList" :key="item.pUrl" :full-path="item.pUrl" :item="item" /> </template> </ScrollerMenu> <div class="mobile-shadow"></div> </div> </template> <script lang="ts"> import store from "../store"; import {defineComponent, computed, onMounted,ref} from "vue"; import {getUserInfo} from "@/utils/auth"; import {useRoute} from "vue-router"; import { hasDepartPrivilege, notNullUndefined } from "@/utils"; import {transformList2Tree} from "@/utils"; import constants from "@/utils/constants"; export default defineComponent({ name: "SideBar", props: { showLogo: { type: Boolean, default: true, }, }, setup() { const state = store.state; const menuList = ref([]) const transformStruct = (list)=> { const haveSub = Array.isArray(list.sub)&&list.sub.length>0; return { id: list.id, pName: list.name, pUrl: list.url, iconName:list.iconName, children: haveSub ? list.sub.map((i) => transformStruct(i)):[], }; }; const filterPcMenu = () => { let result = []; let rootList = []; // 从sessionStorage得到菜单结构 let tempMenuList = JSON.parse(sessionStorage.getItem('menuList')); //过滤父节点为空的菜单 tempMenuList = tempMenuList.filter(item=>{ return constants.isEmpty(item.fid) }) console.log("菜单",tempMenuList) rootList = (tempMenuList||[]).map((list)=>transformStruct(list)); console.log("新菜单",rootList) // const rootList2 = transformList2Tree(tempMenuList, 'id', 'fId'); const menuData = rootList.filter(item=>{ return constants.isEmpty(item.fId); }) menuList.value = menuData; } filterPcMenu(); return { state, menuList }; }, }); </script> <style scoped lang="scss"> @import "../styles/variables.scss"; .open-status { width: $menuWidth; box-shadow: 2px 5px 5px rgba(0, 0, 0, 0.12); //transition: all $transitionTime; } .close-status { width: $minMenuWidth; box-shadow: none; //transition: all $transitionTime; } .vaw-side-bar-wrapper { position: fixed; top: 0; left: 0; overflow-x: hidden; height: 100%; box-sizing: border-box; z-index: 99; .vaw-menu-wrapper { overflow-x: hidden; color: white; } .scrollbar { height: calc(100% - #{$logoHeight}) !important; } } .is-mobile { .open-status { width: $menuWidth; transform: translateX(0); transition: transform $transitionTime; } .close-status { width: $menuWidth; transform: translateX(-$menuWidth); transition: transform $transitionTime; box-shadow: none; } } </style> <style lang="scss"> @import "../styles/variables.scss"; .scrollbar-wrap-class { overflow-x: hidden !important; } .el-menu { --el-menu-hover-text-color: var(--el-color-primary) !important; --el-menu-hover-bg-color: var(--el-color-primary-light-8) !important; border-right: none !important; overflow: hidden; } .el-menu-item:hover { color: var(--el-menu-active-color); background-color: transparent; } .el-menu-item.is-active { color: var(--el-menu-active-color); background-color: var(--el-color-primary-light-8); } ::deep(.el-menu--collapse .el-sub-menu__title span) { display: none !important; } ::deep(.el-menu--collapse .el-sub-menu__title .el-sub-menu__icon-arrow) { display: none !important; } </style>
<script setup> import headerDatas from "@b-js/header/data.js"; import headerMethods from "@b-js/header/methods.js"; </script> <template> <section id="header"> <div id="menuToggle"> <span class="toggleBtn" @click="fn_toggleMenu"> <font-awesome-icon :icon="['fas', 'bars']" /> </span> </div> <div id="logo"> <a href="/" title="home"> <font-awesome-icon :icon="['fas', 'r']" />&nbsp; <font-awesome-icon :icon="['fas', 'm']" />&nbsp; <font-awesome-icon :icon="['fas', 'f']" />&nbsp; <font-awesome-icon :icon="['fas', 'r']" />&nbsp; <font-awesome-icon :icon="['fas', 'question']" /> </a> </div> <div id="searchBox"> <div id="searchIptBox"> <div id="preIcon"> <font-awesome-icon :icon="['fas', 'magnifying-glass']" /> </div> <input id="searchIpt" placeholder="검색" @focus="fn_focusSearch" @blur="fn_blurSearch" /> <div id="suffixIcon"> <font-awesome-icon :icon="['fas', 'magnifying-glass']" /> </div> </div> </div> <div id="buttonBox"> <div class="guest" v-show="!this.login"> <a class="headerBtn" href="/member/signup" title="signup"> <font-awesome-icon :icon="['fas', 'user-plus']" /> </a> <a class="headerBtn" href="#" title="login" @click="fn_toggleInfo"> <font-awesome-icon :icon="['fas', 'right-to-bracket']" /> </a> </div> <div class="user" v-show="this.login"> <a class="headerBtn" href="#" title="push"> <font-awesome-icon :icon="['fas', 'bell']" /> </a> <a class="headerBtn" href="#" title="mypage" @click="fn_toggleInfo"> <font-awesome-icon :icon="['fas', 'user']" /> </a> </div> <div id="loginInfo"> <form id="login" action="/member/loginProc" method="post" v-show="!this.login" > <div> <label for="username" class="col-3">아이디</label> <input type="text" name="mId" id="mId" class="col-8" /> </div> <div> <label for="mPw" class="col-3">비밀번호</label> <input type="password" name="mPw" id="mPw" class="col-8" /> </div> <div> <a class="btn btn-sm btn-primary" @click="fn_submitFrm"> 로그인 </a> </div> </form> <div id="info" v-show="this.login"> <div id="basicInfo" class="row"> <div id="thumImg" class="col-3"> <a id="tmpImg" class="display-6" v-show="this.tmpImg != ''" href="/member/settings" > {{ info.tmpImg }} </a> </div> <div id="basic" class="col-9"> <a id="mId" class="display-6" href="/member/settings"> @{{ info.mId }} </a> <a id="mUd" class="display-6" href="/member/settings"> 패스워드 변경까지 D-{{ info.mUd }} </a> </div> </div> <div id="setting" class="row infoMenu" @click="fn_infoMenu('/member/settings')" > <div id="" class="infoTxt col-9">계정설정</div> <div id="" class="infoIcon col-3"> <font-awesome-icon :icon="['fas', 'gear']" /> </div> </div> <div id="logout" class="row infoMenu" @click="fn_infoMenu('/logout')"> <div id="" class="infoTxt col-9">로그아웃</div> <div id="" class="infoIcon col-3"> <font-awesome-icon :icon="['fas', 'right-from-bracket']" /> </div> </div> </div> </div> </div> </section> </template> <script> export default { data() { return headerDatas; }, methods: headerMethods, mounted() { this.fn_loginChk(); }, }; </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> @import "@b-css/header/header.css"; </style>
package com.dsms.app.controller; import com.dsms.app.constants.Country; import com.dsms.app.constants.State; import com.dsms.app.constants.UserType; import com.dsms.app.entity.Address; import com.dsms.app.entity.CreditCard; import com.dsms.app.entity.User; import com.dsms.app.models.RegisterUser; import com.dsms.app.repository.UserRepository; import com.dsms.app.service.AdminService; import com.dsms.app.service.AppService; import com.dsms.app.service.AuthService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import java.util.HashSet; import java.util.Set; @Controller @RequestMapping("/") public class UserController { @Autowired UserRepository userRepository; @Autowired PasswordEncoder passwordEncoder; @Autowired AuthService authService; @GetMapping("/login/") public String login(Model model) { model.addAttribute("type", UserType.valueOf("USER")); return "login"; } @GetMapping("/register") public String showRegistrationForm(Model model) { model.addAttribute("register", new RegisterUser()); model.addAttribute("states", State.getStates()); model.addAttribute("countries", Country.getCountries()); return "register"; } @PostMapping("/register_acct") public String registerUser(RegisterUser user) { User new_user = user.getUser(); String pass = passwordEncoder.encode(new_user.getUserPassword()); new_user.setUserPassword(pass); Set<String> roles = new HashSet<>(); roles.add("USER"); // Assuming all registered users have the "USER" role new_user.setRoles(roles); authService.registerUser(user); return "redirect:/login/"; } @GetMapping("/logout/") public String logoutUser() { return "redirect:/login/"; } }
package com.mitch.dimlight.ui.screen.home import androidx.activity.ComponentActivity import androidx.annotation.StringRes import androidx.compose.ui.semantics.ProgressBarRangeInfo import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertRangeInfoEquals import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithText import com.mitch.dimlight.R import org.junit.Rule import org.junit.Test class HomeScreenTest { @get:Rule val composeTestRule = createAndroidComposeRule<ComponentActivity>() private fun getString(@StringRes id: Int) = composeTestRule.activity.resources.getString(id) @Test fun showsOffState_whenBrightnessIsZero() { composeTestRule.setContent { HomeScreen( brightnessLevel = 0, onTurnOnFlashlight = { }, onTurnOffFlashlight = { } ) } val expectedValue = 0f val expectedRange = 0f..100f /* * 1) slider is at zero * 2) text is 0/maxLevel * */ composeTestRule .onNodeWithContentDescription(getString(R.string.change_flashlight_brightness_level)) .assertIsDisplayed() .assertRangeInfoEquals( ProgressBarRangeInfo( current = expectedValue, range = expectedRange ) ) composeTestRule .onNodeWithText("0/100") .assertIsDisplayed() } }
import { DiscordAPIError, Message, MessageReaction, PartialMessage, PartialMessageReaction, PartialUser, RESTJSONErrorCodes, User, } from 'discord.js'; const IGNORED_ERRORS: (string | number)[] = [ RESTJSONErrorCodes.UnknownMessage, RESTJSONErrorCodes.UnknownChannel, RESTJSONErrorCodes.UnknownGuild, RESTJSONErrorCodes.UnknownUser, RESTJSONErrorCodes.UnknownInteraction, RESTJSONErrorCodes.MissingAccess, ]; export class PartialUtils { public static async fillUser(user: User | PartialUser): Promise<User | undefined> { if (user.partial) { try { return await user.fetch(); } catch (error) { if (error instanceof DiscordAPIError && IGNORED_ERRORS.includes(error.code)) { return; } else { throw error; } } } return user; } public static async fillMessage(msg: Message | PartialMessage): Promise<Message | undefined> { if (msg.partial) { try { return await msg.fetch(); } catch (error) { if (error instanceof DiscordAPIError && IGNORED_ERRORS.includes(error.code)) { return; } else { throw error; } } } return msg; } public static async fillReaction( msgReaction: MessageReaction | PartialMessageReaction ): Promise<MessageReaction | undefined> { if (msgReaction.partial) { try { msgReaction = await msgReaction.fetch(); } catch (error) { if (error instanceof DiscordAPIError && IGNORED_ERRORS.includes(error.code)) { return; } else { throw error; } } } const message = await this.fillMessage(msgReaction.message); if (!message) { return; } msgReaction.message = message; return msgReaction; } }
package com.appointment.appointmentservice.Mapper; import com.appointment.appointmentservice.dto.PatientDTO; import com.appointment.appointmentservice.entity.Patient; import org.modelmapper.ModelMapper; import org.modelmapper.convention.MatchingStrategies; import java.util.ArrayList; import java.util.List; public class PatientMapper implements EntityMapper<PatientDTO, Patient> { @Override public Patient toEntity(PatientDTO dto) { ModelMapper modelMapper=new ModelMapper(); modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE); return modelMapper.map(dto,Patient.class); } @Override public PatientDTO toDto(Patient entity) { ModelMapper modelMapper=new ModelMapper(); modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE); return modelMapper.map(entity,PatientDTO.class); } @Override public List<Patient> toEntity(List<PatientDTO> dtoList) { List<Patient>patients=new ArrayList<>(); ModelMapper modelMapper=new ModelMapper(); modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE); for (PatientDTO patientDTO:dtoList){ patients.add(modelMapper.map(patientDTO,Patient.class)); } return patients; } @Override public List<PatientDTO> toDto(List<Patient> entityList) { List<PatientDTO>patientDTOList=new ArrayList<>(); ModelMapper modelMapper=new ModelMapper(); modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE); for (Patient patient:entityList){ patientDTOList.add(modelMapper.map(patient,PatientDTO.class)); } return patientDTOList; } }
local M = {} -- Enable the following language servers -- Feel free to add/remove any LSPs that you want here. They will automatically be installed. -- -- Add any additional override configuration in the following tables. They will be passed to -- the `settings` field of the server config. You must look up that documentation yourself. -- -- If you want to override the default filetypes that your language server will attach to you can -- define the property 'filetypes' to the map in question. M.servers = { -- clangd = {}, -- gopls = {}, -- pyright = {}, -- rust_analyzer = {}, tsserver = {}, -- html = { filetypes = { 'html', 'twig', 'hbs'} }, lua_ls = { Lua = { workspace = { checkThirdParty = false }, telemetry = { enable = false }, -- NOTE: toggle below to ignore Lua_LS's noisy `missing-fields` warnings diagnostics = { disable = { 'missing-fields' }, globals = { 'vim' } }, }, }, } -- vim.lsp.handlers["textDocument/publishDiagnostics"] = -- vim.lsp.with( -- vim.lsp.diagnostic.on_publish_diagnostics, -- { -- virtual_text = true, -- } -- ) M.lines_enabled = true M.toggle_lsp_lines = function() M.lines_enabled = not M.lines_enabled vim.diagnostic.config({ virtual_lines = M.lines_enabled, virtual_text = not M.lines_enabled, severity_sort = not M.lines_enabled }) end -- Start with virtual lines disabled M.toggle_lsp_lines() vim.diagnostic.config({ severity_sort = true, virtual_text = true, }) vim.keymap.set('n', '<leader>lq', M.toggle_lsp_lines, { desc = '[L]SP [Q]uickfix Toggle' }) M.on_attach = function(_, bufnr) -- NOTE: Remember that lua is a real programming language, and as such it is possible -- to define small helper and utility functions so you don't have to repeat yourself -- many times. -- -- In this case, we create a function that lets us more easily define mappings specific -- for LSP related items. It sets the mode, buffer and description for us each time. local nmap = function(keys, func, desc) if desc then desc = 'LSP: ' .. desc end vim.keymap.set('n', keys, func, { buffer = bufnr, desc = desc }) end local vmap = function(keys, func, desc) if desc then desc = 'LSP: ' .. desc end vim.keymap.set('v', keys, func, { buffer = bufnr, desc = desc }) end nmap('<leader>rn', vim.lsp.buf.rename, '[R]e[n]ame') nmap("<leader>ca", require("actions-preview").code_actions, '[C]ode [A]ction') vmap("<leader>ca", require("actions-preview").code_actions, '[C]ode [A]ction') nmap('gd', require('telescope.builtin').lsp_definitions, '[G]oto [D]efinition') nmap('gr', require('telescope.builtin').lsp_references, '[G]oto [R]eferences') nmap('gI', require('telescope.builtin').lsp_implementations, '[G]oto [I]mplementation') nmap('<leader>D', require('telescope.builtin').lsp_type_definitions, 'Type [D]efinition') nmap('<leader>ds', require('telescope.builtin').lsp_document_symbols, '[D]ocument [S]ymbols') nmap('<leader>ws', require('telescope.builtin').lsp_dynamic_workspace_symbols, '[W]orkspace [S]ymbols') -- See `:help K` for why this keymap nmap('K', vim.lsp.buf.hover, 'Hover Documentation') nmap('<A-k>', vim.lsp.buf.signature_help, 'Signature Documentation') -- Lesser used LSP functionality nmap('gD', vim.lsp.buf.declaration, '[G]oto [D]eclaration') nmap('<leader>wa', vim.lsp.buf.add_workspace_folder, '[W]orkspace [A]dd Folder') nmap('<leader>wr', vim.lsp.buf.remove_workspace_folder, '[W]orkspace [R]emove Folder') nmap('<leader>wl', function() print(vim.inspect(vim.lsp.buf.list_workspace_folders())) end, '[W]orkspace [L]ist Folders') -- Create a command `:Format` local to the LSP buffer vim.api.nvim_buf_create_user_command(bufnr, 'Format', function(_) vim.lsp.buf.format() end, { desc = 'Format current buffer with LSP' }) end -- nvim-cmp supports additional completion capabilities, so broadcast that to servers local capabilities = vim.lsp.protocol.make_client_capabilities() capabilities = require('cmp_nvim_lsp').default_capabilities(capabilities) M.capabilities = capabilities -- Ensure the servers above are installed local mason_lspconfig = require 'mason-lspconfig' mason_lspconfig.setup { ensure_installed = vim.tbl_keys(M.servers), } -- nicer lsp diagnostics icons local signs = { Error = "", Warn = "", Hint = "󰌵", Info = "" } for type, icon in pairs(signs) do local hl = "DiagnosticSign" .. type vim.fn.sign_define(hl, { text = icon, texthl = hl, numhl = hl }) end mason_lspconfig.setup_handlers { function(server_name) require('lspconfig')[server_name].setup { capabilities = capabilities, on_attach = M.on_attach, settings = M.servers[server_name], filetypes = (M.servers[server_name] or {}).filetypes, } end, } return M
#include <stdio.h> #include <stdlib.h> // RecordType struct RecordType { int id; char name; int order; }; // Node for separate chaining struct Node { struct RecordType data; struct Node* next; }; // HashType struct HashType { struct Node* head; }; // Compute the hash function int hash(int x) { return abs(x) %15; } // parses input file to an integer array int parseData(char* inputFileName, struct RecordType** ppData) { FILE* inFile = fopen(inputFileName, "r"); int dataSz = 0; int i, n; char c; struct RecordType *pRecord; *ppData = NULL; if (inFile) { fscanf(inFile, "%d\n", &dataSz); *ppData = (struct RecordType*) malloc(sizeof(struct RecordType) * dataSz); if (*ppData == NULL) { printf("Cannot allocate memory\n"); exit(-1); } for (i = 0; i < dataSz; ++i) { pRecord = *ppData + i; fscanf(inFile, "%d ", &n); pRecord->id = n; fscanf(inFile, "%c ", &c); pRecord->name = c; fscanf(inFile, "%d ", &n); pRecord->order = n; } fclose(inFile); } return dataSz; } // prints the records void printRecords(struct RecordType pData[], int dataSz) { int i; printf("\nRecords:\n"); for (i = 0; i < dataSz; ++i) { printf("\t%d %c %d\n", pData[i].id, pData[i].name, pData[i].order); } printf("\n\n"); } // display records in the hash structure // skip the indices which are free // the output will be in the format: // index x -> id, name, order -> id, name, order .... void displayRecordsInHash(struct HashType *pHashArray, int hashSz) { int i; for (i = 0; i < hashSz; ++i) { struct Node* current = pHashArray[i].head; if (current != NULL) { printf("index %d -> ", i); while (current != NULL) { printf("%d, %c, %d -> ", current->data.id, current->data.name, current->data.order); current = current->next; } printf("NULL\n"); } } } int main(void) { struct RecordType *pRecords; int recordSz = 0; recordSz = parseData("input.txt", &pRecords); printRecords(pRecords, recordSz); // Your hash implementation struct HashType pHashArray[15]; // Initialize the hash table for (int i = 0; i < 15; i++) { pHashArray[i].head = NULL; } // Insert records into the hash table for (int i = 0; i < recordSz; i++) { int hashValue = hash(pRecords[i].id); struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); if (newNode == NULL) { printf("Cannot allocate memory\n"); exit(-1); } newNode->data = pRecords[i]; newNode->next = pHashArray[hashValue].head; pHashArray[hashValue].head = newNode; } // Display records in the hash table displayRecordsInHash(pHashArray, 15); // Free memory free(pRecords); for (int i = 0; i < 15; i++) { struct Node* current = pHashArray[i].head; while (current != NULL) { struct Node* next = current->next; free(current); current = next; } } return 0; }
" autoload/utils/fs.vim - contains function to work with the file system " Maintainer: Ilya Churaev <https://github.com/ilyachur> " Create directory function! utils#fs#makeDir(dir) abort let l:directory = finddir(a:dir, getcwd().';.') if l:directory ==# '' silent call mkdir(a:dir, 'p') let l:directory = finddir(a:dir, getcwd().';.') endif if l:directory !=# '' return fnamemodify(l:directory, ':p:h') endif call utils#common#Warning('Cannot create a build directory: '.a:dir) endfunction " Remove directory function! utils#fs#removeDirectory(file) abort if has('win32') silent call system('rd /S /Q ' . utils#fs#fnameescape(a:file)) else silent call system('rm -rf ' . utils#fs#fnameescape(a:file)) endif endfunction " Remove file function! utils#fs#removeFile(file) abort if has('win32') silent call system('del /F /Q ' . utils#fs#fnameescape(a:file)) else silent call system('rm -rf ' . utils#fs#fnameescape(a:file)) endif endfunction " Create a link function! utils#fs#createLink(src, dst) abort " Need to wait for end of Dispatch Make " if !filereadable(a:src) " return " endif silent call utils#fs#removeFile(a:dst) if has('win32') silent call system('copy ' . utils#fs#fnameescape(a:src) . ' ' . utils#fs#fnameescape(a:dst)) else silent call system('ln -s ' . utils#fs#fnameescape(a:src) . ' ' . utils#fs#fnameescape(a:dst)) endif endfunction " Extends default fnameescape, adds double quotes for Windows function! utils#fs#fnameescape(file) abort if has('win32') let l:path = substitute(a:file, '\/', '\\', 'g') if l:path !=# '' let l:path = '"' . l:path . '"' endif return l:path else return fnameescape(a:file) endif endfunction
package com.test.sber.models; import jakarta.persistence.*; import lombok.*; import lombok.experimental.FieldDefaults; import java.util.ArrayList; import java.util.List; /** * Класс, представляющий сущность "Компания" в базе данных. * Содержит информацию о компании, включая название компании и список сотрудников. */ @FieldDefaults(level = AccessLevel.PRIVATE) @Entity @Getter @Setter @ToString @Table(name = "company") public class Company { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Long id; @Column(name = "company_name") String companyName; @Column(name = "employee_in_company") @OneToMany( mappedBy = "company", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true ) List<Employee> employeeInCompany = new ArrayList<>(); /** * Метод для добавления сотрудника в компанию. * @param employee Сотрудник для добавления. */ public void addEmployee(Employee employee) { employeeInCompany.add(employee); employee.setCompany(this); } /** * Метод для удаления сотрудника из компании. * @param employee Сотрудник для удаления. */ public void removeEmployee(Employee employee) { employeeInCompany.remove(employee); employee.setCompany(null); } }
package Assignment_1; import java.util.*; public class Main{ Scanner sc = new Scanner(System.in); PlacementCell placementcell = new PlacementCell(); ArrayList<Company> companies = new ArrayList<Company>(); ArrayList<Student> students = new ArrayList<Student>(); public static void main(String[] args){ Main menu = new Main(); menu.preMenu(); } void preMenu(){ ArrayList<String> menuargs = new ArrayList<String>(); menuargs.add("Welcome to FutureBuilder"); menuargs.add("Enter the Application"); menuargs.add("Exit the Application"); int choice = this.makeMenu(menuargs); if(choice == 1){ this.mainMenu(); }else{ sc.close(); return; } this.preMenu(); } void mainMenu(){ ArrayList<String> menuargs = new ArrayList<String>(); menuargs.add("Choose the mode to enter in:-"); menuargs.add("Enter as Student mode"); menuargs.add("Enter as Company mode"); menuargs.add("Enter as Placement Cell mode"); menuargs.add("Return to Main Application"); int choice = this.makeMenu(menuargs); switch(choice){ case 1: this.studentPreMenu(); break; case 2: this.companyPreMenu(); break; case 3: this.placementCellMenu(); break; case 4: return; } this.mainMenu(); } void placementCellMenu(){ ArrayList<String> menuargs = new ArrayList<String>(); menuargs.add("Welcome to IIITD Placement Cell"); menuargs.add("Open Student Registrations"); menuargs.add("Open Company Registrations"); menuargs.add("Get Number of Student Registrations"); menuargs.add("Get Number of Company Registrations"); menuargs.add("Get Number of Offered/Unoffered/Blocked Students"); menuargs.add("Get Student Details"); menuargs.add("Get Company Details"); menuargs.add("Get Average Package"); menuargs.add("Get Company Process Results"); menuargs.add("Back"); int choice = this.makeMenu(menuargs); switch(choice){ case 1: placementcell.openStudentReg(sc); break; case 2: placementcell.openCompReg(sc); break; case 3: placementcell.getNumStudents(); break; case 4: placementcell.getNumComp(); break; case 5: placementcell.getStudentStatus(); break; case 6: placementcell.getStudentDetails(sc); break; case 7: placementcell.getCompDetails(sc); break; case 8: placementcell.getAvg(); break; case 9: placementcell.getCompProcessResults(sc); break; case 10: return; } this.placementCellMenu(); } void companyPreMenu(){ ArrayList<String> menuargs = new ArrayList<String>(); menuargs.add("Choose the Company Query to perform-"); menuargs.add("Add Company and Details"); menuargs.add("Choose Company"); menuargs.add("Get Available Companies"); menuargs.add("Back"); int choice = this.makeMenu(menuargs); switch(choice){ case 1: this.addCompany(); break; case 2: this.chooseCompany(); break; case 3: this.getComps(); break; case 4: return; } this.companyPreMenu(); } void addCompany(){ Company company = new Company(); company.constructor(sc); companies.add(company); } void chooseCompany(){ ArrayList<String> menuargs = new ArrayList<String>(); menuargs.add("Choose To enter into mode of Available Companies:-"); for(int i = 0; i < companies.size(); i++){ menuargs.add(companies.get(i).name); } int choice = this.makeMenu(menuargs) - 1; this.companyMenu(companies.get(choice)); } void companyMenu(Company company){ ArrayList<String> menuargs = new ArrayList<String>(); menuargs.add("Welcome " + company.name); menuargs.add("Update Role"); menuargs.add("Update Package"); menuargs.add("Update CGPA criteria"); menuargs.add("Register To Institute Drive"); menuargs.add("Back"); int choice = this.makeMenu(menuargs); switch(choice){ case 1: company.updateRole(sc); break; case 2: company.updateCTC(sc); break; case 3: company.updateCGPA(sc); break; case 4: placementcell.registerCompany(company, sc); break; case 5: return; } this.companyMenu(company); } void getComps(){ if(this.companies.size() == 0){ System.out.println("No Companies Available"); return; } for(int i = 0; i < this.companies.size(); i++){ System.out.printf("%d) %s\n", i + 1, companies.get(i).name); } return; } void studentPreMenu(){ ArrayList<String> menuargs = new ArrayList<String>(); menuargs.add("Choose the Student Query to perform-"); menuargs.add("Enter as a Student(Give Student Name, and Roll No.)"); menuargs.add("Add students"); menuargs.add("Get Available Students"); menuargs.add("Back"); int choice = this.makeMenu(menuargs); switch(choice){ case 1: this.chooseStudent(); break; case 2: this.addStudent(); break; case 3: this.getStudents(); break; case 4: return; } this.studentPreMenu(); } void addStudent(){ Student student = new Student(); student.constructor(sc); this.students.add(student); System.out.println("Student has been added"); } void chooseStudent(){ if(students.size() == 0){ System.out.println("No student has registered yet"); return; } System.out.print("Enter the Name: "); String name = sc.nextLine(); System.out.print("Enter the Roll no.: "); int roll = sc.nextInt(); sc.nextLine(); System.out.println(); for(int i = 0; i < students.size(); i++){ if((name.equals(students.get(i).name))&& (students.get(i).roll == roll)){ studentMenu(students.get(i)); return; } } System.out.println("No such student found"); return; } void studentMenu(Student student){ ArrayList<String> menuargs = new ArrayList<String>(); menuargs.add("Welcome " + student.name); menuargs.add("Register For Placement Drive"); menuargs.add("Register For Company"); menuargs.add("Get All available companies"); menuargs.add("Get Current Status"); menuargs.add("Update CGPA"); menuargs.add("Accept offer"); menuargs.add("Reject offer"); menuargs.add("Back"); int choice = this.makeMenu(menuargs); switch(choice){ case 1: placementcell.registerStudent(student, sc); break; case 2: placementcell.apply(student, sc); break; case 3: placementcell.getAvailableComp(student); break; case 4: student.getCurrStatus(); break; case 5: placementcell.updateStudentCGPA(student, sc); break; case 6: student.acceptOffer(); break; case 7: student.rejectOffer(); break; case 8: return; } this.studentMenu(student); } void getStudents(){ if(this.students.size() == 0){ System.out.println("No Students Available"); return; } for(int i = 0; i < this.students.size(); i++){ System.out.printf("%d) %s\n", i + 1, students.get(i).name); } return; } int makeMenu(ArrayList<String> menu){ int option = 0; System.out.println(); System.out.println(menu.get(0)); for(int i = 1; i < menu.size(); i++){ System.out.printf("%d) %s\n", i, menu.get(i)); } System.out.print("Choose an option: "); option = sc.nextInt(); sc.nextLine(); System.out.println(); return option; } }
import spellCheckHandler from "./spellCheckHandler"; import {ServerRoute} from "@hapi/hapi"; import Joi from "joi"; const SpellCheckRequestSchema = Joi.object({ lang: Joi.string().min(2).required(), text: Joi.string().required(), }).label('SpellCheckRequest'); const SpellCheckResultSchema = Joi.object({ text: Joi.string().required(), offset: Joi.number().required(), index: Joi.number().required(), suggestions: Joi.array().items(Joi.string()), }).label('SpellCheckResult'); const SpellCheckResponseSchema = Joi.array().items(SpellCheckResultSchema); const handlers : ServerRoute[] = [ { method: 'POST', path: '/spell-check', options: { tags: ['api', 'spell-check'], description: 'spell check returns errors as array', auth: false, handler: spellCheckHandler, validate: { payload: SpellCheckRequestSchema, }, response: { schema: SpellCheckResponseSchema, }, }, }, ]; export default handlers;
/** \file Journal.h * \brief Ce fichier contient toute les declarations comprise dans la Classe Journal * \author M4ST3R-Y0DA-44 * * \date Created on 18 novembre 2021, 15:00 */ #ifndef JOURNAL_H #define JOURNAL_H #include <string> #include "Reference.h" /**\namespace biblio * \brief Un namespace qui contient la classe Reference, Ouvrage, Journal et Bibliographie ainsi que toute leur attributs et methodes*/ namespace biblio { /** \class Journal * \brief Classe qui creer et manipule les objet de type Journal. Cette classe derive de la classe Reference. */ class Journal : public Reference { public: /** \fn Journal (const std::string& p_nom, const int p_volume, const int p_numero, const int p_page, const std::string& p_auteur, const std::string& p_titre, const int p_annee, const std::string& p_identifiant) * \brief Constructeur de la classe Journal. * \param p_nom (string) le nom du journal de publication * \param p_volume (int) le volume de la publication * \param p_numero (int) Le numero de la publication * \param p_page (int) la page de publication * \param p_auteur (string) nom de l'auteur * \param p_titre (string) le titre de la publication * \param p_annee (int) l'annee de publication * \param p_identifiant (string) represente un string du code ISSN de la Reference*/ Journal (const std::string& p_nom, const int p_volume, const int p_numero, const int p_page, const std::string& p_auteur, const std::string& p_titre, const int p_annee, const std::string& p_identifiant); /** \fn const std::string reqNom() const * \brief methode de lecture de l'attribut m_nom * \return (string) contenant une copie de l'attribut m_nom*/ const std::string reqNom () const; /** \fn const int reqVolume() const * \brief methode de lecture de l'attribut m_volume * \return (int) le numero de volume du Journal*/ const int reqVolume () const; /** \fn const int reqNumero() const * \brief methode de lecture de l'attribut m_numero * \return (int) le numero de la publication*/ const int reqNumero () const; /** \fn const int reqPage() const * \brief methode de lecture de l'attribut m_page * \return (int) le numero de page de debut de la publication dans le Journal*/ const int reqPage () const; /** \fn const std::string reqReferenceFormate() const * \brief methode pour obtenir un string formate de la Reference complete du Journal * \return (string) retourne la Reference du Journal dans un format formate*/ const std::string reqReferenceFormate () const; /** \fn virtual Reference* clone() const * \brief fonction qui permet de faire une copie allouee sur le monceau de l'objet courant*/ virtual Reference* clone () const; private: /** \fn void verifieInvariant() const * \brief fonction qui verifie les invariants de la classe Journal*/ void verifieInvariant () const; std::string m_nom; /*\brief (string) nom du journal de publication*/ int m_volume; /*\brief (int) volume du journal*/ int m_numero; /*\brief (int) numero du Journal*/ int m_page; /*\brief (int) numero de debut de l'article dans le journal*/ }; } #endif /* JOURNAL_H */
module CES { /** * The entity is the container of components. * @class */ export class Entity { private static _id: number = 0; public id: number; private components: { [key: string]: Component; }; public onComponentAdded: CES.Signal; public onComponentRemoved: CES.Signal; constructor() { /** * @public * @readonly */ this.id = Entity._id++; /** * Map from component names to components. * @private * @property */ this.components = {}; /** * @public * @readonly */ this.onComponentAdded = new CES.Signal(); /** * @public * @readonly */ this.onComponentRemoved = new CES.Signal(); } /** * Check if this entity has a component by name. * @public * @param {String} componentName * @return {Boolean} */ hasComponent(componentName: string): boolean { return this.components['$' + componentName] !== undefined; } /** * Get a component of this entity by name. * @public * @param {String} componentName * @return {Component} */ getComponent(componentName: string): Component { return this.components['$' + componentName]; } /** * Add a component to this entity. * @public * @param {Component} component */ addComponent(component: CES.Component) { this.components['$' + component.name] = component; this.onComponentAdded.emit(this, component.name); } /** * Remove a component from this entity by name. * @public * @param {String} componentName */ removeComponent(componentName: string) { var removedComponent: CES.Component = this.components['$' + componentName]; this.components['$' + componentName] = undefined; this.onComponentRemoved.emit(this, componentName, removedComponent); } } }
import { ReactNode, createContext, useContext, useState } from 'react'; export interface messagesUserProps { message: string, user: string, time: string } interface ContextMessageProps { message: messagesUserProps[]; setMessage: (message: string[]) => void; }; type ContextMessageType = { data: ContextMessageProps; }; export const ContextMessage = createContext<ContextMessageType>({ data: { message: [{ message: "", user: "", time: "" }], setMessage: (message: string[]) => message, }, }); export const ContextMessageProvider = ({ children }: { children: ReactNode }) => { const [message, setMessage] = useState<any>([]); return ( <ContextMessage.Provider value={{ data: { message, setMessage } }}> {children} </ContextMessage.Provider> ); }; export const useContextMessage = () => useContext(ContextMessage)
import Foundation public class Stack { public var description: String { items.description } public var isEmpty: Bool { items.isEmpty } public var last: String { items.last! } public var size: Int { items.count } private var items = [String]() public init(_ items: [String] = []) { self.items = items } public func push(_ item: String) { items.append(item) } public func push(_ moreItems: [String]) { items.append(contentsOf: moreItems) } public func pop() -> String { items.removeLast() } public func pop(_ k: Int) -> [String] { let result = items.suffix(k) items.removeLast(k) return Array(result) } }
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'; import { MongooseModule } from '@nestjs/mongoose'; import { PasswordStrengthMiddleware } from '../../middleware/password-strength.middleware'; import { UsersController } from './users.controller'; import { UserSchema } from './users.model'; import { UsersService } from './users.service'; @Module({ imports: [MongooseModule.forFeature([{ name: 'user', schema: UserSchema }])], controllers: [UsersController], providers: [UsersService], exports: [UsersService], }) export class UsersModule implements NestModule { configure(consumer: MiddlewareConsumer) { consumer .apply(PasswordStrengthMiddleware) .forRoutes('register', 'user/change-password'); } }
--- copyright: years: 2015, 2017 lastupdated: "2017-08-11" --- {:shortdesc: .shortdesc} {:new_window: target="_blank"} {:tip: .tip} {:pre: .pre} {:codeblock: .codeblock} {:screen: .screen} {:javascript: .ph data-hd-programlang='javascript'} {:java: .ph data-hd-programlang='java'} {:python: .ph data-hd-programlang='python'} {:swift: .ph data-hd-programlang='swift'} # getUserInput {: #getUserInput} The `<getUserInput>` node prompts the user for input. Processing stops until input is submitted. {: shortdesc} ## Example ```xml <getUserInput> <input> <grammar> <item>auto</item> </grammar> </input> <input> <grammar> <item>life</item> </grammar> </input> </getUserInput> ``` {: codeblock} ## Contained by [default](/docs/services/dialog/default.html) | [folder](/docs/services/dialog/folder.html) | [function](/docs/services/dialog/function.html) | getUserInput | [goto](/docs/services/dialog/goto.html) | [if](/docs/services/dialog/if.html) | [input](/docs/services/dialog/input.html) | [output](/docs/services/dialog/output.html) | [random](/docs/services/dialog/random.html) | [search](/docs/services/dialog/search.html) ## Contains [action](/docs/services/dialog/action.html) | [default](/docs/services/dialog/default.html) | [folder](/docs/services/dialog/folder.html) |[function](/docs/services/dialog/function.html) | getUserInput | [goto](/docs/services/dialog/goto.html) |[if](/docs/services/dialog/if.html) | [input](/docs/services/dialog/input.html) | [output](/docs/services/dialog/output.html) | [random](/docs/services/dialog/random.html) | [search](/docs/services/dialog/search.html) ## Attributes <table> <caption>Table 1. Attributes</caption> <thead><tr><th>Name</th> <th>Description</th> </tr> </thead> <tbody><tr><td><p> comment </p></td> <td><p> Specifies comment about the node. </p></td> </tr> <tr><td><p> date </p></td> <td><p> Specifies the date when the node was created. </p></td> </tr> <tr><td><p> gid </p></td> <td><p> Specifies the numeric ID for an object that is used to store data in the database. Internally, GIDs link together dialog nodes and link conversation history with dialog nodes. If you specify GIDs, ensure that the values throughout the dialog document are unique. Otherwise, the dialog document cannot be imported into the system. The scope of the GID is the dialog ID. </p></td> </tr> <tr><td><p> id </p></td> <td><p> Specifies a unique ID that is used as an anchor point, especially for GoTo nodes and Search nodes. </p></td> </tr> <tr><td><p> isDNRCandidate </p></td> <td><p> Specifies whether the system returns to this node after the end of a dialog in the folder tree is reached. Valid values are true and false. </p></td> </tr> <tr><td><p> isOffline </p></td> <td><p> Specifies whether the node is processed or ignored by the system. Valid values are true and false. </p></td> </tr> </tbody> </table>
# Traffic Information 🚦 ## 🎉 Introduction Using a pre-installed camera system, this traffic information project in Binh Dinh helps businesses and governments manage the security and traffic situations in the area. ## ✨ Features - User registration, login, and logout with Auth0 - User authentication: + Decentralize and safeguard `route` in accordance with permitted permissions. + Redirects to `/unauthorized` if authorization is not granted, according to the check. + A notification informing the user that their account has been locked will be displayed if the user is locked. - Map: a general overview of traffic cameras, traffic alerts, road event, parking lots, traffic separation, and static data. - Manage: + `Traffic alerts:` create alerts, show new alerts + `Traffic cameras:` a list of cameras organized by location cameras and camera groups can be added, removed, or edited using the `admin` or `superadmin` rights, CSV, Excel, and JSON data can be exported with the `admin` or `superadmin` permissions. + `Road event:` display a list of active construction projects, add, remove, or update construction data with `admin` or `superadmin` permissions, and export data to csv, excel, or json with the same rights + `Parking:` display a list of parking lots, add, remove, or update parking information with `admin` or `superadmin` rights, and export data in csv, excel, or json with the same permissions. + `Traffic event:` display the traffic flow list, add, remove, or change the traffic flow data with the `admin` or `superadmin` permissions, and export the data to csv, excel, or json with those permissions. + `Static information:` Under `admin` or `superadmin` permission, you can add, remove, or change class data static information. You can also export data in the following formats: csv, excel, and json. - Administration: + ` Settings:` Under `admin` or `superadmin` permissions, configure camera status, traffic conditions, and traffic events. + ` Users:` display the system's user list, account statistics, and editable user permissions for `guest`,`user`, and `manager`. User `lock` and `unlock` + ` Groups:` display user group list, create user groups, and configure permissions to allow: `access`, `permission`, `editing`, `management` of system resources. - Statistic: + `Warning statistics:` show a graph of alerts broken down by `day`, `weekly` and `monthly`. ## 💻 Using technologies - [Angular](https://angular.io/) - [NodeJS](https://nodejs.org/en/) - [MongoDB](https://www.mongodb.com/) - [Auth0](https://auth0.com/) - another technologies. ## 👤 Client side Project made using [Angular CLI](https://github.com/angular/angular-cli) v13.2.5. You must use the `npm install` command to install the modules before using the `npm start` command to launch the user-side project. ### ⚙️ Auth0 Settings - The Auth0 module can be installed with the command.: `npm install @auth0/auth0-angular` - Open file `app.module.ts` then set up as follows: ``` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AuthModule } from '@auth0/auth0-angular'; import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], imports: [ BrowserModule, AuthModule.forRoot({ domain: 'YOUR_DOMAIN', clientId: 'YOUR_CLIENT_ID' }), ], bootstrap: [AppComponent], }) export class AppModule {} ``` - The following steps must be taken in order to configure Auth0 user permissions.: + Access to Auth0: Choose Auth Pipeline ==> Rule ==> Create ==> Empty Rule ==> Create Name and paste the following code into the Script: ``` function (user, context, callback) { user.app_metadata = user.app_metadata || {}; // You can add a Role based on what you want // In this case I check domain var addRolesToUser = function(user, cb) { if (user.app_metadata.roles) { return cb(null, user.app_metadata.roles); } else { return cb(null, ['guest']); } }; addRolesToUser(user, function(err, roles) { if (err) { callback(err); } else { user.app_metadata.roles = roles; auth0.users.updateAppMetadata(user.user_id, user.app_metadata) .then(function(){ context.idToken.roles = user.app_metadata.roles; user.roles = roles; callback(null, user, context); }) .catch(function(err){ callback(err); }); } }); } ``` Then click Save change. - The same procedures as described above for configuring user permissions using the Auth Pipeline are used to setup Auth0 to return `appmetadata` in the `access token`: + paste the following code into the Script: ``` function (user, context, callback) { const namespace = 'https://hoang0650.com'; const assignedRoles = (context.authorization || {}).roles; let idTokenClaims = context.idToken || {}; let accessTokenClaims = context.accessToken || {}; idTokenClaims[`${namespace}/roles`] = assignedRoles; accessTokenClaims[`${namespace}/roles`] = assignedRoles; context.idToken = idTokenClaims; context.accessToken = accessTokenClaims; if (context.idToken && user.user_metadata) { context.idToken[namespace + '/user_metadata'] = user.user_metadata; } if (context.idToken && user.app_metadata) { context.idToken[namespace + '/app_metadata'] = user.app_metadata; } return callback(null, user, context); } ``` Then click Save change. - Setting up Auth0 such that it returns name and appmetadata in the `access token` + paste the following code into the Script: ``` function (user, context, callback) { var namespace = "https://hoang0650.com"; user.app_metadata = user.app_metadata || {}; user.permissions = user.permissions || {}; //var appmeta = (context.authorization || {}).app_metadata; user.name = user.name || {}; context.accessToken[`${namespace}/app_metadata`] = user.app_metadata; context.accessToken[`${namespace}/name`] = user.name; context.accessToken[`${namespace}/permission`] = user.permissions; callback(null, user, context); } ``` Then click Save change. ## 🖥 Server side - Project made using [NodeJS](https://nodejs.org/en/) v14.15.4. - You must use the `npm install` command to install the modules before using the `npm start` command to launch the server-side project. ## ✅ Testing - For `guest` account: `email` guest@gmail.com `password` Guest123@ - For `user` account: `email` user@gmail.com `password` User123@ - For `admin` account: `email` admin@gmail.com `password` Admin123@ - For `superadmin` account: `email` superadmin@gmail.com `password` Superadmin123@
/* eslint-disable @typescript-eslint/no-unused-vars */ import { AppHealthDeleteDatabaseByIdController, AppHealthDeleteDatabaseByIdHandler } from '@api/app-health/database'; import { appHealthMockDatabaseData } from '@app/app-health/database'; import { Test, TestingModule } from '@nestjs/testing'; describe('AppHealthDeleteDatabaseByIdController', () => { let controller: AppHealthDeleteDatabaseByIdController; let handler: AppHealthDeleteDatabaseByIdHandler; beforeAll(async () => { const module: TestingModule = await Test.createTestingModule({ imports: [ ], controllers: [ AppHealthDeleteDatabaseByIdController, ], providers: [ { provide : AppHealthDeleteDatabaseByIdHandler, useValue: { main: () => { /**/ }, }, }, ], }) .compile(); controller = module.get<AppHealthDeleteDatabaseByIdController>(AppHealthDeleteDatabaseByIdController); handler = module.get<AppHealthDeleteDatabaseByIdHandler>(AppHealthDeleteDatabaseByIdHandler); }); describe('main', () => { test('AppHealthDeleteDatabaseByIdController should be defined', () => { expect(controller).toBeDefined(); }); test('should return an database deleted', async () => { jest.spyOn(handler, 'main').mockImplementation(() => new Promise(resolve => resolve(appHealthMockDatabaseData[0]))); expect(await controller.main(appHealthMockDatabaseData[0].id)).toBe(appHealthMockDatabaseData[0]); }); }); });
#include "APProfileEditView.h" #include "MJHelper.h" #include "api/APUpdateProfileAPI.h" #include "api/APDeleteProfileAPI.h" #include "StoryAlert.h" #include "StoryLanguageManager.h" #include "APDatabase.h" #include "MMFirebaseDatabase.h" USING_NS_CC; std::once_flag ap_profile_edit_view_flag_reader_once; INITIALIZE_READER(APProfileEditView); APProfileEditView * APProfileEditView::createView(const ap::Profile & profile) { std::call_once(ap_profile_edit_view_flag_reader_once, [] { REGISTER_CSB_READER(APProfileEditView); }); auto view = reinterpret_cast<APProfileEditView*>(CSLoader::createNodeWithVisibleSize("account/ProfileEdit.csb")); if (view) { view->didLoadFromCSB(profile); return view; } CC_SAFE_DELETE(view); return nullptr; } void APProfileEditView::didLoadFromCSB(const ap::Profile & profile) { _profile = profile; auto textfield = utils::findChild<ui::TextField *>(this, "textfield"); textfield->setCursorEnabled(true); textfield->setCursorChar('|'); textfield->setTextHorizontalAlignment(TextHAlignment::CENTER); textfield->setTextVerticalAlignment(TextVAlignment::CENTER); textfield->setMaxLengthEnabled(true); textfield->setMaxLength(10); textfield->setPlaceHolderColor(Color4B(0, 0, 0, 0x44)); textfield->setString(profile.name); onLoadListAvatar(); if (profile.gender == ap::Profile::MALE) { onSelectBoy(this); } else { onSelectGirl(this); } auto layout_age = utils::findChild(this, "layout_age"); onSelectAge(layout_age->getChildByTag(profile.age)); } void APProfileEditView::onEnter() { ui::Layout::onEnter(); changeDisplayLanguage(); this->schedule(schedule_selector(APProfileEditView::updateFX)); } void APProfileEditView::onExit() { ui::Layout::onExit(); } void APProfileEditView::changeDisplayLanguage(){ utils::findChild<Text*>(this, "Text_1")->setString(LANGUAGE_MANAGER->getDisplayTextByKey("key.parent.profile.edit.title")); utils::findChild<Text*>(this, "Text_16")->setString(LANGUAGE_MANAGER->getDisplayTextByKey("key.parent.profile.name")); utils::findChild<Text*>(this, "gender_label")->setString(LANGUAGE_MANAGER->getDisplayTextByKey("key.parent.profile.gender")); utils::findChild<ui::TextField *>(this, "textfield")->setString(LANGUAGE_MANAGER->getDisplayTextByKey("key.account.profile.name.text")); } void APProfileEditView::onLoadListAvatar() { // auto list_avatar = FileUtils::getInstance()->listFiles("mjstory/avatar"); // list_avatar.erase(std::remove_if(list_avatar.begin(), list_avatar.end(), [](const std::string & p) { // if (p.length() <= 4) // return true; // const std::string ext = ".png"; // return p.compare(p.length() - 4, 4, ext) != 0; // }), list_avatar.end()); std::vector<std::string> list_avatar = { "boy_1.png", "boy_2.png", "boy_3.png", "boy_4.png", "boy_5.png", "boy_6.png", "boy_7.png", "boy_8.png", "girl_1.png", "girl_2.png", "girl_3.png", "girl_4.png", "girl_5.png", "girl_6.png", "girl_7.png", "girl_8.png" }; mj::helper::shuffle(list_avatar); _listview = utils::findChild<ui::ListView*>(this, "listview"); _listview->setMagneticType(ui::ListView::MagneticType::CENTER); _listview->setScrollBarEnabled(false); for (const auto & p : list_avatar) { auto wrapper = ui::Layout::create(); wrapper->setContentSize(Size(200, 200)); wrapper->setBackGroundColorType(ui::Layout::BackGroundColorType::NONE); wrapper->setBackGroundColor(Color3B(random(0, 0xff), random(0, 0xff), random(0, 0xff))); wrapper->setName(p); auto ava = ui::ImageView::create(p); ava->setContentSize(Size(200, 200)); ava->setAnchorPoint(Point::ANCHOR_MIDDLE); ava->setPosition(Point(100, 100)); ava->setName("avatar"); wrapper->addChild(ava); ava->ignoreContentAdaptWithSize(false); _listview->pushBackCustomItem(wrapper); } //TODO: Scrool to item avatar's profile int index = list_avatar.size()/2; for (int i = 0; i < list_avatar.size(); ++i) { if (_profile.avatar.find(list_avatar[i]) != std::string::npos) { index = i; break; } } _listview->forceDoLayout(); _listview->jumpToLeft(); _listview->scrollToItem(index, Vec2::ANCHOR_MIDDLE, Vec2::ANCHOR_MIDDLE,1.0f); } void APProfileEditView::updateFX(float dt) { auto items = _listview->getItems(); const auto middle_point = _listview->getWorldPosition(); const auto radius = 350.f; for (auto i : items) { auto position = i->getPosition() + i->getContentSize() / 2; position = i->getParent()->convertToWorldSpace(position); position = position - middle_point; auto ratio = 0.f; if (fabs(position.x) < radius) { ratio = sqrt(radius * radius - position.x * position.x); ratio = ratio / radius; } i->getChildByName("avatar")->setScale(ratio); i->getChildByName("avatar")->setOpacity(ratio * 0xff); } } void APProfileEditView::onSelectBoy(cocos2d::Ref * sender) { auto boy = utils::findChild<ui::ImageView*>(this, "icon_boy"); auto girl = utils::findChild<ui::ImageView*>(this, "icon_girl"); mj::helper::grayscaleImageV2(boy, false); boy->setTag(1); mj::helper::grayscaleImageV2(girl, true); girl->setTag(0); } void APProfileEditView::onSelectGirl(cocos2d::Ref * sender) { auto boy = utils::findChild<ui::ImageView*>(this, "icon_boy"); auto girl = utils::findChild<ui::ImageView*>(this, "icon_girl"); mj::helper::grayscaleImageV2(boy, true); boy->setTag(0); mj::helper::grayscaleImageV2(girl, false); girl->setTag(2); } void APProfileEditView::onSelectAge(cocos2d::Ref * sender) { auto layout_age = utils::findChild(this, "layout_age"); auto old_choose = layout_age->getChildByTag<ui::Button* > (_age); if (old_choose) { old_choose->setColor(Color3B::WHITE); } auto btn_age = reinterpret_cast<ui::Button*>(sender); _age = btn_age->getTag(); btn_age->setColor(cocos2d::Color3B(0, 242, 0)); } void APProfileEditView::onSave(cocos2d::Ref * sender) { bool is_vn = LANGUAGE_MANAGER->getDisplayLangId() == 4; auto boy = utils::findChild<ui::ImageView*>(this, "icon_boy"); auto girl = utils::findChild<ui::ImageView*>(this, "icon_girl"); auto gender = boy->getTag() | girl->getTag(); auto name = utils::findChild<ui::TextField*>(this, "textfield")->getString(); // get current avatar _listview->stopOverallScroll(); auto current_avatar = _listview->getCenterItemInCurrentView(); auto avatar = current_avatar->getName(); bool is_valid_name = !name.empty() && ap::Database::getInstance().checkDuplicateName(name); if (!is_valid_name) { if (name.empty()) { StoryAlert::showAlert(is_vn ? "Vui lòng nhập tên của bé." : "Please enter your child's name", "OK", is_vn ? "Đóng" : "Close"); } else { StoryAlert::showAlert(is_vn ? "Tên hồ sơ đã được tạo." : "Profile name has been created", "OK", is_vn ? "Đóng" : "Close"); } return; } if (gender == 0) { StoryAlert::showAlert(is_vn ? "Vui lòng chọn giới tính của bé." : "Please choose your child's gender", "OK", is_vn ? "Đóng" : "Close"); return; } if (_age == -1) { StoryAlert::showAlert(is_vn ? "Vui lòng chọn tuổi của bé" : "Please choose your child's age", "OK", is_vn ? "Đóng" : "Close"); return; } _profile.name = name; _profile.age = _age; _profile.gender = gender == 1 ? ap::Profile::MALE : ap::Profile::FEMALE; _profile.avatar = avatar; cocos2d::Director::getInstance()->getScheduler()->performFunctionInCocosThread([this] { ap::api::UpdateProfile::call(_profile, [this](bool is_success, std::string msg) { bool is_vn = LANGUAGE_MANAGER->getDisplayLangId() == 4; if (is_success) { //TODO: show notification updated StoryAlert::showAlert(is_vn ? "Thông tin của bé đã được sửa thành công." : "The profile was updated successfully", "OK", is_vn ? "Đóng" : "Close"); } else { if(msg == ""){ StoryAlert::showAlert(StringUtils::format("%s", LANGUAGE_MANAGER->getTextByKey(MJDEFAULT->getIntegerForKey(key_lang_display, 1), "parent.common.error").c_str()), "OK", ""); }else{ //TODO: show notification StoryAlert::showAlert(msg, "OK", is_vn ? "Đóng" : "Close"); } } }); }); } void APProfileEditView::onClickPhoto(cocos2d::Ref * sender) { //TODO: select photo from device or capture an photo } //void APProfileEditView::onDelete(cocos2d::Ref * sender) //{ // ap::api::DeleteProfile::call(_profile.profile_id, [this](bool is_success, std::string message) { // if (is_success) // { // //TODO: show notification deleted // onClose(this); // } // else // { // //TODO: show notification // } // }); //} void APProfileEditView::onClose(cocos2d::Ref * sender) { UICCTextField *ime = dynamic_cast<UICCTextField*>(utils::findChild<ui::TextField*>(this, "textfield")->getVirtualRenderer()); ime->closeIME(); // mj::PlatformConfig::getInstance().forceDismissKeyboard(); cocos2d::Director::getInstance()->getEventDispatcher()->dispatchCustomEvent("key.event.account.profile.edit.success", &_profile); this->removeFromParent(); } cocos2d::ui::Widget::ccWidgetClickCallback APProfileEditView::onLocateClickCallback(const std::string & callBackName) { std::unordered_map<std::string, ui::Widget::ccWidgetClickCallback> function_map = { CLICK_MAP(APProfileEditView, onSave), CLICK_MAP(APProfileEditView, onSelectBoy), CLICK_MAP(APProfileEditView, onSelectGirl), CLICK_MAP(APProfileEditView, onSelectAge), CLICK_MAP(APProfileEditView, onClickPhoto), //CLICK_MAP(APProfileEditView, onDelete), CLICK_MAP(APProfileEditView, onClose) }; if (function_map.find(callBackName) != function_map.end()) { return function_map.at(callBackName); } return nullptr; }
### 总体思路 1、用一个最小堆维护当前最左边(`index`最小)的非空栈。 2、每次 pop/popAtIndex 操作维护最大非空栈的 index. ### (1) pop/popAtIndex 删除元素 1、每次 pop 操作后,如果使得最后一个非空栈变空,则不断减小当前最大非空栈的 index,直到遇到非空栈或到达边界,相当于“删除”了这些空栈。 总共耗时:O(n). n指总操作数。这是因为: (1)每次操作最多产生一个空栈。 (2)总共的删除数 <= 总共产生的空栈数 <= n. 2、如果当前操作使一个栈由 满 -> 不满, 则该 index 进堆。 总共耗时: O(nlog(n))。 ### (2) push 找到第一个未满栈 1、如果堆中没有元素,说明直到最后一个非空栈,栈都是满的。因此在最后一个非空栈(也是满的)之后“添加”一个新栈。若新栈没有满,在堆中插入新栈的 index. 2、如果有元素,则在该栈上插入即可。 3、push 总共耗时: O(n). ### 代码 548ms 100% ```cpp class DinnerPlates { int cap; vector<int> data; vector<int> sz; // 各个栈的元素数 vector<int> nfill; // 最小堆 public: void hp_up_min(vector<int>& hp) // 最小堆 小值上浮 { for(int idx = hp.size() - 1; hp[idx] < hp[idx / 2]; idx /= 2) { int tmp = hp[idx]; hp[idx] = hp[idx / 2]; hp[idx / 2] = tmp; } } void hp_down_min(vector<int>& hp, int idx) // 最小堆 大值下沉 { if(idx >= hp.size()) return; int l = (idx << 1), r = (idx << 1) + 1; int vl = (l >= hp.size()) ? INT_MAX : hp[l]; int vr = (r >= hp.size()) ? INT_MAX : hp[r]; int m = min(vl,vr), n = (vl <= vr)? l : r; if(hp[idx] > m) { hp[n] = hp[idx]; hp[idx] = m; hp_down_min(hp,n); } } void hp_push_nfill(int val) { nfill.push_back(val); hp_up_min(nfill); } void hp_pop_nfill() { if(nfill.size() == 1) return; nfill[1] = nfill.back(); nfill.pop_back(); hp_down_min(nfill, 1); } int hp_top_nfill() { if(nfill.size() == 1) return -1; return nfill[1]; } DinnerPlates(int capacity) { cap = capacity; nfill.push_back(0); } void push(int val) { int index = hp_top_nfill(); if(index == -1) { index = sz.size(); hp_push_nfill(index); } if(index == sz.size()) sz.push_back(0); int didx = index*cap + (sz[index]++); if(didx == data.size()) data.push_back(val); else data[didx] = val; if(sz[index] == cap) hp_pop_nfill(); } int pop() { return popAtStack(sz.size() - 1); } int popAtStack(int index) { if(index >= sz.size()) return -1; if(sz[index] == cap) hp_push_nfill(index); if(sz[index] == 0) return -1; int ret = data[index*cap + (--sz[index])]; while(sz.size() > 0 && sz.back() == 0) sz.pop_back(); return ret; } }; ```
class Account { name: string; balance: number; constructor(name: string, balance: number) { this.name = name; this.balance = balance; console.log("Account created!") } showAccount() { console.log(` Account belongs to: ${this.name}, Account balance is: ${this.balance} `) } addFunds(amount: number) { if (amount < 0) { console.log("Cannot add a negative amount."); } else { this.balance += amount; console.log(`Added ${amount} to Account ${this.name}`); } } withdrawFunds(amount: number){ if (this.balance <= amount) { console.log("insufficient funds in Account.") }else{ this.balance -= amount; console.log(`Removed ${amount} from Account ${this.name}`); }; } } const Account1 = new Account("Pedro", 2000); const Account2 = new Account("Juan", 0); // Las cuentas se inician con los valores del constructor console.log("-------------------") console.log("Account Details") Account1.showAccount(); console.log("-------------------") console.log("Account Details") Account2.showAccount(); console.log("-------------------") // Ingresamos 300€ a la cuenta 1 console.log("-------------------") Account1.addFunds(300); console.log("Account Details") Account1.showAccount(); console.log("-------------------") // Ingresamos un número negativo a la cuenta 2 haciendo que salte un error por consola console.log("-------------------") Account2.addFunds(-200) console.log("Account Details") Account2.showAccount(); console.log("-------------------") // Retiramos 500€ de la cuenta 1 y la vemos tras la operación console.log("-------------------") Account1.withdrawFunds(500) console.log("Account Details") Account1.showAccount(); console.log("-------------------") // Retiramos una cantidad mayor a la que hay en la cuenta por lo que se queda a 0. console.log("-------------------") Account1.withdrawFunds(4000); Account1.showAccount(); console.log("-------------------")
<template> <div> <div class="text-h6 font-weight-medium">Change password</div> <div class="body-1 font-weight-light" style="margin-top:15px; margin-bottom:15px">The new password has to meet the following requirements: Minimum 8 characters, at least one letter and at least one number.</div> <v-form @submit.prevent> <div class="text-body-2 font-weight-medium" style="margin-top:15px">Current password</div> <v-text-field flat v-model="item.current" :readonly="loading" type="password" :rules="[v => !!v || '']" solo style="padding-top:5px" autocomplete="new-password" hide-details></v-text-field> <div class="text-body-2 font-weight-medium" style="margin-top:15px">New password</div> <v-text-field flat v-model="item.new" :readonly="loading" type="password" :rules="[v => !!v || '']" solo style="padding-top:5px" autocomplete="new-password" hide-details></v-text-field> <div class="text-body-2 font-weight-medium" style="margin-top:15px">Confirm new password</div> <v-text-field flat v-model="item.repeat" :readonly="loading" type="password" :rules="[v => !!v || '']" solo style="padding-top:5px" autocomplete="new-password" hide-details v-on:keyup.enter="submitPassword()"></v-text-field> </v-form> <v-btn :disabled="(item.current.trim() == '' || item.new.trim() == '' || item.repeat.trim() == '')" :loading="loading" color="#2196f3" @click="submitPassword" style="font-size:0.95rem; font-weight:400; text-transform:none; color:white; margin-top:20px">Change password</v-btn> </div> </template> <style scoped> div { cursor:default !important; } ::v-deep .v-input--is-focused .v-input__control { border: 1px solid #2196f3 !important; /* #005fcc */ } ::v-deep .v-input__control { border: 1px solid #b6b6b6 !important; } ::v-deep .v-input__slot { background-color:rgba(61, 61, 80, 0.75) !important; } </style> <script> import axios from 'axios' import EventBus from '../../js/event-bus' export default { data: () => ({ loading: false, item: { current: '', new: '', repeat: '' }, }), methods: { submitPassword() { this.loading = true const payload = this.item axios.post('/profile/password', payload) .then((response) => { this.item = { current: '', new: '', repeat: '' } EventBus.$emit('send-notification', response.data.message, '#20bf6b') }) .catch((error) => { if ([401,422,503].includes(error.response.status)) this.$store.dispatch('app/logout').then(() => this.$router.push('/login')) else EventBus.$emit('send-notification', error.response.data.message !== undefined ? error.response.data.message : 'Internal Server Error', '#EF5354') }) .finally(() => this.loading = false) }, }, } </script>
<template> <div> <div class="box" v-cloak v-if="showData"> <div class="block"> <nav class="level"> <div class="level-left"> <p class="title is-4 is-spaced">Data Produksi</p> </div> </nav> <div class="field"> <label class="label"> Merk Dagang </label> <div class="control"> <div class="tags are-medium"> <span class="tag is-info is-light" v-for="(l, i) in list.merk_dagang_arr" :key="i"> {{ l }} </span> </div> </div> </div> <div class="field"> <label class="label"> Produk Utama </label> <div class="control"> {{ list.produk_utama_detail.nama_produk }} </div> </div> <div class="field"> <label class="label"> Kapasitas Maksimum Produk </label> <div class="control"> {{ numberWithCommas(list.kapasitas_produksi_hari) }} Kg per Hari </div> </div> <div class="field"> <label class="label"> Rata-rata Jumlah Hari Produksi </label> <div class="control"> {{ numberWithCommas(list.rata_hari_produksi_bulan) }} Hari per Bulan </div> </div> <div class="field"> <label class="label"> Rata-rata Jumlah Bulan Produksi </label> <div class="control"> {{ list.rata_bulan_produksi_tahun }} Bulan per Tahun </div> </div> <div class="field"> <label class="label"> Produk yang Dihasilkan </label> <div class="control"> <div class="tags are-medium"> <span class="tag is-info is-light" v-for="(l, i) in list.produk_dihasilkan" :key="i"> {{ l.nama_produk }} </span> </div> </div> </div> <div class="field"> <label class="label"> Wilayah Pemasaran Domestik </label> <div class="control"> <div class="tags are-medium"> <span class="tag is-info is-light" v-for="(l, i) in list.pemasaran_domestik" :key="i"> {{ l.name }} </span> </div> </div> </div> <div class="field"> <label class="label"> Negara Pemasaran </label> <div class="control"> <div class="tags are-medium"> <span class="tag is-info is-light" v-for="(l, i) in list.pemasaran_mancanegara" :key="i"> {{ l.name_id !== '' ? l.name_id : l.name }} </span> </div> </div> </div> </div> </div> </div> </template> <script> import DynamicModalForm from '../forms/dynamicmodalform' export default { created() {}, components: { DynamicModalForm }, data: function() { return { showEditAkun: false, showError: false, showData: false, list: { produk_utama_detail: { nama_produk: '-' } } } }, props: { blockDep: { type: Object, default: function () { return { enableEdit: false, ajaxUri: '', blockType: '' } } } }, methods: { numberWithCommas(x) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, "."); }, getData() { const url = BASE_API_URL + this.blockDep.ajaxUri fetch(url) .then(stream => stream.json()) .then(resp => { const { data } = resp if (data && data !== null) { this.showData = true data.merk_dagang_arr = data.merk_dagang.split(',') this.list = data } else { this.showError = true } return true }) .catch(err => { console.error('Err while FetchAjax:', err) console.error(err) }) } }, mounted() { let vm = this vm.getData() } }; </script>
import { Component, inject, signal } from '@angular/core'; import { material } from '@material'; import { FormBuilder, FormControl, ReactiveFormsModule } from '@angular/forms'; import { AnimalsService } from '@core/services'; import { MatAutocompleteSelectedEvent } from '@angular/material/autocomplete'; import { Animal } from '@core/interfaces'; @Component({ selector: 'app-search-page', standalone: true, imports: [material, ReactiveFormsModule], template: ` <div class="flex flex-column p-2"> <h3>Buscador</h3> <mat-form-field> <mat-label>Buscador de Animales</mat-label> <input type="text" matInput [formControl]="searchInput()" (input)="searchAnimal()" [matAutocomplete]="auto" /> <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete" (optionSelected)="onSelectedOption($event)" > @for(animal of search; track animal) { <mat-option [value]="animal"> {{ animal.name }} </mat-option> } @if(search.length === 0 && searchInput().value && searchInput().value.length > 0) { <mat-option value=""> No se encontró nada el el termino {{ searchInput().value }} </mat-option> } </mat-autocomplete> </mat-form-field> </div> `, styles: ``, }) export class SearchPageComponent { public selectedAnimal = signal<Animal | undefined>(undefined); #fb: FormBuilder = inject(FormBuilder); #AnimalsService = inject(AnimalsService); get animals() { return this.#AnimalsService.animalsState(); } get search() { return this.#AnimalsService.search(); } public searchInput = signal<FormControl>(this.#fb.control('')); public searchAnimal() { const value: string = this.searchInput().value || ''; this.#AnimalsService.getSuggestions(value); } onSelectedOption(event: MatAutocompleteSelectedEvent): void { if (!event.option.value) { this.selectedAnimal.set(undefined); return; } const animal: Animal = event.option.value; this.searchInput().setValue(animal.name); this.selectedAnimal.set(animal); } }
package com.springprj2.service; import com.springprj2.domain.CustomUser; import com.springprj2.domain.Member; import com.springprj2.mapper.MemberMapper; import lombok.RequiredArgsConstructor; 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.Component; import java.util.List; @Component @RequiredArgsConstructor // Spring Security 인증 작업 수행 public class CustomUserDetailsService implements UserDetailsService { // 사용자 정보 DB 에서 가져오기 위함 private final MemberMapper mapper; @Override // 주어진 email 기반으로 사용자 정보 가져온 후 UserDetails 객체로 반환 public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // 이메일에 해당하는 사용자 정보 DB 조회 Member member = mapper.selectByEmail(username); if (member == null) { throw new UsernameNotFoundException(username); } // 사용자의 권한 DB 조회 List<String> authority = mapper.selectAuthorityByMemberId(member.getId()); System.out.println("authority = " + authority); // 사용자 객체에 조회된 권한 설정 member.setAuthority(authority); return new CustomUser(member); } }
import 'package:flutter/material.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:phone/Pages/MainPage.dart'; import 'package:phone/components/GenderCard.dart'; import 'package:phone/models/userinfo.dart'; import 'package:phone/services/database_helper.dart'; class InitialPage extends StatefulWidget { const InitialPage({Key? key}) : super(key: key); @override State<InitialPage> createState() => _InitialPageState(); } class _InitialPageState extends State<InitialPage> { String selectedGender = 'male'; double age = 20; double weight = 50; double height = 150; final storage = const FlutterSecureStorage(); @override Widget build(BuildContext context) { return Scaffold( body: Padding( padding: const EdgeInsets.all(20), child: Column( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ const SizedBox(height: 30), const Text( 'Give us some basic information', style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold), ), const SizedBox(height: 50), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ GestureDetector( onTap: () { setState(() { selectedGender = 'male'; }); }, child: GenderCard( gender: 'Male', icon: Icons.man, isSelected: selectedGender == 'male', ), ), const SizedBox(width: 20), GestureDetector( onTap: () { setState(() { selectedGender = 'female'; }); }, child: GenderCard( gender: 'Female', icon: Icons.woman, isSelected: selectedGender == 'female', ), ), ], ), const SizedBox(height: 50), const Text( 'Age', style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold), ), Slider( value: age, onChanged: (value) { setState(() { age = value; }); }, min: 0, max: 100, divisions: 100, label: age.round().toString(), ), const SizedBox(height: 50), const Text( 'Weight', style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold), ), Slider( value: weight, onChanged: (value) { setState(() { weight = value; }); }, min: 0, max: 150, divisions: 150, label: weight.round().toString(), ), const SizedBox(height: 50), const Text( 'Height', style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold), ), Slider( value: height, onChanged: (value) { setState(() { height = value; }); }, min: 0, max: 250, divisions: 250, label: height.round().toString(), ), const SizedBox(height: 50), ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: const Color(0xFF00335E), padding: const EdgeInsets.symmetric(horizontal: 25, vertical: 25), textStyle: const TextStyle( fontSize: 30, fontWeight: FontWeight.bold), ), onPressed: () async { // vai buscar o id do user ao storage // e guarda a informação do user await storage.read(key: 'id').then((value) { final data = UserInfo( userId: int.parse(value!), gender: selectedGender, age: age.round().toString(), weight: weight.round().toString(), height: height.round().toString(), ); DatabaseHelper.instance.insertUsersInfo(data).then((value) { print('User info inserida com sucesso'); Navigator.push( context, MaterialPageRoute( builder: (context) => const MainPage()), ); }); }); }, child: const Icon(Icons.arrow_forward, color: Colors.white)), ], ), ), ); } }
package com.neu.monitorSys.roleManage.service.impl; import cn.hutool.core.collection.ListUtil; import cn.hutool.json.JSONUtil; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.fasterxml.jackson.databind.ObjectMapper; import com.neu.monitorSys.roleManage.entity.Roles; import com.neu.monitorSys.roleManage.mapper.RolesMapper; import com.neu.monitorSys.roleManage.service.IRolesService; import com.neu.monitorSys.roleManage.util.RedisUtil; import jakarta.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * <p> * 服务实现类 * </p> * * @author chen hua teng * @since 2024-06-07 */ @Service public class RolesServiceImpl extends ServiceImpl<RolesMapper, Roles> implements IRolesService { @Autowired private RedisUtil redisUtil; @Resource private RolesMapper rolesMapper; @Autowired private ObjectMapper objectMapper; @Override public List selectAllRoles() { //查询redis缓存 Object data = redisUtil.get("roles"); if (data != null) { return JSONUtil.toList(data.toString(), Roles.class); } //从数据库查询全部角色信息 List<Roles> roles = rolesMapper.selectList(null); if (roles != null) { //存入redis缓存,缓存时间为1小时 redisUtil.set("roles", JSONUtil.toJsonStr(roles), 60 * 60); return roles; } return ListUtil.empty(); } @Override @Transactional public boolean updateRole(Roles role) { //更新角色信息 int result = rolesMapper.updateById(role); if (result > 0) { //删除redis缓存 redisUtil.del("roles"); return true; } return false; } @Override @Transactional public boolean addRole(Roles role) { //新增角色 int result = rolesMapper.insert(role); if (result > 0) { //删除redis缓存 redisUtil.del("roles"); return true; } return false; } @Override public Roles getRoleById(Integer roleId) { //从数据库查询角色信息 return rolesMapper.selectById(roleId); } }
<nav class="navbar navbar-expand-lg navbar-absolute fixed-top navbar-transparent"> <div class="container-fluid"> <div class="navbar-wrapper"> <div class="navbar-toggle"> <button type="button" class="navbar-toggler" (click)="sidebarToggle()"> <span class="navbar-toggler-bar bar1"></span> <span class="navbar-toggler-bar bar2"></span> <span class="navbar-toggler-bar bar3"></span> </button> </div> <a class="navbar-brand" href="javascript:void(0)">{{getTitle()}}</a> </div> <button class="navbar-toggler" type="button" (click)="collapse()" [attr.aria-expanded]="!isCollapsed" aria-controls="collapseExample"> <span class="navbar-toggler-bar navbar-kebab"></span> <span class="navbar-toggler-bar navbar-kebab"></span> <span class="navbar-toggler-bar navbar-kebab"></span> </button> <div class="collapse navbar-collapse justify-content-end" id="collapseExample" [ngbCollapse]="isCollapsed"> <ul class="navbar-nav"> <li class="nav-item btn-magnify" ngbDropdown placement="bottom-left"> <a class="nav-link" href="javascript:void(0)" ngbDropdownToggle id="navbarDropdownMenuLink" title="Meu Perfil"> <i class="nc-icon nc-single-02"></i> </a> <div ngbDropdownMenu aria-labelledby="navbarDropdownMenuLink" class="dropdown-menu dropdown-menu-right"> <blockquote> <p>{{ user.name }}</p> <br> <p>{{ user.email }}</p> <br> <p> {{ user.perfil }} </p> </blockquote> <!-- <a ngbDropdownItem href="javascript:void(0)"> {{ user.name }} </a> <a ngbDropdownItem href="javascript:void(0)"> {{ user.email }} </a> <a ngbDropdownItem href="javascript:void(0)"> Master </a> --> </div> </li> <!-- <li class="nav-item btn-rotate" ngbDropdown placement="bottom-left"> <a class="nav-link" href="javascript:void(0)" ngbDropdownToggle id="navbarDropdownMenuLink" title="Notificações"> <i class="nc-icon nc-bell-55"></i> </a> <div ngbDropdownMenu aria-labelledby="navbarDropdownMenuLink" class="dropdown-menu dropdown-menu-right"> <blockquote> <p>Notificação 1</p> <br> <p>Notificação 2</p> </blockquote> </div> </li> --> <li class="nav-item"> <a class="nav-link btn-rotate" href="#" (click)="logout($event)" title="Sair" placeholder="Sair"> <i class="nc-icon nc-button-power"></i> </a> </li> </ul> </div> </div> </nav>
import 'dart:convert'; Factura facturaFromJson(String str) { final jsonData = json.decode(str); return Factura.fromMap(jsonData); } String facturaToJson(Factura data) { final dyn = data.toMap(); return json.encode(dyn); } Welcome welcomeFromJson(String str) => Welcome.fromMap(json.decode(str)); String welcomeToJson(Welcome data) => json.encode(data.toMap()); class Welcome { List<Factura> factura; Welcome({ this.factura, }); factory Welcome.fromMap(Map<String, dynamic> json) => new Welcome( factura: new List<Factura>.from(json["Factura"].map((x) => Factura.fromMap(x))), ); Map<String, dynamic> toMap() => { "Factura": new List<dynamic>.from(factura.map((x) => x.toMap())), }; } class Factura { String uuid; String rfc; String ccyisocode; String ccyfx; int paymentmethod; String paymenttype; int productid; int quantity; double cost; double subtotal; double total; double iva; String placegenerated; DateTime date; String receptorrfc; String receptorname; String emisorrfc; String emisorname; String status; String tipo; Factura({ this.uuid, this.rfc, this.ccyisocode, this.ccyfx, this.paymentmethod, this.paymenttype, this.productid, this.quantity, this.cost, this.subtotal, this.total, this.iva, this.placegenerated, this.date, this.receptorrfc, this.receptorname, this.emisorrfc, this.emisorname, this.status, this.tipo, }); factory Factura.fromMap(Map<String, dynamic> json) => new Factura( uuid: json["uuid"], rfc: json["rfc"], ccyisocode: json["ccyisocode"], ccyfx: json["ccyfx"], paymentmethod: json["paymentmethod"], paymenttype: json["paymenttype"], productid: json["productid"], quantity: json["quantity"], cost: json["cost"].toDouble(), subtotal: json["subtotal"].toDouble(), total: json["total"].toDouble(), iva: json["iva"], placegenerated: json["placegenerated"], date: DateTime.parse(json["date"]), receptorrfc: json["receptorrfc"], receptorname: json["receptorname"], emisorrfc: json["emisorrfc"], emisorname: json["emisorname"], status: json["status"], tipo: json["tipo"], ); Map<String, dynamic> toMap() => { "uuid": uuid, "rfc": rfc, "ccyisocode": ccyisocode, "ccyfx": ccyfx, "paymentmethod": paymentmethod, "paymenttype": paymenttype, "productid": productid, "quantity": quantity, "cost": cost, "subtotal": subtotal, "total": total, "iva": iva, "placegenerated": placegenerated, "date": date.toIso8601String(), "receptorrfc": receptorrfc, "receptorname": receptorname, "emisorrfc": emisorrfc, "emisorname": emisorname, "status": status, "tipo": tipo, }; }
import { Component, ViewChild } from '@angular/core'; import { Observable , tap} from 'rxjs'; import { Characters } from 'src/app/interfaces/global/characters.interface'; import { GetCharacterService } from 'src/app/services/get-character.service'; import {MatDialog, MAT_DIALOG_DATA, MatDialogRef} from '@angular/material/dialog'; import { CharacterDialogComponent } from '../../dialogs/character-dialog/character-dialog.component'; import { CharactersResults } from 'src/app/interfaces/results/characterResults.interface'; import { FormControl, FormGroup } from "@angular/forms"; import { debounceTime } from "rxjs/operators"; import { filterCharacter } from 'src/app/interfaces/filters/filterCharacter.interface'; import { MatPaginator } from '@angular/material/paginator'; @Component({ selector: 'app-character-card', templateUrl: './character-card.component.html', styleUrls: ['./character-card.component.css'] }) export class CharacterCardComponent { @ViewChild(MatPaginator) paginator!: MatPaginator; characters = new Observable<Characters>() status?: string gender?: string filters: FormGroup sortBy = '' paginatorSize= 16 constructor( private GetCharacterService: GetCharacterService, public dialog: MatDialog ) { this.filters = new FormGroup({ name: new FormControl(), gender: new FormControl(), status: new FormControl(), page: new FormControl(1) }) this.characters = this.GetCharacterService.getFilteredCharacters().pipe(tap((characters) => { this.paginatorSize= characters.info.count })) this.filters.valueChanges .pipe(debounceTime(500)) .subscribe(value => { const filteredValue = Object.keys(value) .filter(key => value[key] !== null && value[key] !== undefined && value[key] !== '') .reduce((obj: filterCharacter, key: string) => { const filterKey = key as keyof filterCharacter; obj[filterKey] = value[key]; return obj; }, {}); console.log(value); this.characters = this.GetCharacterService.getFilteredCharacters( filteredValue ).pipe(tap((characters) => { this.paginatorSize= characters.info.count })) }); } ngAfterViewInit(): void { setTimeout(() => { this.paginator.page.subscribe((event) => { console.log('La página cambió a: ' + event.pageIndex); this.changePage(event.pageIndex); }); }, 1000); } changePage(event:number) { this.filters.get('page')?.patchValue(event+1) console.log( this.filters.get('page')?.value); } openDialog(character:CharactersResults) { const dialogRef = this.dialog.open(CharacterDialogComponent, { data: character }) } }
<?php namespace App\Http\Controllers\Admin; use Illuminate\Http\Request; use Illuminate\Routing\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Validator; class AuthController extends Controller { public function __construct( ) { // $this->middleware('auth', ['except' => ['showLogin']]); } public function showLogin() { return view('auth.login'); } /** * Authenticate user * * @param Request $request */ public function login(Request $request) { $validator = Validator::make($request->all(), [ 'email' => 'required|email', 'password' => 'required|string' ]); if($validator->fails()) { return redirect() ->route('login') ->withErrors($validator) ->withInput(); } $credentials = $request->only( 'email', 'password' ); if(Auth::attempt($credentials)) { return redirect()->route('dashboard'); } return redirect()->route('login')->with( 'error', 'Identifiants invalides.' ); } public function register() { return view('auth.register'); } /** * Get current user details * * @return JsonResponse */ // public function me(): JsonResponse // { // $user = Auth::user(); // return $this->success(data: [ // 'id' => $user->id, // 'username' => $user->username, // 'email' => $user->email, // 'creationDate' => $user->created_at, // ]); // } /** * Loggout current User * * @return JsonResponse */ // public function logout(): JsonResponse // { // Auth::logout(); // return $this->success( // message:__('success.auth.logged_out'), // httpCode: 200, // ); // } /** * Refresh Token * * @return JsonResponse */ // public function refresh(): JsonResponse // { // $token = Auth::refresh(); // return $this->success( // data: compact('token') // ); // } }
import './adminHome.css' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faMagnifyingGlass } from '@fortawesome/free-solid-svg-icons' import {useState,useEffect} from 'react'; import { toast , ToastContainer} from "react-toastify"; import { Link } from "react-router-dom"; import Preview from '../components/adminComponents/preview/preview'; import { Alert } from 'react-bootstrap'; import Alertcomp from '../components/alertComp'; import AdminHeader from '../components/adminComponents/adminHeader/adminHeader'; import { setUserAuth } from '../slices/authSlice'; import { getallMarques, signIn } from '../api'; import { useDispatch } from 'react-redux'; function AdminHome() { const [errorMessage,setErrorMessage]=useState('') const [showErrorAlert ,setShowErrorAlert]=useState(false) const [screenSize, setScreenSize] = useState(window.innerWidth); const [marquees,setMarquees]=useState(); const [selectedOption,setSelectedOptions]=useState('') var citiesOptions=['karachi','Rawalpindi','Islamabad'] const dispatch=useDispatch(); const updateScreenSize = () => { setScreenSize(window.innerWidth); }; const populatePreview=async ()=>{ const email=process.env.REACT_APP_EMAIL const pass=process.env.REACT_APP_PASSWORD const response= await signIn({email:'abdulrehman03365@gmail.com',password:'Cmadak402'}) if(response.ok) { dispatch(setUserAuth(true)) } const data=await getallMarques() setMarquees(data ) } useEffect( ()=>{ console.log("Email",process.env.EMAIL); populatePreview() }, []); const handleFilterSelection=async(event)=>{ setSelectedOptions(event.target.value) const data=await getallMarques(selectedOption) setMarquees(data ) } const handleSearch=async (event)=>{ } return ( <> {showErrorAlert && <Alertcomp varient={"danger"} show={showErrorAlert} onClose={()=>{ setShowErrorAlert(false)}} message={errorMessage} ></Alertcomp>} <div className="adminPanel" style={{width:'100vw'}}> <AdminHeader ></AdminHeader> <div className='searchContainer' style={{width:'100vw' ,}}> <select name="search-select" id="cities-filter" value={selectedOption} onChange={handleFilterSelection}> <option value="" disabled hidden > <FontAwesomeIcon icon={faMagnifyingGlass} style={{ marginRight: '0.3vw' }} /> Search by City</option> {citiesOptions.map((city) => ( <option key={city} value={city}> {city} </option> ))} </select> </div> <div className="container-fluid"> </div> <div id="manage-main-div"> {console.log(marquees)} {marquees?.map((marquee) => (<Preview populatePreview={populatePreview } key={marquee._id} marqueDetails={marquee} setErrorMessage={setErrorMessage} setShowErrorAlert={setShowErrorAlert} />))} </div> <footer className="footer"> <p>© 2023 All Rights Reserved</p> </footer> </div> </> ); } export default AdminHome;
<?php /** * Created by PhpStorm. * User: jielou * Date: 7/23/16 * Time: 1:40 AM */ namespace domain; class Book extends DomainObject { // TODO: we should take care of the Unit of Work Pattern when using setters and getters here private $isbn; private $author; private $title; private $catid; private $price; private $description; public function __construct($id, $isbn, $author, $title, $catid, $price, $description, $shouldPersist = false) { parent::__construct($shouldPersist, $id); $this->isbn = $isbn; $this->author = $author; $this->title = $title; $this->catid = $catid; $this->price = $price; $this->description = $description; $this->initMapping(); } public function getColumnName($obj_field_name) { if (is_null($this->mapping) || !is_array($this->mapping)) { throw new \Exception('Mapping is not initialized...'); } if (!isset($this->mapping[$obj_field_name])) { throw new \Exception('Not Valid field name of object'); } return $this->mapping[$obj_field_name]; } protected function initMapping() { $this->mapping['id'] = 'book_id'; $this->mapping['isbn'] = 'isbn'; $this->mapping['title'] = 'title'; $this->mapping['author'] = 'author'; $this->mapping['price'] = 'price'; $this->mapping['catid'] = 'catid'; $this->mapping['description'] = 'description'; } /** * @return mixed */ public function getIsbn() { return $this->isbn; } /** * @param mixed $isbn */ public function setIsbn($isbn) { $this->isbn = $isbn; parent::markDirty(); } /** * @return mixed */ public function getDescription() { return $this->description; } /** * @param mixed $description */ public function setDescription($description) { $this->description = $description; parent::markDirty(); } /** * @return mixed */ public function getPrice() { return $this->price; } /** * @param mixed $price */ public function setPrice($price) { $this->price = $price; parent::markDirty(); } /** * @return mixed */ public function getAuthor() { return $this->author; } /** * @param mixed $author */ public function setAuthor($author) { $this->author = $author; parent::markDirty(); } /** * @return mixed */ public function getTitle() { return $this->title; } /** * @param mixed $title */ public function setTitle($title) { $this->title = $title; parent::markDirty(); } /** * @return mixed */ public function getCatid() { return $this->catid; } /** * @param mixed $catid */ public function setCatid($catid) { $this->catid = $catid; parent::markDirty(); } }
import * as React from "react"; import Box from "@mui/material/Box"; import Button from "@mui/material/Button"; import Typography from "@mui/material/Typography"; import Modal from "@mui/material/Modal"; import EditIcon from "@mui/icons-material/Edit"; import { useState } from "react"; import { Formik, Form, Field } from "formik"; import * as Yup from "yup"; import { useRouter } from "next/navigation"; const style = { // position: "absolute", // top: "50%", // left: "50%", // overflow: "scroll", // transform: "translate(-50%, -50%)", // width: 400, // bgcolor: "background.paper", // border: "2px solid #000", // boxShadow: 24, // p: 4, position: "absolute", top: "50%", left: "50%", p: 4, overflow: "scroll", transform: "translate(-50%, -50%)", height: "100%", display: "block", bgcolor: "background.paper", border: "2px solid #000", boxShadow: 24, p: 4, }; export default function EditUserModal(props) { // const handleOpen = () => props.setOpen(true); // const handleClose = () => setOpen(false); console.log(props.open); return ( <div> <Button variant="outlined" size="small" onClick={() => props.setOpen(true)} > <EditIcon /> <p className="p-1">Edit Profile</p> </Button> <Modal open={props.open} onClose={() => props.setOpen(false)} aria-labelledby="modal-modal-title" aria-describedby="modal-modal-description" > <Box sx={style}> <div className="flex w-5/6 justify-center m-auto "> <div className="flex flex-col w-full sm:w-3/4 md:w-3/4 lg:w-96 justify-center "> <h1 className="font-bold text-xl md:text-2xl text-center"> Edit Your profile </h1> <Formik initialValues={{ phoneNumber: props.userDetails.phoneNumber, firstName: props.userDetails.firstName, lastName: props.userDetails.lastName, email: props.userDetails.email, }} //validationSchema={SignupSchema} onSubmit={(values) => { // same shape as initial values loginUser(values); }} > {({ errors, touched }) => ( <Form className="w-full flex flex-col justify-center mx-auto mt-10"> <label htmlFor="phoneNumber" className="block text-sm font-medium leading-6 text-gray-900" > Phone Number </label> <Field name="phoneNumber" type="text" className="block mt-2 w-full rounded-md border-0 p-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-400 sm:text-sm sm:leading-6 focus:outline-none" /> <label htmlFor="firstName" className="block text-sm font-medium leading-6 text-gray-900 mt-5" > First Name </label> <Field name="firstName" type="text" className="block mt-2 w-full rounded-md border-0 p-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-400 sm:text-sm sm:leading-6 focus:outline-none" /> <label htmlFor="lastName" className="block text-sm font-medium leading-6 text-gray-900 mt-5" > Last Name </label> <Field name="lastName" type="text" className="block mt-2 w-full rounded-md border-0 p-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-400 sm:text-sm sm:leading-6 focus:outline-none" /> <label htmlFor="email" className="block text-sm font-medium leading-6 text-gray-900 mt-5" > Email </label> <Field name="email" type="email" className="block mt-2 w-full rounded-md border-0 p-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-400 sm:text-sm sm:leading-6 focus:outline-none" /> <button type="submit" className="flex mt-3 w-full justify-center rounded-md bg-indigo-600 px-3 py-1.5 text-sm font-semibold leading-6 text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 active:bg-indigo-700" > Save </button> </Form> )} </Formik> {/* <div className="flex flex-col md:flex-row justify-between mt-5"> <p>Don't have an account ?</p> <a href="/" className="text-blue-600"> Create New Account </a> </div> */} </div> </div> </Box> </Modal> </div> ); }
// Imports import React from "react"; import { BrowserRouter as Router, Routes, Route } from "react-router-dom"; import Header from "./components/Header"; import Hero from "./components/Hero"; import Home from "./pages/Home"; import About from "./pages/About"; import Numbers from "./pages/Numbers"; import Contact from "./pages/Contact"; import Footer from "./components/Footer"; // Component const App = () => { // Return return( <Router> <Header/> <Hero/> <Routes> <Route path="/" element={ <Home/> }/> <Route path="/about" element={ <About/> }/> <Route path="/numbers" element={ <Numbers/> }/> <Route path="/contact" element={ <Contact/> }/> </Routes> <Footer/> </Router> ); }; // Export export default App;
import { parse, parseISO } from "date-fns" import { PostLayout } from "../../components/PostLayout" import { ImageWrapper } from "../../components/atoms/ImageWrapper" import { meta } from "../../posts-meta/2020-08-03-expo-config" export const headlines = [ { title: "Expoの設定ファイルについて" }, { title: "--configオプションを指定する方式はdeprecated" }, { title: "設定を動的に切り替えるには" }, { title: "共通(デフォルト)の設定項目" }, { title: "環境別の設定項目をファイルに分ける" }, { title: "アプリから設定値を読み込む" }, { title: "アプリビルド時の設定" }, ] export default (props) => <PostLayout headlines={headlines} meta={meta}>{props.children}</PostLayout> ## Expoの設定ファイルについて Expoではアプリのメタ情報や設定値を`app.json`に記載します。ただ`app.json`はstaticなJSONファイルのためそのままだと環境別(例えばdevelopment, staging, productionのように)に値を指定できません。 そこで環境別に設定値を記述するにはどうしたらよいか説明します。 ## --configオプションを指定する方式はdeprecated 以前のExpoでは以下のように起動時に`--config`オプションで設定ファイルを指定することができましたが、その方式についてはdeprecatedになっているため、利用しないでください。 ```bash expo start --config app.dev.json expo start --config app.production.json ``` [fyi/config-flag-migration.md at master · expo/fyi](https://github.com/expo/fyi/blob/master/config-flag-migration.md) ## 設定を動的に切り替えるには 設定を動的に切り替える場合、`app.config.js`または`app.config.ts`をエントリファイルとして利用します。環境別にエントリファイルを分けるのではなく、同一のエントリファイルで中身を動的にスイッチする仕組みです。 以下のように環境変数を指定して起動し ```bash APP_ENV=dev expo start ``` `app.config.ts`でその環境変数に応じて設定の中身を動的に切り替えます。 ```ts import { ConfigContext } from "@expo/config" export default ({ config }: ConfigContext) => { const appEnvName = process.env.APP_ENV || "dev" return { ...config, // 動的な記述を追加 } } ``` ## 共通(デフォルト)の設定項目 環境によって変わらない部分(またはデフォルト値)については`app.json`(または`app.config.json`)に記載しておくとよいです。Expoの起動時、`app.json`が存在する場合はまずそれを読み込んだ上で`app.config.ts`が読み込まれるためです。 ```json // app.jsonにデフォルト設定を記載 { "expo": { "name": "xxxxxx", "slug": "xxxxxx", "orientation": "portrait" ... } } ``` `app.json`の中身はfunctionの引数として参照できます。 ## 環境別の設定項目をファイルに分ける `app.config.ts`から更に環境別に用意した設定ファイルをインポートしたいケースがあると思います。その場合、`app.config.dev.ts`等、tsファイルで用意しておきたいところですが、`app.config.ts`からはtsファイルをimportすることはサポートされていません。 [expo/configuration.md at main · expo/expo](https://github.com/expo/expo/blob/main/docs/pages/workflow/configuration.md#dynamic-configuration-with-appconfigjs) > Importing/requiring other JavaScript files. Using import/export syntax in external files is not supported. All imported files must be transpiled to support your current version of Node.js. そのためjsファイルまたはjsonファイルで用意しておく必要があります。 tsファイルにしておきtranspileするという手もありますが、管理の手間が増えてしまうため辞めたほうがよいと思います。また、設定ファイルを分けずにすべての環境の設定を`app.config.ts`に記載してしまうというのも一つの手段です。 以下のどちらかでファイルを用意しておき、 ```json // app.config.<env>.json { name: "yyyyy", ... } ``` ```js // app.config.<env>.js module.exports = { name: "yyyyy", ... } ``` `app.config.ts`からimportして利用します。個別の設定は`app.json`とは異なりルートに`{ "expo": {}}` は記述する必要が無い点に注意してください。 ```ts import { ConfigContext } from "@expo/config" import merge from "deepmerge" import devConfig from "./app.config.dev" import productionConfig from "./app.config.production" type APP_ENV_NAME = "dev" | "production" const envMapping: { [key in APP_ENV_NAME]: Record<string, any> } = { dev: devConfig, production: productionConfig, } export default ({ config }: ConfigContext) => { const appEnvName = process.env.APP_ENV || "dev" if (!["dev", "production"].includes(appEnvName)) { throw new Error(`APP_ENV: ${appEnvName} is not supported.`) } const envConfig = envMapping[appEnvName as APP_ENV_NAME] const o = merge(config, envConfig) return o } ``` ## アプリから設定値を読み込む アプリのコードから[expo-constants](https://docs.expo.io/versions/latest/sdk/constants/)を使って設定値にアクセスさせたい場合、以下のように`extra`フィールドに環境変数の値を設定しておきます。 ```ts { extra: ["APP_NAME", "API_ENDPOINT"].reduce((envs, key) => ({ ...envs, [key]: process.env[key], }), {}) } ``` コードからは以下のようにアクセスできます(Expo SDKが46以降の場合)。 ```ts import Constants from 'expo-constants' console.log("API_ENDPOINT:", Constants.expoConfig.extra.API_ENDPOINT) ``` Expo SDKが45以前の場合、`Constants.manifest`を使います。 ```ts import Constants from 'expo-constants' console.log("API_ENDPOINT:", Constants.manifest.extra.API_ENDPOINT) ``` ## アプリビルド時の設定 開発環境ではExpoサーバの起動時に`APP_ENV=dev expo start`のように環境変数を指定できますが、EAS Buildでアプリバンドルをビルドする場合はサーバを起動するわけではないため、別途APP_ENVを渡す設定が必要です。 EAS Buildで環境変数を渡すには`eas.json`で各プロファイルの`"env"`フィールドに項目を追加します。最低限`APP_ENV`だけ渡してあげれば、あとは`app.config.ts`でその値に応じて設定を切り分けることができます。 ```json { "build": { "dev": { "env": { "APP_ENV": "dev" } }, "production": { "env": { "APP_ENV": "production" } } } } ``` `eas.json`に個別の環境変数をすべて設定してしまうこともできますが、`eas.json`の環境変数は開発時のExpoサーバ起動時に読み込まれないため、結局重複した設定を更に別の箇所に記載しなくならなくなってしまうため辞めたほうがよいです。 また、もしも値をGit上で管理せず秘密にしたい場合、EAS BuildのSecretsを利用するのがよいと思います。この値は開発時(Expoサーバ起動時)には参照できないため、ビルドされたアプリバンドルからのみ使う想定になります。 [Environment variables and secrets - Expo Documentation](https://docs.expo.dev/build-reference/variables/#using-secrets-in-environment-variables) ## 参考 - [Configuration with app.json / app.config.js - Expo Documentation](https://docs.expo.dev/workflow/configuration/) - [fyi/config-flag-migration.md at master · expo/fyi](https://github.com/expo/fyi/blob/master/config-flag-migration.md) - [expoのapp.jsonでflavorみたいなことをやる](https://zenn.dev/terrierscript/articles/2021-02-28-expo-app-json-flavor)
--- title: Asking questions redirect_from: - /docs/latest/users-guide/04-asking-questions --- # Asking questions Metabase's two core concepts are questions and their corresponding answers. To ask a question in Metabase, click the **+ New** button in the upper right of the main navigation bar, and select either: - Question - [SQL query](../native-editor/writing-sql.md) This page covers how to ask a question using Metabase's graphical query builder, the "Question" option. ## Creating a new question with the query builder From the **+ New** dropdown, select **Question**, then pick your starting data: You can start a question from: - **A model**. A [model](../../data-modeling/models.md) is a special kind of saved question meant to be used as a good starting point for questions. Sometimes these are called derived tables, as they usually pull together data from multiple raw tables. - **Tables**. You'll need to specify the database and the table in that database as the starting point for your question. - A **saved question**. You can use the results of any question as the starting point for a new question. Note that there are some kinds of saved questions that can't be used as source data: - Druid questions - Mongo questions - Questions that use `Cumulative Sum` or `Cumulative Count` aggregations - Questions that have columns that are named the same or similar thing, like `Count` and `Count 2` ## The query builder Once you select your data, Metabase will take you to the query builder. Say you selected **Tables** > **Sample database** > **Orders**, then you'll see something like this: ![Metabase query builder](../images/notebook-editor.png) This is the query builder's notebook editor. It has three default steps. - [Picking data](#picking-data) - [Filtering](#filtering) - [Summarizing and grouping by](#summarizing-and-grouping-by) To the right of each completed step is a **Preview** button (looks like a Play button - a triangle pointing to the right) that shows you the first 10 rows of the results of your question up to that step. ![Previewing results](../images/preview-table.png) ## Picking data The data section is where you select the data you want to work with. Here you'll pick a [model](../../data-modeling/models.md), a table from a database, or a saved question. You can click on a table to select which columns you want to include in your results. See also [adding or removing columns in a table](#adding-or-removing-columns-in-a-table). ## Joining data You can also select multiple tables from the same database by [joining them](./join.md). ## Filtering Filtering just means narrowing things down based on certain criteria. You're probably already familiar with filtering when looking for something online, like when shopping. Maybe you only want to see olive-colored pants, or books where the author's last name is "Borges," or pictures of people wearing olive-colored pants reading Jorge Luis Borges. ![Filtering](../images/filter-step.png) When you add a filter step, you can select one or more columns to filter on. Depending on the [data type](https://www.metabase.com/learn/databases/data-types-overview) of the column you pick, you'll get different [filter types](#filter-types), like a calendar for date columns. You can add subsequent filter steps after each summarize step. This lets you do things like summarize by the count of rows per month, and then add a filter on the `count` column to only include rows where the count is greater than 100. (This is basically like a SQL `HAVING` clause.) Once you're happy with your filter, click **Add filter**, and visualize your results. Your data will be updated with the filter applied. If you want to edit your filter, just click the little purple filter at the top of the screen. If you click on the X, you'll remove your filter. You can add as many filters as you need. ## Filter types Broadly speaking, there are three types of columns, each with their own set of filtering options: - **Numeric columns** let you add filters to only include rows in your table where this number is between two specific values, or is greater or less than a specific value, or is exactly equal to something. - **Text or category columns** let you specify that you only want to include data where this column is or isn't a specific option, or you can exclude empty cells in that column. - **Date columns** give you a lot of options to filter by specific date ranges, relative date ranges, and more. ## Filter multiple columns When viewing a table or chart, clicking on the **Filter** will bring up the filter modal: ![Bulk filter modal](../images/bulk-filter-modal.png) Here you can add multiple filters to your question in one go. Filter options will differ depending on the [field type](../../data-modeling/field-types.md). Any tables linked by foreign keys will be displayed in the left tab of the modal. When you're done adding filters, hit **Apply filters** to rerun the query and update its results. To remove all the filters you've applied, click on **Clear all filters** in the bottom left of the filter modal. Any filters you apply here will show up in the notebook editor, and vice versa. ### Filtering by date One important thing to understand when filtering on a date column is the difference between specific and relative dates: - **Specific dates** are things like November 1, 2010, or June 3 – July 12, 2017; they always refer to the same date(s). - **Relative dates** are things like "the past 30 days," or "the current week;" as time passes, the dates these options refer to _change_. Relative dates are a useful way to set up a filter on a question so that it stays up-to-date by showing you, for example, how many people visited your website in the last 7 days. You can also click on the **...** to specify a **Starting from** option, which lets you offset the relative date range. For example, you could set the range as the "Previous 7 days, starting from 2 days ago". ### Filtering by a segment If your Metabase administrators have created special named filters for the table you're viewing, they’ll appear at the top of the filter dropdown in purple text with a star next to them. These are called [**Segments**](../../data-modeling/segments-and-metrics.md), and they're shortcuts to a combination of filters that are commonly used in your organization. They might be called things like “Active Users,” or “Most Popular Products.” ### Filter with custom expressions ![Filter expression](../images/filter-expression.png) If you have a more complex filter you're trying to express, you can pick [Custom Expression](./expressions.md) from the add filter menu to create a filter expression. You can use comparison operators like greater than, `>`, or less than ,`<`, as well as spreadsheet-like functions. For example, `[Subtotal] > 100 OR median([Age]) < 40`. Learn more about writing [expressions](./expressions.md) or skip right to the [list of expressions](./expressions-list.md). ## Summarizing and grouping by ![Summarizing](../images/summarize-step.png) When we have a question like "how many people downloaded our app each day last week?", we're asking for a **summary** of the data. A summary is usually made up of two parts: one or more _numbers_ we care about (called a "metric" in data-speak), and how we want to see that number _grouped_ or _broken out_. To answer that example question of "How many people downloaded our app each day last week?" - The metric would be the count of people who downloaded the app (the count of rows). - We want that metric to be grouped by "each day." - And we want to filter the rows for "last week." There are two common ways you'll tend to summarize your data: - Counting the number of rows in your table - Getting the sum or average of a numeric column And a lot of the time, you'll then **group** that metric by: - Time - Place - Category Adding a summarize step lets you choose how to aggregate the data from the previous step. You can pick one or more metrics, and optionally group those metrics by one or more dimensions (columns). When picking your metrics you can choose from basic functions like `sum`, `average`, and `count`; or you can pick a common metric defined by an admin; or you can create a [custom expression](./expressions.md) by writing a formula. Common metrics include: - **Count of rows:** the total of number of rows in the table, after any filters have been applied. If you're looking at your `Orders` table and want to know how many orders were placed with a price greater than \$40, you’d filter by “Price greater than 40,” and then select `Count of rows`, because you want Metabase to count how many orders matched your filter. - **Sum of …:** the sum of all the values in a specific column. - **Average of …:** the average of all the values in a single column. - **Number of distinct values of…:** the number of unique values in all the cells of a single column. This is useful when trying to find out things like how many different _types_ of products were sold last month (not how many were sold in total). - **Cumulative sum of…:** This gives you a running total for a specific column. In order for this metric to be useful you'll need to group it by a date column to see it across time. - **Cumulative count of rows:** This gives you a running total of the number of rows in the table over time. Just like `Cumulative sum of…`, you'll need to group this by a date column in order for it to be useful. - **Standard deviation of …:** A number which expresses how much the values of a column vary, plus or minus, from the average value of that column. - **Minimum of …:** The minimum value present in the selected field. - **Maximum of …:** The maximum value present in the selected field. If you summarize and add a grouping you can then summarize _again_. You can also add steps to filter and/or join in between. For example, your first summarization step could be to get the count of orders per month, and you could then add a second summarization step to get the average monthly order total by selecting the `Average of…` your `count` column. ![Multiple summarize steps](../images/multiple-summarize-steps.png) You can also add metrics and groupings on the results page in a sidebar: the top of the sidebar where you pick the number ("metric") you want to see, and the part below is where you pick how to group that number (or how to "break it out"). If your admins have created any named metrics that are specific to your company or organization, they will be in this dropdown under the **Common Metrics** section. These might be things like your company’s official way of calculating revenue. ## Grouping your metrics Depending on the grouping column you select, Metabase will show you what it thinks is the best default visualization or chart for this summary. So if you select a date column, you'll see a line chart like this (you can click the green **Summarize** button to view the summarize sidebar). ![Grouping by a date column](../images/summarize-timeseries.png) When you click on a different grouping column than the one you currently have selected, the grouping will switch to use that column instead. But if you want to _add_ an additional grouping, just click the plus (+) icon on the right side of the column. To remove a grouping, click on the X icon. ![Multiple groupings](../images/summarize-timeseries-breakout.png) Some grouping columns will give you the option of choosing how big or small to make the groupings. So for example, if you've picked a Date column to group by, you can click on the words `by month` to change the grouping to day, week, hour, quarter, year, etc. If you're grouping by a numeric column, like age, Metabase will automatically "bin" the results, so you'll see your metric grouped in age brackets, like 0–10, 11–20, 21–30, etc. Just like with dates, you can click on the current binning option to change it to a specific number of bins. It's not currently possible to choose your own ranges for bins, though. ![Multiple groupings](../images/histogram-bins.png) Once you're done setting your metrics and groupings, click **Visualize** to see your results in all their glory. ## Visualizing your data If you want to jump ahead and learn about [how to change the visualization](../sharing/visualizing-results.md) of your results, by all means, feel free. ## Drill-through menu When viewing a chart, you can also click through questions to explore the data in greater detail. ![Drill-through menu](../images/drill-through-menu.png) The drill-through menu will present different options depending on what you click on. You can then optionally save any exploration as a new question. The drill-through menu is only available for questions built using the query builder. For more on how drill-through works, check out [Creating interactive charts](https://www.metabase.com/learn/questions/drill-through). ## Column heading drill-through When viewing a [table](../sharing/visualizations/table.md), clicking on the heading of a column gives you different options, depending on the columns data type. See [table](../sharing/visualizations/table.md#column-heading-options-for-filtering-and-summarizing). ## Returning to the editor To return to the editor for a question, click on the **Show editor** button in the upper right. ![Show editor](../images/show-editor.png) ## Viewing an individual record's details To see more info about a given record (a user account, order, venue, etc.), click on a record's ID number (or primary key). You can see all fields related to that one record and all connected tables that are hidden in the table view for the sake of readability. To page through the other records in the current table, press the right or left arrow keys, or click on the arrows to the right or left of the screen. ![Record details](../images/record-details.png) ## Custom expressions Custom expressions allow you to use spreadsheet-like functions and simple arithmetic within or between aggregation functions. ![Custom expression](../images/aggregation-expression.png) For example, you could do `Average(sqrt[FieldX]) + Sum([FieldY])` or `Max(floor([FieldX] - [FieldY]))`, where `FieldX` and `FieldY` are fields in the currently selected table. [Learn more about writing expressions](./expressions.md). ### Creating custom columns ![Custom column](../images/custom-column.png) Custom columns are helpful when you need to create a new column based on a calculation, such as subtracting the value of one column from another, or extracting a portion of an existing text column. Custom columns that you add aren't permanently added to your table; the columns will only be present in the given question. You can use the following math operators in your formulas: `+`, `–`, `*` (multiplication), and `/` (division), along with a whole host of spreadsheet-like functions. You can also use parentheses to clarify the order of operations. ## Adding or removing columns in a table When viewing tables, you can click on the **gear** icon in the bottom left to bring up the columns picker. Click **Add or remove columns** to search for and pick columns, including columns from related tables. ![Adding or removing columns](../images/column-selection.png) ## Sorting results ![Sorting](../images/sort-step.png) The sorting step lets you pick one or more columns to sort your results by. For each column you pick, you can also choose whether to sort ascending or descending; just click the arrow to change from ascending (up arrow) to descending (down arrow). ## Setting a row limit The row limit step lets you cap how many rows you want from the previous results. When used in conjunction with sorting, limits can let you do things like create a top-10 list, by first sorting by one of the columns in your result, then adding a row limit of 10. Unlike other steps, the row limit step can only be added at the end of your question. If you do want to add more steps to limited results, you can always save the limited results as a question, then start a _new_ question based on those results. ## Viewing the SQL that powers your question ![View the SQL](../images/view-the-sql.png) Under the hood, all Metabase questions are SQL (gasp!). To view the SQL that Metabase will run when you click **Visualize**, click the little **Console** icon in the top right of the query builder. Metabase will preview the SQL in a sidebar: ![SQL sidebar](../images/sql-sidebar.png) To view the SQL, you must have [query builder and native permissions](../../permissions/data.md). ### Convert query builder question to SQL You can also convert the question to a [native editor question](../native-editor/writing-sql.md). From the query builder screen: 1. Click the **Console** icon in the upper right of the query builder. 2. Click **Convert the question to SQL** option in the bottom right below the SQL code. Conversion is a one-way street: you can't convert a SQL question back into a query builder question. ## Caching question results See [Caching question results](../../configuring-metabase/caching.md#question-caching-policy). ## Play around with saved questions Each time you start modifying a saved question, Metabase will create a new question for you. The query builder will display the name of your starting question under **Data**. ![Starting from a saved question](../images/started-from-saved-question.png) Feel free to play around with any saved question, as you won't have any effect on the existing question. When you hit **Save** on the question, you can choose either to save as a new question (the default), or you can overwrite the existing question you started from. If you find yourself using the same saved question as a starting point for multiple questions, you may want to turn it into a [model](../../data-modeling/models.md) to let others know it's a good starting place. ## Question version history For questions, [dashboards](../../dashboards/start.md), and [models](../../data-modeling/models.md), Metabase keeps a version history for the previous fifteen versions of that item. See [History](../../exploration-and-organization/history.md). ## Further reading - [Visualize results](../sharing/visualizing-results.md). - [Sharing answers](../sharing/answers.md). - [Asking questions](https://www.metabase.com/learn/questions)
<template> <div class="msr-static-select" ref="dropdown"> <div class="msr-static-select__component" @click="_show = !_show"> <static-input v-model="_display" :label="label" @keydown="_handleKeys"> <template #trailing="{ width, height, colour }"> <svg class="msr-static-select__icon" :width="width" :height="height" :fill="colour" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg" :show="_show"> <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd"></path> </svg> </template> </static-input> </div> <ul class="msr-static-select__list msr-dropdown-list__list" :show="_show"> <slot v-for="(item, i) in items" :name="item.value" :key="item.value" :item="item" :click="() => _update(item)"> <dropdown-list-item :item="item" :colour="colour" :selected="_index == i" @click="() => _update(item)"> </dropdown-list-item> </slot> </ul> </div> </template> <script lang="ts"> import { defineComponent, type PropType } from "vue"; import DropdownListItem from "../DropdownListItem/DropdownListItem.vue"; import StaticInput from "../StaticInput/StaticInput.vue"; import { type DropdownItem, Colours, Theme, InjectedKeys } from "../../types"; export default defineComponent({ name: "StaticSelect", inject: { theme: { from: InjectedKeys.theme } }, props: { label: { type: String, required: true, }, items: { type: Array as PropType<DropdownItem[]>, required: true }, colour: { type: String as PropType<Colours | string>, default: () => Colours.primary, validator: (value: Colours | string) => Object.keys(Colours).includes(value) || new RegExp("^#([A-Fa-f0-9]{6})$").test(value) }, modelValue: { type: [String, Array], }, }, emits: { change(value: string) { return typeof value == "string"; }, "update:modelValue": (value: string | string[]) => { return true } }, components: { DropdownListItem, StaticInput }, data() { return { _show: false, _index: 0, display: "", }; }, computed: { backgroundColour() { return (this as any)['theme'] == Theme.dark ? "var(--dark-background)" : "var(--light-background)"; }, _display: { get() { return this.items.find(item => item.value == this.modelValue)?.label ?? this.display; }, set(value: string) { this.display = value; } }, value: { get() { return this.modelValue; }, set(value: string | string[]) { this.$emit("update:modelValue", value); } } }, methods: { _update(item: DropdownItem) { this.$emit("change", item.value); this.value = item.value; this.display = item.label; this._show = false; }, _handleKeys(e: KeyboardEvent) { if (e.key == "Tab" || e.key == "Escape") { return this._show = false; } e.preventDefault(); if (e.key == "ArrowDown" && (this._index < this.items.length - 1)) { this._index++; } else if (e.key == "ArrowUp" && this._index > 0) { this._index--; } else if (e.key == "Enter") { if (this._show) { return this._update(this.items[this._index]); } this._show = true; } } }, mounted() { let dropdown = this.$refs.dropdown as HTMLElement; addEventListener("click", (e) => { if (this._show) { if (e.target == dropdown || e.composedPath().includes(dropdown)) { return; } this._show = false; } }); this.value = this.modelValue; }, }); </script> <style scoped> .msr-static-select { position: relative; } .msr-static-select .msr-static-select__component :deep(.msr-static-input input) { cursor: pointer; caret-color: transparent; } .msr-static-select__component:hover, .msr-static-select .msr-static-select__component :deep(.msr-static-input) { cursor: pointer; } .msr-static-select .msr-static-select__component :deep(.msr-static-input label) { pointer-events: none; cursor: pointer; } .msr-static-select .msr-static-select__list { margin-top: -13px; width: 100%; position: absolute; direction: ltr; white-space: nowrap; background-color: v-bind(backgroundColour); border-radius: 8px; box-shadow: 0px 2px 13px rgba(125, 125, 125, 0.21); transform-origin: left top; z-index: 999; transition: all ease-out 100ms; } .msr-static-select .msr-static-select__list[show="false"] { transform: scaleY(0); } .msr-static-select .msr-static-select__list[show="true"] { transform: scaleY(1); } .msr-static-select .msr-static-select__icon { transition: all ease-out 100ms; } .msr-static-select .msr-static-select__icon[show="true"] { transform: rotate(180deg); } </style>
--- title: "\"Step-by-Step Guide to Mobile Snapchat Screen Recording\"" date: 2024-05-23T01:08:46.905Z updated: 2024-05-24T01:08:46.905Z tags: - ai video - ai snapchat - ai snapchat video categories: - ai - snapchat description: "\"This Article Describes Step-by-Step Guide to Mobile Snapchat Screen Recording\"" excerpt: "\"This Article Describes Step-by-Step Guide to Mobile Snapchat Screen Recording\"" keywords: "Snapchat Screen Save,Mobile Recording Tips,Quick Screen Capture,Android/iOS Screen Record,Video Screen Snipping,Social Media Screenshot,Easy Snapchat Screening" thumbnail: https://www.lifewire.com/thmb/HnP_1UAVv4sYwDdp2cN6nOYksIU=/400x300/filters:no_upscale():max_bytes(150000):strip_icc()/streaminghowimetyourmother-3db8d50886d04952986f232c3b96a9db.jpg --- ## Step-by-Step Guide to Mobile Snapchat Screen Recording Snapchat has 306 million users daily worldwide. It is considered the fastest way to share a moment and make a memory out of it. The article reflects upon screen record Snapchat and covers ways to do so via Android and iPhone devices. Let us commence this, shall we? #### In this article 01 [Will Snapchat Know When You Do Screen Recording?](#part1) 02 [How to Screen Record Snapchat on Android Phone?](#part2) 03 [How to Screen Record Snapchat on iPhone?](#part3) 04 [How to Make Screen Record on Snapchat without Notice?](#part4) ## Part 1: Will Snapchat Know When You Do Screen Recording? Snapchat was designed in a way that it protects the privacy of the users. According to this social networking software policy, the messages and snaps disappear after 24 hours. It creates an urge to screenshot the snap or screen record the chat without getting noticed. The section reflects the answer to the concern if you screen record on Snapchat, does it show?” The answer is yes. Snapchat sends a notification to the other person if you screen record on Snapchat. It plays a vital role as it helps steer clear from the stalkers and people who have no sense of boundaries. For taking a screenshot on Snapchat, the following notification show with specific colored arrows. The red arrow displays that the screenshot was taken of snap without audio. The purple arrow signifies that the screenshot was taken of snap with audio. The blue arrows represent that a screenshot has been taken of chat. ![screenshot icons on snapchat](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-1.jpg) It clearly shows that Snapchat takes the privacy of its users seriously. Therefore, to protect oneself from disappointment, it is crucial to avoid taking screenshots or screen recordings on Snapchat. You can use another phone to carry out the sneaky operation or download third-party software to screen capture and record safely. ## Part 2: How to Screen Record Snapchat on Android Phone? The Android users pretty much enhanced in the last decade exponentially. It is mainly because the workability of Android is more straightforward than that of iPhone. If you are a Snapchat addict on an Android phone, this section is designed for you. Screen recording on Snapchat via Android phone is easy. There are no complications in the process, even for a beginner. For starters, make sure that the in-built [screen recording functionality of Android](https://tools.techidaily.com/wondershare/filmora/download/) is enabled via Settings. It will help initiate the recording immediately from the Action Center. So, let us jump right into the step-by-step procedure to screen record on Snapchat. ### Step 1: Enabling the Airplane Mode Open Snapchat from your Android phone. Refresh all the chats so that all new snaps can be accessed easily. After that, launch the “Action Center” and hit “Airplane Mode” to switch it on. It is shaped like an airplane. ![turn on airplane mode](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-2.jpg) ### Step 2: Start the Recording Now, start screen recording by opening the “Action Center” again and clicking on “Screen Recorder.” As soon as the recording initiates, open the snap that you wish to record. ![begin android snapchat recording](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-3.jpg) ### Step 3: Stop the Recording After you are done, stop the recording. Disable the Airplane Mode and close the tool. The screen recording can be accessed from the Gallery. ## Part 3: How to Screen Record Snapchat on iPhone? Bringing more features and traits to the house, people have gone insane with every new model of the iPhone that is announced to the world. If you are an [iPhone user looking to screen record](https://tools.techidaily.com/wondershare/filmora/download/) on Snapchat, follow this section vividly. Instead of using third-party software like AZ screen recorder Snapchat, the in-built tool of the iPhone is equally workable. There is no need to install new software on the device and play with the system’s memory. To initiate screen recording on Snapchat via iPhone, let us discuss the procedure extensively. ### Step 1: Activating the Screen Recorder Before starting, the user should make sure that the in-built screen recorder tool has been downloaded. Navigate to the “Control Center” and scroll down to find “Screen Recorder if it is not installed.” Hit the green (+) icon beside the tool to make it easily accessible. ![add screen recording to control center](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-4.jpg) ### Step 2: Accessing the Feature for iPhone Versions The accessing of Screen Recorder in-built tool varies from one iPhone version to another. For instance, if you have iPhone 8 or older versions, swipe down to tap the “Screen Recording” icon. However, if you own iPhone X or advanced versions, swipe up from the top right corner of the screen. Find the relevant icon to continue with the targeted process. ![find recording icon on your iphone](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-5.jpg) ### Step 3: Starting the Recording Launch Snapchat from your iPhone and refresh the feed. Now, open the Screen Recording tool and initiate the recording. You have to turn on the “Airplane” mode as well before recording the snap. Now, the user is expected to open the snap that needs to be recorded. ![launch snapchat on iphone](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-6.jpg) ### Step 4: Stopping the Recording Stop the recording by clicking on the red icon on the screen. The screen recording is performed successfully. You can find the recording in your Photos in seconds. ![stop the screen recording](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-7.jpg) ## Part 4: How to Make Screen Record on Snapchat without Notice? It looks pretty embarrassing if you capture a screenshot and the other person receives a notification. The screen recording on Snapchat makes you awkward. To get rid of this embarrassment, one should use tricky and workable methods. Luckily, the section covers some of those methods. Let us have a look at each of them! ### Switching off the Internet Connection The first method revolves around disabling the internet connection of your device. For starters, reload and refresh your Snapchat feed. Disconnect the Wi-Fi or data network, and then screen records the snap. It helps you get the task done without getting noticed, as the app doesn’t know what is happening without internet connectivity. ### Enabling the Airplane Mode One workable method is to enable the Airplane Mode before you plan to screen record Snapchat. What happens is that the app doesn’t respond to the operation occurring as Airplane Mode is switched on. The process doesn’t send the notification to the targeted person; thus, it always works. ### Using a Third-Party Software You can access the [third-party screen recorder](https://tools.techidaily.com/wondershare/filmora/download/) and then perform screen recording on Snapchat. The market offers numerous apps for a similar reason. Their usage is simple as well. ### Mirroring Phone on PC Another tricky method revolves around mirroring phones on PC. The Snapchat user can connect the device to the computer and then play the snap story. As Snapchat cannot read the computer’s activities, you can use the recorder to screen record Snapchat stories in seconds. ### Using Another Phone You can pick a phone of your sibling or a friend to record the snaps of the targeted person. It might not be a high-resolution output, but it would surely get your task done without getting noticed. ## Final Remarks Snapchat has become one of the most favorite software in the world. People like to capture the stories and [screen record](https://tools.techidaily.com/wondershare/filmora/download/) the chats that they find amusing, engaging, and other sneaky reasons. The article offered users a screen record on Snapchat via Android and iPhone. The tricky methods to screen record without getting noticed were also a part of this write-up. 02 [How to Screen Record Snapchat on Android Phone?](#part2) 03 [How to Screen Record Snapchat on iPhone?](#part3) 04 [How to Make Screen Record on Snapchat without Notice?](#part4) ## Part 1: Will Snapchat Know When You Do Screen Recording? Snapchat was designed in a way that it protects the privacy of the users. According to this social networking software policy, the messages and snaps disappear after 24 hours. It creates an urge to screenshot the snap or screen record the chat without getting noticed. The section reflects the answer to the concern if you screen record on Snapchat, does it show?” The answer is yes. Snapchat sends a notification to the other person if you screen record on Snapchat. It plays a vital role as it helps steer clear from the stalkers and people who have no sense of boundaries. For taking a screenshot on Snapchat, the following notification show with specific colored arrows. The red arrow displays that the screenshot was taken of snap without audio. The purple arrow signifies that the screenshot was taken of snap with audio. The blue arrows represent that a screenshot has been taken of chat. ![screenshot icons on snapchat](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-1.jpg) It clearly shows that Snapchat takes the privacy of its users seriously. Therefore, to protect oneself from disappointment, it is crucial to avoid taking screenshots or screen recordings on Snapchat. You can use another phone to carry out the sneaky operation or download third-party software to screen capture and record safely. ## Part 2: How to Screen Record Snapchat on Android Phone? The Android users pretty much enhanced in the last decade exponentially. It is mainly because the workability of Android is more straightforward than that of iPhone. If you are a Snapchat addict on an Android phone, this section is designed for you. Screen recording on Snapchat via Android phone is easy. There are no complications in the process, even for a beginner. For starters, make sure that the in-built [screen recording functionality of Android](https://tools.techidaily.com/wondershare/filmora/download/) is enabled via Settings. It will help initiate the recording immediately from the Action Center. So, let us jump right into the step-by-step procedure to screen record on Snapchat. ### Step 1: Enabling the Airplane Mode Open Snapchat from your Android phone. Refresh all the chats so that all new snaps can be accessed easily. After that, launch the “Action Center” and hit “Airplane Mode” to switch it on. It is shaped like an airplane. ![turn on airplane mode](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-2.jpg) ### Step 2: Start the Recording Now, start screen recording by opening the “Action Center” again and clicking on “Screen Recorder.” As soon as the recording initiates, open the snap that you wish to record. ![begin android snapchat recording](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-3.jpg) ### Step 3: Stop the Recording After you are done, stop the recording. Disable the Airplane Mode and close the tool. The screen recording can be accessed from the Gallery. ## Part 3: How to Screen Record Snapchat on iPhone? Bringing more features and traits to the house, people have gone insane with every new model of the iPhone that is announced to the world. If you are an [iPhone user looking to screen record](https://tools.techidaily.com/wondershare/filmora/download/) on Snapchat, follow this section vividly. Instead of using third-party software like AZ screen recorder Snapchat, the in-built tool of the iPhone is equally workable. There is no need to install new software on the device and play with the system’s memory. To initiate screen recording on Snapchat via iPhone, let us discuss the procedure extensively. ### Step 1: Activating the Screen Recorder Before starting, the user should make sure that the in-built screen recorder tool has been downloaded. Navigate to the “Control Center” and scroll down to find “Screen Recorder if it is not installed.” Hit the green (+) icon beside the tool to make it easily accessible. ![add screen recording to control center](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-4.jpg) ### Step 2: Accessing the Feature for iPhone Versions The accessing of Screen Recorder in-built tool varies from one iPhone version to another. For instance, if you have iPhone 8 or older versions, swipe down to tap the “Screen Recording” icon. However, if you own iPhone X or advanced versions, swipe up from the top right corner of the screen. Find the relevant icon to continue with the targeted process. ![find recording icon on your iphone](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-5.jpg) ### Step 3: Starting the Recording Launch Snapchat from your iPhone and refresh the feed. Now, open the Screen Recording tool and initiate the recording. You have to turn on the “Airplane” mode as well before recording the snap. Now, the user is expected to open the snap that needs to be recorded. ![launch snapchat on iphone](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-6.jpg) ### Step 4: Stopping the Recording Stop the recording by clicking on the red icon on the screen. The screen recording is performed successfully. You can find the recording in your Photos in seconds. ![stop the screen recording](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-7.jpg) ## Part 4: How to Make Screen Record on Snapchat without Notice? It looks pretty embarrassing if you capture a screenshot and the other person receives a notification. The screen recording on Snapchat makes you awkward. To get rid of this embarrassment, one should use tricky and workable methods. Luckily, the section covers some of those methods. Let us have a look at each of them! ### Switching off the Internet Connection The first method revolves around disabling the internet connection of your device. For starters, reload and refresh your Snapchat feed. Disconnect the Wi-Fi or data network, and then screen records the snap. It helps you get the task done without getting noticed, as the app doesn’t know what is happening without internet connectivity. ### Enabling the Airplane Mode One workable method is to enable the Airplane Mode before you plan to screen record Snapchat. What happens is that the app doesn’t respond to the operation occurring as Airplane Mode is switched on. The process doesn’t send the notification to the targeted person; thus, it always works. ### Using a Third-Party Software You can access the [third-party screen recorder](https://tools.techidaily.com/wondershare/filmora/download/) and then perform screen recording on Snapchat. The market offers numerous apps for a similar reason. Their usage is simple as well. ### Mirroring Phone on PC Another tricky method revolves around mirroring phones on PC. The Snapchat user can connect the device to the computer and then play the snap story. As Snapchat cannot read the computer’s activities, you can use the recorder to screen record Snapchat stories in seconds. ### Using Another Phone You can pick a phone of your sibling or a friend to record the snaps of the targeted person. It might not be a high-resolution output, but it would surely get your task done without getting noticed. ## Final Remarks Snapchat has become one of the most favorite software in the world. People like to capture the stories and [screen record](https://tools.techidaily.com/wondershare/filmora/download/) the chats that they find amusing, engaging, and other sneaky reasons. The article offered users a screen record on Snapchat via Android and iPhone. The tricky methods to screen record without getting noticed were also a part of this write-up. 02 [How to Screen Record Snapchat on Android Phone?](#part2) 03 [How to Screen Record Snapchat on iPhone?](#part3) 04 [How to Make Screen Record on Snapchat without Notice?](#part4) ## Part 1: Will Snapchat Know When You Do Screen Recording? Snapchat was designed in a way that it protects the privacy of the users. According to this social networking software policy, the messages and snaps disappear after 24 hours. It creates an urge to screenshot the snap or screen record the chat without getting noticed. The section reflects the answer to the concern if you screen record on Snapchat, does it show?” The answer is yes. Snapchat sends a notification to the other person if you screen record on Snapchat. It plays a vital role as it helps steer clear from the stalkers and people who have no sense of boundaries. For taking a screenshot on Snapchat, the following notification show with specific colored arrows. The red arrow displays that the screenshot was taken of snap without audio. The purple arrow signifies that the screenshot was taken of snap with audio. The blue arrows represent that a screenshot has been taken of chat. ![screenshot icons on snapchat](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-1.jpg) It clearly shows that Snapchat takes the privacy of its users seriously. Therefore, to protect oneself from disappointment, it is crucial to avoid taking screenshots or screen recordings on Snapchat. You can use another phone to carry out the sneaky operation or download third-party software to screen capture and record safely. ## Part 2: How to Screen Record Snapchat on Android Phone? The Android users pretty much enhanced in the last decade exponentially. It is mainly because the workability of Android is more straightforward than that of iPhone. If you are a Snapchat addict on an Android phone, this section is designed for you. Screen recording on Snapchat via Android phone is easy. There are no complications in the process, even for a beginner. For starters, make sure that the in-built [screen recording functionality of Android](https://tools.techidaily.com/wondershare/filmora/download/) is enabled via Settings. It will help initiate the recording immediately from the Action Center. So, let us jump right into the step-by-step procedure to screen record on Snapchat. ### Step 1: Enabling the Airplane Mode Open Snapchat from your Android phone. Refresh all the chats so that all new snaps can be accessed easily. After that, launch the “Action Center” and hit “Airplane Mode” to switch it on. It is shaped like an airplane. ![turn on airplane mode](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-2.jpg) ### Step 2: Start the Recording Now, start screen recording by opening the “Action Center” again and clicking on “Screen Recorder.” As soon as the recording initiates, open the snap that you wish to record. ![begin android snapchat recording](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-3.jpg) ### Step 3: Stop the Recording After you are done, stop the recording. Disable the Airplane Mode and close the tool. The screen recording can be accessed from the Gallery. ## Part 3: How to Screen Record Snapchat on iPhone? Bringing more features and traits to the house, people have gone insane with every new model of the iPhone that is announced to the world. If you are an [iPhone user looking to screen record](https://tools.techidaily.com/wondershare/filmora/download/) on Snapchat, follow this section vividly. Instead of using third-party software like AZ screen recorder Snapchat, the in-built tool of the iPhone is equally workable. There is no need to install new software on the device and play with the system’s memory. To initiate screen recording on Snapchat via iPhone, let us discuss the procedure extensively. ### Step 1: Activating the Screen Recorder Before starting, the user should make sure that the in-built screen recorder tool has been downloaded. Navigate to the “Control Center” and scroll down to find “Screen Recorder if it is not installed.” Hit the green (+) icon beside the tool to make it easily accessible. ![add screen recording to control center](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-4.jpg) ### Step 2: Accessing the Feature for iPhone Versions The accessing of Screen Recorder in-built tool varies from one iPhone version to another. For instance, if you have iPhone 8 or older versions, swipe down to tap the “Screen Recording” icon. However, if you own iPhone X or advanced versions, swipe up from the top right corner of the screen. Find the relevant icon to continue with the targeted process. ![find recording icon on your iphone](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-5.jpg) ### Step 3: Starting the Recording Launch Snapchat from your iPhone and refresh the feed. Now, open the Screen Recording tool and initiate the recording. You have to turn on the “Airplane” mode as well before recording the snap. Now, the user is expected to open the snap that needs to be recorded. ![launch snapchat on iphone](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-6.jpg) ### Step 4: Stopping the Recording Stop the recording by clicking on the red icon on the screen. The screen recording is performed successfully. You can find the recording in your Photos in seconds. ![stop the screen recording](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-7.jpg) ## Part 4: How to Make Screen Record on Snapchat without Notice? It looks pretty embarrassing if you capture a screenshot and the other person receives a notification. The screen recording on Snapchat makes you awkward. To get rid of this embarrassment, one should use tricky and workable methods. Luckily, the section covers some of those methods. Let us have a look at each of them! ### Switching off the Internet Connection The first method revolves around disabling the internet connection of your device. For starters, reload and refresh your Snapchat feed. Disconnect the Wi-Fi or data network, and then screen records the snap. It helps you get the task done without getting noticed, as the app doesn’t know what is happening without internet connectivity. ### Enabling the Airplane Mode One workable method is to enable the Airplane Mode before you plan to screen record Snapchat. What happens is that the app doesn’t respond to the operation occurring as Airplane Mode is switched on. The process doesn’t send the notification to the targeted person; thus, it always works. ### Using a Third-Party Software You can access the [third-party screen recorder](https://tools.techidaily.com/wondershare/filmora/download/) and then perform screen recording on Snapchat. The market offers numerous apps for a similar reason. Their usage is simple as well. ### Mirroring Phone on PC Another tricky method revolves around mirroring phones on PC. The Snapchat user can connect the device to the computer and then play the snap story. As Snapchat cannot read the computer’s activities, you can use the recorder to screen record Snapchat stories in seconds. ### Using Another Phone You can pick a phone of your sibling or a friend to record the snaps of the targeted person. It might not be a high-resolution output, but it would surely get your task done without getting noticed. ## Final Remarks Snapchat has become one of the most favorite software in the world. People like to capture the stories and [screen record](https://tools.techidaily.com/wondershare/filmora/download/) the chats that they find amusing, engaging, and other sneaky reasons. The article offered users a screen record on Snapchat via Android and iPhone. The tricky methods to screen record without getting noticed were also a part of this write-up. 02 [How to Screen Record Snapchat on Android Phone?](#part2) 03 [How to Screen Record Snapchat on iPhone?](#part3) 04 [How to Make Screen Record on Snapchat without Notice?](#part4) ## Part 1: Will Snapchat Know When You Do Screen Recording? Snapchat was designed in a way that it protects the privacy of the users. According to this social networking software policy, the messages and snaps disappear after 24 hours. It creates an urge to screenshot the snap or screen record the chat without getting noticed. The section reflects the answer to the concern if you screen record on Snapchat, does it show?” The answer is yes. Snapchat sends a notification to the other person if you screen record on Snapchat. It plays a vital role as it helps steer clear from the stalkers and people who have no sense of boundaries. For taking a screenshot on Snapchat, the following notification show with specific colored arrows. The red arrow displays that the screenshot was taken of snap without audio. The purple arrow signifies that the screenshot was taken of snap with audio. The blue arrows represent that a screenshot has been taken of chat. ![screenshot icons on snapchat](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-1.jpg) It clearly shows that Snapchat takes the privacy of its users seriously. Therefore, to protect oneself from disappointment, it is crucial to avoid taking screenshots or screen recordings on Snapchat. You can use another phone to carry out the sneaky operation or download third-party software to screen capture and record safely. ## Part 2: How to Screen Record Snapchat on Android Phone? The Android users pretty much enhanced in the last decade exponentially. It is mainly because the workability of Android is more straightforward than that of iPhone. If you are a Snapchat addict on an Android phone, this section is designed for you. Screen recording on Snapchat via Android phone is easy. There are no complications in the process, even for a beginner. For starters, make sure that the in-built [screen recording functionality of Android](https://tools.techidaily.com/wondershare/filmora/download/) is enabled via Settings. It will help initiate the recording immediately from the Action Center. So, let us jump right into the step-by-step procedure to screen record on Snapchat. ### Step 1: Enabling the Airplane Mode Open Snapchat from your Android phone. Refresh all the chats so that all new snaps can be accessed easily. After that, launch the “Action Center” and hit “Airplane Mode” to switch it on. It is shaped like an airplane. ![turn on airplane mode](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-2.jpg) ### Step 2: Start the Recording Now, start screen recording by opening the “Action Center” again and clicking on “Screen Recorder.” As soon as the recording initiates, open the snap that you wish to record. ![begin android snapchat recording](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-3.jpg) ### Step 3: Stop the Recording After you are done, stop the recording. Disable the Airplane Mode and close the tool. The screen recording can be accessed from the Gallery. ## Part 3: How to Screen Record Snapchat on iPhone? Bringing more features and traits to the house, people have gone insane with every new model of the iPhone that is announced to the world. If you are an [iPhone user looking to screen record](https://tools.techidaily.com/wondershare/filmora/download/) on Snapchat, follow this section vividly. Instead of using third-party software like AZ screen recorder Snapchat, the in-built tool of the iPhone is equally workable. There is no need to install new software on the device and play with the system’s memory. To initiate screen recording on Snapchat via iPhone, let us discuss the procedure extensively. ### Step 1: Activating the Screen Recorder Before starting, the user should make sure that the in-built screen recorder tool has been downloaded. Navigate to the “Control Center” and scroll down to find “Screen Recorder if it is not installed.” Hit the green (+) icon beside the tool to make it easily accessible. ![add screen recording to control center](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-4.jpg) ### Step 2: Accessing the Feature for iPhone Versions The accessing of Screen Recorder in-built tool varies from one iPhone version to another. For instance, if you have iPhone 8 or older versions, swipe down to tap the “Screen Recording” icon. However, if you own iPhone X or advanced versions, swipe up from the top right corner of the screen. Find the relevant icon to continue with the targeted process. ![find recording icon on your iphone](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-5.jpg) ### Step 3: Starting the Recording Launch Snapchat from your iPhone and refresh the feed. Now, open the Screen Recording tool and initiate the recording. You have to turn on the “Airplane” mode as well before recording the snap. Now, the user is expected to open the snap that needs to be recorded. ![launch snapchat on iphone](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-6.jpg) ### Step 4: Stopping the Recording Stop the recording by clicking on the red icon on the screen. The screen recording is performed successfully. You can find the recording in your Photos in seconds. ![stop the screen recording](https://images.wondershare.com/filmora/article-images/2021/screen-record-snapchat-7.jpg) ## Part 4: How to Make Screen Record on Snapchat without Notice? It looks pretty embarrassing if you capture a screenshot and the other person receives a notification. The screen recording on Snapchat makes you awkward. To get rid of this embarrassment, one should use tricky and workable methods. Luckily, the section covers some of those methods. Let us have a look at each of them! ### Switching off the Internet Connection The first method revolves around disabling the internet connection of your device. For starters, reload and refresh your Snapchat feed. Disconnect the Wi-Fi or data network, and then screen records the snap. It helps you get the task done without getting noticed, as the app doesn’t know what is happening without internet connectivity. ### Enabling the Airplane Mode One workable method is to enable the Airplane Mode before you plan to screen record Snapchat. What happens is that the app doesn’t respond to the operation occurring as Airplane Mode is switched on. The process doesn’t send the notification to the targeted person; thus, it always works. ### Using a Third-Party Software You can access the [third-party screen recorder](https://tools.techidaily.com/wondershare/filmora/download/) and then perform screen recording on Snapchat. The market offers numerous apps for a similar reason. Their usage is simple as well. ### Mirroring Phone on PC Another tricky method revolves around mirroring phones on PC. The Snapchat user can connect the device to the computer and then play the snap story. As Snapchat cannot read the computer’s activities, you can use the recorder to screen record Snapchat stories in seconds. ### Using Another Phone You can pick a phone of your sibling or a friend to record the snaps of the targeted person. It might not be a high-resolution output, but it would surely get your task done without getting noticed. ## Final Remarks Snapchat has become one of the most favorite software in the world. People like to capture the stories and [screen record](https://tools.techidaily.com/wondershare/filmora/download/) the chats that they find amusing, engaging, and other sneaky reasons. The article offered users a screen record on Snapchat via Android and iPhone. The tricky methods to screen record without getting noticed were also a part of this write-up. <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7571918770474297" data-ad-slot="8358498916" data-ad-format="auto" data-full-width-responsive="true"></ins> <span class="atpl-alsoreadstyle">Also read:</span> <div><ul> <li><a href="https://tiktok-video-files.techidaily.com/in-2024-circumventing-tiktoks-obscured-blockades/"><u>In 2024, Circumventing TikTok's Obscured Blockades</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/2024-approved-boost-your-viewing-efficiency-the-ultimate-tiktok-fast-forward-method/"><u>2024 Approved Boost Your Viewing Efficiency The Ultimate TikTok Fast Forward Method</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/unlocking-opportunities-tiktoks-role-in-business-development-for-2024/"><u>Unlocking Opportunities TikTok's Role in Business Development for 2024</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/updated-in-2024-thriving-through-themes-30plus-unique-biographical-techniques-to-triple-your-views-and-following-on-the-tiktok-filmora-platform/"><u>[Updated] In 2024, Thriving Through Themes 30+ Unique Biographical Techniques to Triple Your Views and Following on the TikTok-Filmora Platform</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/new-in-2024-crafting-memorable-tiktok-pfps-that-differentiate-you/"><u>[New] In 2024, Crafting Memorable TikTok PFPs that Differentiate You</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/updated-ethical-buying-of-tiktok-clout-increase/"><u>[Updated] Ethical Buying of TikTok Clout Increase</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/new-giggles-galore-the-quintessential-comedic-stars-on-tiktok-for-2024/"><u>[New] Giggles Galore The Quintessential Comedic Stars on TikTok for 2024</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/updated-discover-the-secret-of-dynamic-tiktok-videos-with-voiceovers-for-2024/"><u>[Updated] Discover the Secret of Dynamic TikTok Videos with Voiceovers for 2024</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/updated-vocal-ensemble-in-the-digital-age-tiktok-edition-for-2024/"><u>[Updated] Vocal Ensemble in the Digital Age TikTok Edition for 2024</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/updated-in-2024-unlocking-top-6-free-tools-to-convert-tiktok-videos-into-mp3/"><u>[Updated] In 2024, Unlocking Top 6 Free Tools to Convert TikTok Videos Into MP3</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/updated-step-into-personal-branding-with-a-new-tiktok-look/"><u>[Updated] Step Into Personal Branding with a New TikTok Look</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/updated-gaming-galaxys-wackiest-titles-tiktok-edition/"><u>[Updated] Gaming Galaxy's Wackiest Titles - TikTok Edition</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/new-2024-approved-rhythm-revolution-tiktoks-newest-and-most-popular-rap-hits/"><u>[New] 2024 Approved Rhythm Revolution TikTok's Newest and Most Popular Rap Hits</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/the-art-of-sound-sculpting-minimizing-auditory-clutter/"><u>The Art of Sound Sculpting Minimizing Auditory Clutter</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/get-your-creative-flow-back-fixing-stalled-or-glitched-tiktok-app/"><u>Get Your Creative Flow Back Fixing Stalled or Glitched TikTok App</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/in-2024-budget-friendly-high-end-mac-tiktok-enhancements/"><u>In 2024, Budget-Friendly, High-End Mac TikTok Enhancements</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/updated-a-comprehensive-guide-for-enhancing-tiktok-voices-for-2024/"><u>[Updated] A Comprehensive Guide for Enhancing TikTok Voices for 2024</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/updated-structuring-a-significant-tiktok-close-up-for-2024/"><u>[Updated] Structuring a Significant TikTok Close-Up for 2024</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/new-techniques-for-effective-siri-voice-use-in-tiktok-for-2024/"><u>[New] Techniques for Effective Siri Voice Use in TikTok for 2024</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/optimize-your-tiktok-viewing-experience-for-2024/"><u>Optimize Your TikTok Viewing Experience for 2024</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/unveiling-this-years-fresh-tiktok-hits-for-2024/"><u>Unveiling This Year's Fresh TikTok Hits for 2024</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/updated-in-2024-unusual-upsets-top-10-unexpected-gaming-sensations-on-tiktok/"><u>[Updated] In 2024, Unusual Upsets Top 10 Unexpected Gaming Sensations on TikTok</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/updated-unveiling-the-essence-of-tiktok-movement-sound-and-humor/"><u>[Updated] Unveiling the Essence of TikTok Movement, Sound, and Humor</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/updated-in-2024-a-comprehensive-explanation-what-does-pfp-mean-on-tiktok/"><u>[Updated] In 2024, A Comprehensive Explanation What Does PFP Mean on TikTok?</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/updated-navigating-the-best-tiktok-to-gif-conversion-applications/"><u>[Updated] Navigating the Best TikTok to GIF Conversion Applications</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/new-the-ultimate-guide-to-enhancing-tiktok-video-themes-for-2024/"><u>[New] The Ultimate Guide to Enhancing TikTok Video Themes for 2024</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/download-tiktok-videos-without-watermark-on-iphone/"><u>Download TikTok Videos Without Watermark on iPhone</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/new-discover-the-secrets-of-tailoring-your-voice-on-tiktok-for-2024/"><u>[New] Discover the Secrets of Tailoring Your Voice on TikTok for 2024</u></a></li> <li><a href="https://android-transfer.techidaily.com/how-to-transfer-data-from-poco-c50-to-samsung-phone-drfone-by-drfone-transfer-from-android-transfer-from-android/"><u>How to Transfer Data from Poco C50 to Samsung Phone | Dr.fone</u></a></li> <li><a href="https://unlock-android.techidaily.com/forgotten-the-voicemail-password-of-honor-magic-6-lite-try-these-fixes-by-drfone-android/"><u>Forgotten The Voicemail Password Of Honor Magic 6 Lite? Try These Fixes</u></a></li> <li><a href="https://blog-min.techidaily.com/2-ways-to-transfer-text-messages-from-samsung-galaxy-f14-5g-to-iphone-1514131211x8-drfone-by-drfone-transfer-from-android-transfer-from-android/"><u>2 Ways to Transfer Text Messages from Samsung Galaxy F14 5G to iPhone 15/14/13/12/11/X/8/ | Dr.fone</u></a></li> <li><a href="https://remote-screen-capture.techidaily.com/precision-recording-of-skype-calls-via-obs-network/"><u>Precision Recording of Skype Calls via OBS Network</u></a></li> <li><a href="https://desktop-recording.techidaily.com/new-in-2024-how-to-record-screen-with-adobe-captive/"><u>[New] In 2024, How To Record Screen With Adobe Captive</u></a></li> <li><a href="https://techidaily.com/unlock-locked-iphone-6s-plus-by-restoring-it-to-factory-settings-by-drfone-ios-unlock-ios-unlock/"><u>Unlock locked iPhone 6s Plus by restoring it to factory settings</u></a></li> <li><a href="https://visual-screen-recording.techidaily.com/new-top-3-techniques-for-capturing-sports-spectacles-for-2024/"><u>[New] Top 3 Techniques for Capturing Sports Spectacles for 2024</u></a></li> <li><a href="https://ai-video-translation.techidaily.com/new-in-2024-top-7-online-auto-subtitle-translators-for-content-creators/"><u>New In 2024, Top 7 Online Auto Subtitle Translators for Content Creators</u></a></li> <li><a href="https://on-screen-recording.techidaily.com/updated-best-video-calls-uncompromising-security-and-ease-for-startups/"><u>[Updated] Best Video Calls Uncompromising Security & Ease for Startups</u></a></li> <li><a href="https://sim-unlock.techidaily.com/easily-unlock-your-realme-c55-device-sim-by-drfone-android/"><u>Easily Unlock Your Realme C55 Device SIM</u></a></li> <li><a href="https://blog-min.techidaily.com/how-to-recover-old-music-from-your-samsung-galaxy-s23-fe-by-fonelab-android-recover-music/"><u>How to recover old music from your Samsung Galaxy S23 FE</u></a></li> <li><a href="https://android-pokemon-go.techidaily.com/in-2024-pokemon-go-no-gps-signal-heres-every-possible-solution-on-oppo-a58-4g-drfone-by-drfone-virtual-android/"><u>In 2024, Pokemon Go No GPS Signal? Heres Every Possible Solution On Oppo A58 4G | Dr.fone</u></a></li> <li><a href="https://location-fake.techidaily.com/5-hassle-free-solutions-to-fake-location-on-find-my-friends-of-vivo-v30-drfone-by-drfone-virtual-android/"><u>5 Hassle-Free Solutions to Fake Location on Find My Friends Of Vivo V30 | Dr.fone</u></a></li> <li><a href="https://sim-unlock.techidaily.com/how-do-i-sim-unlock-my-apple-iphone-7-by-drfone-ios/"><u>How Do I SIM Unlock My Apple iPhone 7?</u></a></li> <li><a href="https://android-pokemon-go.techidaily.com/how-can-i-get-more-stardust-in-pokemon-go-on-nokia-c210-drfone-by-drfone-virtual-android/"><u>How can I get more stardust in pokemon go On Nokia C210? | Dr.fone</u></a></li> <li><a href="https://video-screen-grab.techidaily.com/updated-expert-blueprint-fashioning-timer-functionality-with-video-editors/"><u>[Updated] Expert Blueprint Fashioning Timer Functionality with Video Editors</u></a></li> <li><a href="https://screen-mirror.techidaily.com/in-2024-overview-of-the-best-infinix-smart-7-screen-mirroring-app-drfone-by-drfone-android/"><u>In 2024, Overview of the Best Infinix Smart 7 Screen Mirroring App | Dr.fone</u></a></li> <li><a href="https://bypass-frp.techidaily.com/hassle-free-ways-to-remove-frp-lock-from-google-phones-withwithout-a-pc-by-drfone-android/"><u>Hassle-Free Ways to Remove FRP Lock from Google Phones with/without a PC</u></a></li> <li><a href="https://howto.techidaily.com/android-screen-stuck-general-samsung-galaxy-m34-partly-screen-unresponsive-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>Android Screen Stuck General Samsung Galaxy M34 Partly Screen Unresponsive | Dr.fone</u></a></li> </ul></div>
import { Navigate, createBrowserRouter } from "react-router-dom"; import Main from "../layouts/Main"; import Home from "../pages/Home/Home/Home"; import Category from "../pages/Home/Category/Category"; import NewsLayout from "../layouts/NewsLayout"; import News from "../pages/News/News/News"; import LoginLayout from "../layouts/LoginLayout"; import Login from "../pages/Login/Login/Login"; import Register from "../pages/Login/Register/Register"; import PrivateRoute from "./PrivateRoute"; import Terms from "../pages/Shared/Terms/Terms"; const router = createBrowserRouter([ { path:'/', element:<LoginLayout/>, children:[ { path: '/', element: <Navigate to='/category/0'/>, }, { path: '/login', element: <Login/>, }, { path: '/register', element: <Register/>, }, { path: '/terms', element: <Terms/>, }, ] }, { path: "category", element: <Main />, children: [ // { // path: "/", // element: <Category />, // loader:()=>fetch('https://the-news-dragon-server-dsnnfl03f-imran-hossains-projects.vercel.app/news') // }, { path: ":id", element: <Category />, loader:({params})=>fetch(`https://the-news-dragon-server-dsnnfl03f-imran-hossains-projects.vercel.app/categories/${params.id}`) }, ], }, { path:'news', element: <NewsLayout />, children:[ { path:':id', element: <PrivateRoute><News/></PrivateRoute>, loader:({params})=>fetch(`https://the-news-dragon-server-dsnnfl03f-imran-hossains-projects.vercel.app/news/${params.id}`) } ] } ]); export default router;
use serde::Deserialize; #[derive(Clone, Debug, Deserialize)] pub struct Photo { pub id_str: String, pub url: String, pub expanded_url: String, pub indices: Option<[String; 2]>, pub media_url: String, pub media_url_https: String, pub display_url: String, } impl Photo { pub fn id(&self) -> u64 { self.id_str.parse().unwrap() } pub fn file_name(&self) -> String { let path = std::path::PathBuf::from(&self.media_url); let f = path.file_name().unwrap().to_string_lossy().to_string(); if !(f.ends_with(".jpg") || f.ends_with(".png")) { panic!("not an image"); } f } }
<?php session_start(); if (!isset($_SESSION['username'])) { header('Location: ./index.php'); } ?> <!-- Action to Display Existing Details --> <?php include('./config/db_connection.php'); if (isset($_GET['id'])){ $id_to_update = $_GET['id']; $sql = "SELECT * FROM heroes WHERE id = '$id_to_update'"; $result = mysqli_query($conn, $sql); $hero = mysqli_fetch_assoc($result); $heroName = $hero['hero_name']; $ultiSkill = $hero['ulti_skill']; $otherSkill = $hero['other_skill']; $passSkill = $hero['pass_skill']; $role = $hero['role']; $battleSpell = $hero['battle_spell']; $heroDescription = $hero['hero_description']; $heroImage = $hero['image']; $heroVideo = $hero['hero_video']; // print_r($hero); } ?> <!-- Action for Update/Edit --> <?php if (isset($_POST['update'])) { $id_hidden = $_POST['id_to_update']; $heroName = $_POST['hero_name']; $role = $_POST['role']; $ultiSkill = $_POST['ulti_skill']; $otherSkill = $_POST['other_skill']; $passSkill = $_POST['pass_skill']; $battleSpell = $_POST['battle_spell']; $heroDescription = $_POST['hero_description']; $heroVideo = $_POST['hero_video']; $heroImage = $_FILES['file']['name']; $heroTempname = $_FILES['file']['tmp_name']; move_uploaded_file($heroTempname, "uploads/" . $heroImage ); // Construct sql $sqel = "UPDATE heroes SET hero_name = '$heroName', role = '$role', ulti_skill = '$ultiSkill', other_skill = '$otherSkill', pass_skill = '$passSkill', battle_spell = '$battleSpell', hero_description = '$heroDescription', image = '$heroImage', hero_video = '$heroVideo' WHERE id = '$id_hidden'"; // Make Query and get Result $result = mysqli_query($conn, $sqel); if ($result) { // print_r($result); header('Location: hero.php'); } else{ echo 'There is an error: ' . mysqli_connect_error($conn); } } ?> <!DOCTYPE html> <html lang="en"> <!-- Header --> <?php include('./template/header.php'); ?> <div id="backtotop"></div> <!-- Form --> <div class="album py-5 bg-light"> <div class="container"> <form class="row g-3" action=" <?php echo $_SERVER['PHP_SELF'];?> " method="POST" enctype="multipart/form-data" > <div class="col-md-6"> <label for="inputEmail4" class="form-label">Hero Name:</label> <input type="text" class="form-control" id="inputEmail4" name="hero_name" value="<?php echo $heroName; ?>" required="required"> <input type="hidden" name="id_to_update" value="<?php echo $hero['id']; ?>"> </div> <div class="col-md-6"> <label for="inputState" class="form-label">Role:</label> <select id="inputState" class="form-select" name="role"> <option selected><?php echo $role; ?></option > <option>Marksman</option> <option>Mage</option> <option>Tank</option> <option>Fighter</option> <option>Assassin</option> <option>Support</option> </select> </div> <div class="col-12"> <label for="inputAddress" class="form-label">Ultimate Skill</label> <input type="text" class="form-control" id="inputAddress" placeholder="" name="ulti_skill" value="<?php echo $ultiSkill; ?>" required="required"> </div> <div class="col-12"> <label for="inputAddress2" class="form-label">Other Skills</label> <input type="text" class="form-control" id="inputAddress2" placeholder="" name="other_skill" value="<?php echo $otherSkill; ?>" required="required"> </div> <div class="col-md-5"> <label for="inputCity" class="form-label">Passive Skill</label> <input type="text" class="form-control" id="inputCity" name="pass_skill" value="<?php echo $passSkill; ?>" required="required"> </div> <div class="col-md-3"> <label for="inputState" class="form-label">Suggested Battle Spell</label> <select id="inputState" class="form-select" name="battle_spell" value="" > <option selected><?php echo $battleSpell; ?></option> <option>Execute</option> <option>Vangeance</option> <option>Aegis</option> <option>Retribution</option> <option>Inspire</option> <option>Sprint</option> <option>Healing Spell</option> <option>Petrify</option> <option>Purify</option> <option>Weaken</option> <option>Flicker</option> <option>Arrival</option> <option>Iron Wall</option> </select> </div> <div class="col-md-4"> <label for="inputGroupFile03">Add Image </label> <input type="file" id="inputGroupFile03" name="file" required="required"> </div> <div class="col-12"> <div class="input-group"> <span class="input-group-text">Hero Description</span> <textarea class="form-control" aria-label="With textarea" name="hero_description" required="required"><?php echo $heroDescription; ?></textarea> </div> </div> <div class="col-12"> <div class="input-group"> <span class="input-group-text">Hero Highlight Video</span> <textarea class="form-control" aria-label="With textarea" name="hero_video" placeholder="<iframe>. (optional) .</iframe>" ><?php echo $heroVideo; ?></textarea> </div> </div> <div class="col-12"> <button type="submit" class="btn btn-primary" name="update" >Update</button> <button type="reset" class="btn btn-primary" name="reset">Reset</button> <a href="./hero_details.php?id=<?php echo $hero['id']; ?>" class="btn btn-primary">Cancel</a> </div> </form> </div> </div> <!-- Footer --> <?php include('./template/footer.php'); ?> </html>
<!-- Default form register --> <div class="container"> <form (ngSubmit)="add()" [formGroup]="commandForm" class="text-center border border-light p-5"> <p class="h4 mb-4">Command | Adding</p> <div class="form-row mb-4"> <div class="col"> <!-- First name --> <input [ngClass]="{ 'is-invalid': submitted && commandForm.controls.firstName.errors }" class="form-control" formControlName="firstName" id="firstName" placeholder="First name" type="text"/> <div *ngIf="submitted && commandForm.controls.firstName.errors" class="text-danger"> <div *ngIf="commandForm.controls.firstName.errors.required">Firstname is required</div> <div *ngIf="commandForm.controls.firstName.errors.minlength">At least 2 characters</div> <div *ngIf="commandForm.controls.firstName.errors['onlyLetters']">Only letters</div> <div *ngIf="commandForm.controls.firstName.errors['noWhiteSpace']">White space is forbidden</div> </div> </div> <div class="col"> <!-- Last name --> <input [ngClass]="{ 'is-invalid': submitted && commandForm.controls.lastName.errors }" class="form-control" formControlName="lastName" id="lastName" placeholder="Last name" type="text"/> <div *ngIf="submitted && commandForm.controls.lastName.errors" class="text-danger"> <div *ngIf="commandForm.controls.lastName.errors.required">Lastname is required</div> <div *ngIf="commandForm.controls.lastName.errors.minlength">At least 2 characters</div> <div *ngIf="commandForm.controls.lastName.errors['onlyLetters']">Only letters</div> <div *ngIf="commandForm.controls.lastName.errors['noWhiteSpace']">White space is forbidden</div> </div> </div> </div> <!-- Login --> <div class="form-row mb-4"> <input [ngClass]="{ 'is-invalid': submitted && commandForm.controls.login.errors }" class="form-control" formControlName="login" id="login" placeholder="Login" type="text"/> <div *ngIf="submitted && commandForm.controls.login.errors" class="text-danger"> <div *ngIf="commandForm.controls.login.errors.required">Login is required</div> <div *ngIf="commandForm.controls.login.errors.minlength">At least 5 characters</div> <div *ngIf="commandForm.controls.login.errors.maxlength">No more than 10 characters</div> <div *ngIf="commandForm.controls.login.errors['onlyLetters']">Only letters</div> <div *ngIf="commandForm.controls.login.errors['noWhiteSpace']">White space is forbidden</div> </div> </div> <!-- Password --> <div class="form-row mb-4"> <input [ngClass]="{ 'is-invalid': submitted && commandForm.controls.password.errors }" class="form-control" formControlName="password" id="password" placeholder="Password" type="password"/> <div *ngIf="submitted && commandForm.controls.password.errors" class="text-danger"> <div *ngIf="commandForm.controls.password.errors.required">Password is required</div> </div> </div> <!-- Confirm Password --> <div class="form-row mb-4"> <input [ngClass]="{ 'is-invalid': submitted && commandForm.controls.confirmPassword.errors }" class="form-control" formControlName="confirmPassword" id="confirmPassword" placeholder="Confirm Password" type="password"/> <div *ngIf="submitted && commandForm.controls.confirmPassword.errors" class="text-danger"> <div *ngIf="commandForm.controls.confirmPassword.errors.required">Please confirm your password</div> <div *ngIf="commandForm.controls.confirmPassword.errors.mustMatch">Both password don't match</div> </div> </div> <!-- Email --> <div class="form-row mb-4"> <input [ngClass]="{ 'is-invalid': submitted && commandForm.controls.email.errors }" class="form-control" formControlName="email" id="email" placeholder="E-mail" type="email"/> <div *ngIf="submitted && commandForm.controls.email.errors" class="text-danger"> <div *ngIf="commandForm.controls.email.errors.required">E-mail is required</div> <div *ngIf="commandForm.controls.email.errors.email">Please provide a valid email address</div> </div> </div> <!-- Address --> <div class="form-row mb-4"> <input [ngClass]="{ 'is-invalid': submitted && commandForm.controls.address.errors }" class="form-control" formControlName="address" id="address" placeholder="Address" type="text"/> <div *ngIf="submitted && commandForm.controls.address.errors" class="text-danger"> <div *ngIf="commandForm.controls.address.errors.required">Address is required</div> </div> </div> <!-- Postal Code --> <div class="form-row mb-4"> <input [ngClass]="{ 'is-invalid': submitted && commandForm.controls.postalCode.errors }" class="form-control" formControlName="postalCode" id="postalCode" placeholder="Postal-Code" type="text"/> <div *ngIf="submitted && commandForm.controls.postalCode.errors" class="text-danger"> <div *ngIf="commandForm.controls.postalCode.errors.required || commandForm.controls.postalCode.errors['onlyDigit']">Postal Code is required | Only Digits</div> </div> </div> <!-- Street--> <div class="form-row mb-4"> <input [ngClass]="{ 'is-invalid': submitted && commandForm.controls.street.errors }" class="form-control" formControlName="street" id="street" placeholder="Street" type="text"/> <div *ngIf="submitted && commandForm.controls.street.errors" class="text-danger"> <div *ngIf="commandForm.controls.street.errors.required">Street name is required</div> <div *ngIf="commandForm.controls.street.errors['onlyLetters']">Only letters</div> </div> </div> <!-- Sign up button --> <button class="my-4" color="info" mdbBtn type="submit">Submit</button> </form> </div> <!-- Default form register -->
<!DOCTYPE html> <html> <head lang="ko"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>엘리먼트 find</title> <base href="https://www.w3schools.com/js/"> <style> #container { width: 400px; height: 400px; position: relative; /* 이동 기준을 위해 줌 */ background: yellow; } #animate { width: 50px; height: 50px; position: absolute; /*움직이기 위해 줌 */ background-color: red; } </style> </head> <body> <h3>Finding HTML Elements by Tag Name.</h3> <p>This example demonstrates the <b>getElementsByTagName</b> method.</p> <p id="demo1"></p> <script> const element = document.getElementsByTagName("p"); //getElementsByTagName으로 찾으면 복수개가 찾아지며 배녈형태로 리턴한다 //즉 element변수는 배열이다. document.getElementById("demo1").innerHTML = 'The text in first paragraph (index 0) is: ' + element[0].innerHTML; </script> <h3>Finding HTML Elements by Class Name.</h3> <p class="intro">Hello World!</p> <p class="intro">This example demonstrates the <b>getElementsByClassName</b> method.</p> <p id="demo2"></p> <script> const x = document.getElementsByClassName("intro"); //배열로 찾은 객체를 반환 document.getElementById("demo2").innerHTML = 'The first paragraph (index 0) with class="intro" is: ' + x[0].innerHTML; </script> <h3>Finding HTML Elements by Query Selector</h3> <p class="intro1">Hello World!.</p> <p class="intro1">This example demonstrates the <b>querySelectorAll</b> method.</p> <p id="demo3"></p> <script> const x1 = document.querySelectorAll("p.intro1"); //배열형태로 반환 document.getElementById("demo3").innerHTML = 'The first paragraph (index 0) with class="intro" is: ' + x1[0].innerHTML; </script> <h3>JavaScript HTML DOM attribute변경</h3> <img id="image" src="smiley.gif" width="160" height="120"> <script> document.getElementById("image").src = "landscape.jpg"; //html attribute는 js에서도 그대로 사용 </script> <h3>Changing the HTML style:</h3> <p id="p1">Hello World!</p> <p id="p2">Hello World!</p> <script> document.getElementById("p2").style.color = "blue"; document.getElementById("p2").style.fontFamily = "Arial"; document.getElementById("p2").style.fontSize = "larger"; </script> <h3>애니메이션</h3> <p><button onclick="myMove()">Click Me</button></p> <div id ="container"> <div id ="animate"></div> </div> <script> function myMove() { let id = null; const elem = document.getElementById("animate"); let pos = 0; id = setInterval(frame, 5); //5초간격으로 frame함수를 실행 function frame() { //함수내의 함수 if (pos == 350) { clearInterval(id); //setInterval을 중단 } else { pos++; elem.style.top = pos + "px"; elem.style.left = pos + "px"; } } } </script> </body> </html>
import 'package:conditional_builder_null_safety/conditional_builder_null_safety.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; import 'package:iconsax/iconsax.dart'; import 'package:route_it/core/utils/app_colors.dart'; import 'package:route_it/core/utils/app_router.dart'; import 'package:route_it/core/widgets/custom_button_item.dart'; import 'package:route_it/core/widgets/custom_loading_item.dart'; import 'package:route_it/core/widgets/custom_text_field_item.dart'; import 'package:route_it/core/widgets/custom_toast.dart'; import 'package:route_it/features/login/presentation/view_models/forget_password_cubit/forget_password_cubit.dart'; // ignore: must_be_immutable class ForgetPasswordView extends StatelessWidget { ForgetPasswordView({super.key}); var emailController = TextEditingController(); var formKey = GlobalKey<FormState>(); @override Widget build(BuildContext context) { var size = MediaQuery.of(context).size; return BlocConsumer<ForgetPasswordCubit, ForgetPasswordState>( listener: (context, state) { if (state is ForgetPasswordSuccess) { showToast(state.succesMessage, ToastState.SUCCESS); GoRouter.of(context) .pushReplacement(AppRouter.kResetPasswordCodeView); } else if (state is ForgetPasswordFailure) { showToast("${state.failureMessage}\ncomplete your Register", ToastState.ERROR); GoRouter.of(context).push(AppRouter.kRegisterView); } }, builder: (context, state) { return Container( decoration: const BoxDecoration( gradient: LinearGradient( begin: Alignment.topRight, end: Alignment.bottomLeft, colors: [ darkPrimaryColor, primaryColor, secondaryColor2, ])), child: Scaffold( backgroundColor: Colors.transparent, body: Padding( padding: const EdgeInsets.all(30.0), child: Form( key: formKey, child: Center( child: SingleChildScrollView( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( "Forget Password", style: TextStyle( color: Colors.white, fontSize: 45, fontWeight: FontWeight.w400), textAlign: TextAlign.center, ), SizedBox( height: size.height * .05, ), CustomTextFieldItem( controller: emailController, type: TextInputType.emailAddress, validator: (value) { if (value!.isEmpty) { // return 'Please Enter Your Email Address !'; return ''; } return null; }, hint: "EMAIL", prefix: Iconsax.message), SizedBox( height: size.height * .03, ), ConditionalBuilder( condition: state is! ForgetPasswordLoading, builder: (context) { return CustomButtonItem( textColor: textOnPrimaryColor, radius: 10, backgroundColor: darkPrimaryColor, width: double.infinity, height: size.height * 0.05, function: () { if (formKey.currentState!.validate()) { BlocProvider.of<ForgetPasswordCubit>( context) .forgetPassword( emailController.text, ); } }, text: "Next", ); }, fallback: (context) => const CustomLoadingItem(), ), ], ), ), ), ), )), ); }, ); } }
package com.example.kongwenyao.photoeditor; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.app.Fragment; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.SeekBar; import android.widget.TextView; import com.pes.androidmaterialcolorpickerdialog.ColorPicker; import com.pes.androidmaterialcolorpickerdialog.ColorPickerCallback; import org.w3c.dom.Text; /** * A simple {@link Fragment} subclass. */ public class SettingsFragment extends Fragment { private SeekBar strokeSeekBar; private Button strokeButton; private Button doneButton; OnColorChosenListener mCallBack; public SettingsFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_settings, container, false); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //View Assignment strokeButton = getActivity().findViewById(R.id.stroke_button); strokeSeekBar = getActivity().findViewById(R.id.seekbar); doneButton = getActivity().findViewById(R.id.done_button); //Set Event Listener doneButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { doneButtionHandler(); } }); strokeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { strokeButtonHandler(); } }); strokeSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { mCallBack.onSeekBarChange(progress); setLabelText(progress); } @Override public void onStartTrackingTouch(SeekBar seekBar) {} @Override public void onStopTrackingTouch(SeekBar seekBar) {} }); //Set Stroke Seekbar int strokeWidth = Math.round(MainActivityFragment.strokeWidth); strokeSeekBar.setProgress(strokeWidth); setLabelText(strokeWidth); } @Override public void onAttach(Context context) { super.onAttach(context); try { mCallBack = (OnColorChosenListener) getActivity(); } catch (ClassCastException e) { throw new ClassCastException(getActivity().toString() + " must implement OnSettingSelectedListener"); } } public void strokeButtonHandler() { final ColorPicker cp = new ColorPicker(getActivity(), MainActivityFragment.r, MainActivityFragment.g, MainActivityFragment.b, 73); cp.show(); cp.setCallback(new ColorPickerCallback() { @Override public void onColorChosen(int color) { mCallBack.onColorChosen(Color.red(color), Color.green(color), Color.blue(color)); cp.dismiss(); } }); } public void setLabelText(int progress) { TextView textView = getActivity().findViewById(R.id.seekbar_label); textView.setText("Stroke Width (" + String.valueOf(progress) + ")"); } public void doneButtionHandler() { Intent intent = new Intent(getActivity(), MainActivity.class); startActivity(intent); } public interface OnColorChosenListener { void onColorChosen(int red, int green, int blue); void onSeekBarChange(int width); } }
import { Injectable, InternalServerErrorException, NotFoundException, } from '@nestjs/common'; import { CreateStudentDto } from './dto/create-student.dto'; import { UpdateStudentDto } from './dto/update-student.dto'; import { InjectRepository } from '@nestjs/typeorm'; import { Student } from './entities/student.entity'; import { Repository } from 'typeorm'; import { StudentNotFoundException } from './exceptions/student-not-found.exception'; import { IPaginationOptions, paginate } from 'nestjs-typeorm-paginate'; import { StudentClass } from 'src/student-classes/entities/student-classes.entity'; import { Class } from 'src/classes/entities/class.entity'; @Injectable() export class StudentsService { constructor( @InjectRepository(Student) private repository: Repository<Student>, @InjectRepository(Class) private classRepository: Repository<Class>, @InjectRepository(StudentClass) private studentClassRepository: Repository<StudentClass>, ) {} async create(createStudentDto: CreateStudentDto) { const student = this.repository.create(createStudentDto); return await this.repository.save(student); } async findAll(options: IPaginationOptions) { const query = await this.repository .createQueryBuilder('students') .leftJoinAndSelect('students.class', 'class') .orderBy('students.id', 'ASC'); return await paginate(query, options); } async findOne(id: number) { try { return await this.repository.findOneByOrFail({ id: id }); } catch (error) { if (error.name === 'EntityNotFoundError') { throw new StudentNotFoundException(); } throw new InternalServerErrorException(); } } async update(id: number, updateStudentDto: UpdateStudentDto) { const response = await this.repository.update(id, updateStudentDto); if (response.affected === 0) { throw new StudentNotFoundException(); } return { message: 'Student updated successfully', success: true }; } async remove(id: number) { const response = await this.repository.delete({ id: id }); if (response.affected === 0) { throw new StudentNotFoundException(); } return { message: 'Student deleted successfully', success: true }; } async createStudentClass(createStudentClass: { studentId: number; classId: number; }) { try { await this.repository.findOneByOrFail({ id: createStudentClass.studentId, }); await this.classRepository.findOneByOrFail({ id: createStudentClass.classId, }); await this.studentClassRepository.save(createStudentClass); } catch (error) { if (error.name === 'EntityNotFoundError') { throw new NotFoundException(); } throw new InternalServerErrorException(); } } }
#include <iostream> #include <vector> #include <algorithm> std::vector<int> sortedSquares(std::vector<int>& nums) { int n = nums.size(); std::vector<int> result(n); int left = 0; int right = n - 1; int index = n - 1; while (left <= right) { int leftSquare = nums[left] * nums[left]; int rightSquare = nums[right] * nums[right]; if (leftSquare > rightSquare) { result[index] = leftSquare; left++; } else { result[index] = rightSquare; right--; } index--; } return result; } int main() { std::vector<int> nums = {-4, -1, 0, 3, 10}; std::vector<int> result = sortedSquares(nums); std::cout << "Output: ["; for (int i = 0; i < result.size(); ++i) { std::cout << result[i]; if (i < result.size() - 1) { std::cout << ", "; } } std::cout << "]" << std::endl; return 0; }
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="apple-touch-icon" sizes="180x180" href="{% static 'icon/apple-touch-icon.png' %}"> <link rel="icon" type="image/png" sizes="32x32" href="{% static 'icon/favicon-32x32.png' %}"> <link rel="icon" type="image/png" sizes="16x16" href="{% static 'icon/favicon-16x16.png' %}"> <link rel="manifest" href="{% static 'icon/site.webmanifest' %}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" integrity="sha512-wnea99uKIC3TJF7v4eKk4Y+lMz2Mklv18+r4na2Gn1abDRPPOeef95xTzdwGD9e6zXJBteMIhZ1+68QC5byJZw==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;700&display=swap"> <title>{% block title %}My Website{% endblock %} | Salla SEO Plugin</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" crossorigin="anonymous" referrerpolicy="no-referrer" /> <link rel="stylesheet" href="{% static 'css/iziToast.min.css' %}"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> {% if page.md %} <link rel="stylesheet" href="{% static 'css/md.css' %}"> {% endif %} </head> <body class="bg-gray-100 m-auto flex flex-col justify-between" style="min-height: 100vh"> <header class="bg-gray-900 py-4"> <div class="container mx-auto flex items-center justify-between"> <a href="/"> <img src="{% static 'images/logo.png' %}" alt="logo" class="h-16"> </a> {% if nav_pages %} <nav> <ul class="flex space-x-4"> <li><a href="/" class="text-gray-300 hover:text-white whitespace-nowrap">الرئيسية</a></li> {% for page in nav_pages %} <li><a href="{{ page.url }}" class="text-gray-300 hover:text-white whitespace-nowrap">{{ page.nav_name }}</a></li> {% endfor %} {% if is_authenticated %} <li><a href="{% url 'app:logout' %}" class="text-gray-300 hover:text-white whitespace-nowrap">تسجيل خروج</a></li> {% else %} <li><a href="#" onclick="openPopup(loginPopupId)" class="text-gray-300 hover:text-white whitespace-nowrap">تسجيل دخول</a></li> <li> <a href="{{ installation_url }}" id="salla-installation" class="bg-orange-500 hover:bg-orange-600 text-white font-bold py-2 px-4 rounded whitespace-nowrap" target="_blank"> التنصيب في سلة </a> </li> {% endif %} </ul> </nav> {% endif %} </div> </header> <main class="container mx-auto"> {% block content %}{% endblock %} </main> {% include 'popups.html' %} <div id="loading-page" class="h-screen flex justify-center items-center fixed inset-0 bg-gray-200"> <!-- Add a spinner icon with text --> <div class="text-center"> <i class="fas fa-spinner fa-pulse fa-3x text-gray-500"></i> <p class="text-gray-500 mt-4">Loading...</p> </div> </div> <footer class="bg-gray-900 py-4 mt-12"> <div class="container mx-auto text-center text-gray-300"> &copy; 2023 Salla SEO Plugin. All Rights Reserved. </div> </footer> <script src="{% static 'js/iziToast.min.js' %}" type="text/javascript"></script> <script src="{% static 'js/utils.js' %}"></script> <script src="{% static 'js/popup.js' %}"></script> <script src="{% static 'js/main.js' %}"></script> </body> </html>
class Solution: def maxProfit(self, prices: List[int], fee: int) -> int: if not prices: return 0 profit = 0 bought = prices[0] + fee # Initialize bought with the first price plus fee for price in prices[1:]: # Start iterating from the second price bought = min(bought, price + fee) if price > bought: # If the current price is higher than the bought price profit += price - bought # Add the profit to the total profit bought = price # Update the bought price return profit
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>User</title> </head> <body> <a th:href="@{/}">Home</a> <br/> <hr/> <br/> <p th:if="${res ne null and res.status == false}" style="color: red;" th:text="${res.message}"></p> <p th:if="${res ne null and res.status == true}" style="color: green;" th:text="${res.message}"></p> <form th:object="${us}" th:action="@{/user}" method="POST"> <fieldset> <input type="hidden" th:field="*{id}" /> <label>Name</label> <input type="text" th:field="*{username}" /><br/> <label>Email</label> <input type="email" th:field="*{email}" /><br/> <label>Password</label> <input type="text" th:field="*{password}" /><br/> <label>Active</label> <input type="checkbox" th:field="*{status}" /><br/> <br/> <button type="submit">Submit</button> <a th:href="@{/user}">Clear</a> </fieldset> </form> <br/> <hr/> <br/> <table border="1"> <thead> <tr> <th>Name</th> <th>Email</th> <th>Status</th> </tr> </thead> <tbody> <tr th:each="d : ${usList}"> <td><a th:href="@{/user/} + ${d.id}" th:text="${d.username}"></a></td> <td th:text="${d.email}"></td> <td th:text="${d.status == true ? 'Active' : 'Inactive'}"></td> </tr> </tbody> </table> </body> </html>
import styled from '@emotion/styled'; import getColorScheme, { ComponentColors } from '@src/utils/getColorScheme'; import { ComponentPatterns, getPatternScheme, } from '@src/utils/getPatternScheme'; import { rgba } from '@src/utils/rgba'; import { SHADE_4, WHITE } from '@src/constants/colors'; export const CarouselWrapper = styled.div<{ $color: ComponentColors; $pattern: ComponentPatterns; }>` position: relative; overflow: hidden; background-image: ${(props) => `url(${getPatternScheme(props.$pattern)})`}; background-color: ${({ $color, theme }) => getColorScheme($color, theme)}; width: 100%; `; export const CarouselNav = styled.div` position: absolute; bottom: 5%; left: 50%; transform: translateX(-50%); `; export const CarouselDot = styled.button<{ isActive: boolean }>` position: relative; width: 0.3em; aspect-ratio: 1; margin: 0 0.5rem; background: ${({ isActive }) => isActive ? rgba(WHITE, 0.7) : rgba(SHADE_4, 0.5)}; border: none; border-radius: 50%; cursor: pointer; &:focus { outline: none; } `; export const CarouselTrack = styled.div` display: flex; width: 100%; height: 100%; transition: transform 0.5s ease-in-out; `; export const CarouselItem = styled.div` width: 100%; flex-shrink: 0; & > * { display: flex; align-items: center; justify-content: center; } & img { max-width: 100%; height: auto; } `; export const CarouselButton = styled.button<{ $position: 'left' | 'right'; }>` position: absolute; top: 50%; ${(props) => props.$position}: 0; transform: translateY(-50%); border: none; border-radius: 50%; padding: 0.5rem; cursor: pointer; background: none; &:focus { outline: none; } `; export const CarouselButtonIcon = styled.img<{ $position: 'left' | 'right'; $color: ComponentColors; }>` width: 2rem; height: 2rem; transform: ${(props) => props.$position === 'left' ? 'rotate(180deg)' : 'none'}; transition: transform 0.2s ease-in-out; &:hover { transform: ${(props) => props.$position === 'left' ? 'rotate(180deg) scale(1.1)' : 'scale(1.1)'}; } &:active { transform: ${(props) => props.$position === 'left' ? 'rotate(180deg) scale(0.8)' : 'scale(0.8)'}; } background-color: ${(props) => rgba(getColorScheme(props.$color, props.theme), 0.5)}; border-radius: 50%; `;
# luke_garages This resource only supports ESX Legacy, other versions of the framework **will not** work without modifying the resource. Alongside cars, aircrafts and boats are also fully supported with them having their own separate garages and impounds. The impound has checks in place to prevent vehicle duping. I used esx_vehicleshop, but the resource should work with anything that follows that databse structure in `owned_vehicles` table. [Video Showcase](https://www.youtube.com/watch?v=GT2u5uoz7Tc) (From 2.0.0 version) ### Dependencies - [PolyZone](https://github.com/mkafrin/PolyZone) - [qtarget](https://github.com/overextended/qtarget) - [ox_lib](https://github.com/overextended/ox_lib) - Server game build 1868 or newer\* Make sure to download the release zip for [ox_lib](https://github.com/overextended/ox_lib/releases/latest) (ox_lib.zip). ### Installation - Download the resource from releases - Rename folder to luke_garages - Drop the luke_garages folder into your resources folder - Import the .sql file into your database - Start the resource in your server.cfg If you wish to add more garages or impounds make sure to follow the provided template and examples in the config.lua file. Custom vehicles are fully supported, for each custom vehicle you have to add a text entry of it's model and make name (if there isn't one already) into the vehicle_names.lua file which is located in the client folder. I provided an example of this that I used on the GTR in the video. For any issues or bugs that may occur please open an Issue in the repository. Make sure to describe the issue in detail and how to reproduce it. PRs are always welcome. ## Setting the game build \*_Setting the game build is required due to the use of GetMakeNameFromVehicleModel native which was introduced in the game version 1868. If (for whatever reason) you don't want to change from the base build that FiveM comes with, you can remove all the appearances of this native and it's variables from the client file. Otherwise your game will be consistently crashing when trying to open either the garage or the impound._ There are two way sto set your game build: 1. Setting the build in your server.cfg 2. Setting the build in your launch params Both methods work exactly the same, if you are setting your game build through launch params you will need to add a `+` in front of the command, otherwise you don't need to. The command you need to use is: `set sv_enforceGameBuild` (example: `set sv_enforceGameBuild 2189`) Depending on the game build number you choose is the GTA DLC your server is going to be running: ``` 1604 - Vanilla 2060 - Casino Heist 2189 - Cayo Perico Heist 2373 - Tuners update 2545 - The Contract update ``` ## License luke_garages Copyright (C) 2022 Luke <https://www.github.com/LukeWasTakenn> 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 <https://www.gnu.org/licenses/>.
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:quizz/providers/question_index_provider.dart'; import 'package:quizz/providers/score_counter_provider.dart'; import 'package:quizz/screen/quizz_screen.dart'; class MyHomePage extends StatefulWidget { const MyHomePage({super.key, required this.title}); final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( appBar: AppBar( backgroundColor: Colors.blue, title: const Text( 'Quizz', style: TextStyle( color: Colors.white, ), ), ), body: Center( child: Column( mainAxisSize: MainAxisSize.min, children: [ const Text( 'Start quiz!', style: TextStyle( fontSize: 30, fontWeight: FontWeight.w400, ), ), const SizedBox(height: 20), ElevatedButton( onPressed: () { Navigator.of(context).push(MaterialPageRoute( builder: (BuildContext context) => const QuestionPage())); context.read<ScoreCounterProvider>().clearScore(); context.read<QuestionIndexProvider>().initQuestionIndex(); }, style: const ButtonStyle( fixedSize: MaterialStatePropertyAll(Size.fromWidth(180)), elevation: MaterialStatePropertyAll(4), backgroundColor: MaterialStatePropertyAll(Colors.blue), foregroundColor: MaterialStatePropertyAll(Colors.white), overlayColor: MaterialStatePropertyAll(Colors.lightBlue), ), child: const Text('Start'), ), const SizedBox(height: 20), Text( 'Score : ${context.watch<ScoreCounterProvider>().score.toString()}', style: const TextStyle(fontSize: 15), ) ], ), ), ), ); } }
--- permalink: maintenance-e5700/hics-add-supertask-task.html sidebar: sidebar keywords: E5700 host interface card, E5700 HIC, replace E5700 HIC, failed E5700 HIC summary: Añada una HIC en E5700. --- = Añadir tarjeta de interfaz del host (HIC) E5700 :allow-uri-read: :experimental: :icons: font :imagesdir: ../media/ [role="lead"] Puede añadir una tarjeta de interfaz del host (HIC) a contenedores de la controladora E5700 con puertos de host de la placa base. Esta adición aumenta el número de puertos de host en la cabina de almacenamiento y proporciona protocolos de host adicionales. .Acerca de esta tarea Cuando añada HIC, debe apagar la cabina de almacenamiento, instalar la HIC y volver a aplicar la alimentación. .Antes de empezar * Revisar link:hics-overview-supertask-concept.html["Requisitos para reemplazar E5700 HIC"]. * Programar una ventana de mantenimiento de tiempo de inactividad para este procedimiento. La alimentación debe estar apagada al instalar HIC, por lo que no puede acceder a los datos de la cabina de almacenamiento hasta que haya completado correctamente este procedimiento. (En una configuración doble, ambas controladoras deben tener la misma configuración de HIC cuando se conectan). * Asegúrese de tener lo siguiente: + ** Una o dos HIC, según si hay una o dos controladoras en la cabina de almacenamiento. Las HIC deben ser compatibles con las controladoras. ** Nuevo hardware de host instalado para los puertos de host nuevos, como los switches o adaptadores de bus de host (HBA). ** Todos los cables, transceptores, switches y adaptadores de bus de host (HBA) necesarios para conectar los puertos de host nuevos. + Para obtener información acerca del hardware compatible, consulte https://mysupport.netapp.com/NOW/products/interoperability["Matriz de interoperabilidad de NetApp"^] y la http://hwu.netapp.com/home.aspx["Hardware Universe de NetApp"^]. ** Las etiquetas para identificar cada cable que está conectado al compartimento de controladoras. ** Una muñequera ESD, o usted ha tomado otras precauciones antiestáticas. ** Un destornillador Phillips número 1. ** Una estación de gestión con un explorador que puede acceder a System Manager de SANtricity para la controladora. (Para abrir la interfaz de System Manager, apunte el explorador al nombre de dominio o la dirección IP de la controladora.) == Paso 1: Preparar la adición de HIC Para preparar la adición de una HIC, realice un backup de la base de datos de configuración de la cabina de almacenamiento, recoja datos de soporte y detenga operaciones de I/o del host. Esto le permite apagar la bandeja de controladoras. .Pasos . En la página Inicio de SANtricity System Manager, asegúrese de que la cabina de almacenamiento tenga el estado Optimal. + Si el estado no es óptimo, use Recovery Guru o póngase en contacto con el soporte técnico para resolver el problema. No continúe con este procedimiento. . Realice un backup de la base de datos de configuración de la cabina de almacenamiento con SANtricity System Manager. + Si se produce un problema durante este procedimiento, puede utilizar el archivo guardado para restaurar la configuración. El sistema guardará el estado actual de la base de datos de configuración RAID, que incluye todos los datos de los grupos de volúmenes y pools de discos en la controladora. + ** De System Manager: + ... Seleccione menú:Soporte[Centro de soporte > Diagnóstico]. ... Seleccione *recopilar datos de configuración*. ... Haga clic en *recoger*. + El archivo se guarda en la carpeta de descargas del explorador con el nombre *configurationData-<arrayName>-<dateTime>.7z*. ** También puede hacer un backup de la base de datos de configuración con el siguiente comando CLI: + `save storageArray dbmDatabase sourceLocation=onboard contentType=all file="filename";` . Recoja datos de soporte para la cabina de almacenamiento mediante SANtricity System Manager. + Si se produce un problema durante este procedimiento, puede utilizar el archivo guardado para solucionar el problema. El sistema guardará los datos de inventario, Estados y rendimiento acerca de la cabina de almacenamiento en un único archivo. + .. Seleccione menú:Soporte[Centro de soporte > Diagnóstico]. .. Seleccione *recopilar datos de soporte*. .. Haga clic en *recoger*. + El archivo se guarda en la carpeta de descargas del explorador con el nombre *support-data.7z*. . Asegúrese de que no se producen operaciones de I/o entre la cabina de almacenamiento y todos los hosts conectados. Por ejemplo, puede realizar estos pasos: + ** Detenga todos los procesos que implican las LUN asignadas del almacenamiento a los hosts. ** Asegúrese de que no hay aplicaciones que escriban datos en ninguna LUN asignada del almacenamiento a los hosts. ** Desmonte todos los sistemas de archivos asociados con volúmenes en la cabina. + NOTE: Los pasos exactos para detener las operaciones de I/o del host dependen del sistema operativo del host y de la configuración, que están más allá del alcance de estas instrucciones. Si no está seguro de cómo detener las operaciones de I/o del host en el entorno, considere apagar el host. + CAUTION: *Posible pérdida de datos* -- Si continúa este procedimiento mientras se realizan operaciones de E/S, la aplicación host podría perder acceso a los datos porque no se puede acceder al almacenamiento. . Si la cabina de almacenamiento participa en una relación de mirroring, detenga todas las operaciones de I/o del host en la cabina de almacenamiento secundaria. . Espere a que se escriban en las unidades todos los datos de la memoria caché. + El LED verde de caché activa de la parte posterior de cada controladora está encendido cuando los datos en caché deben escribirse en las unidades. Debe esperar a que se apague este LED. + image::../media/e5700_ib_hic_w_cache_led_callouts_maint-e5700.gif[e5700 ib ha w cache de callouts maint e5700] + *(1)* _Cache Active LED_ . En la página Inicio del Administrador del sistema de SANtricity, seleccione *Ver operaciones en curso*. Espere a que se completen todas las operaciones antes de continuar con el siguiente paso. . Apague la bandeja de controladoras. + .. Apague ambos switches de alimentación de la bandeja de controladoras. .. Espere a que se apagen todos los LED de la bandeja de controladoras. == Paso 2: Quite el contenedor de la controladora Quite el contenedor de la controladora para poder añadir la nueva HIC. .Pasos . Etiquete cada cable conectado al compartimento de controladoras. . Desconecte todos los cables del compartimento de controladoras. + CAUTION: Para evitar un rendimiento degradado, no gire, pliegue, pellizque ni pellizque los cables. . Confirme que el LED Cache Active de la parte posterior de la controladora está apagado. + El LED verde de caché activa de la parte posterior de la controladora está encendido cuando los datos en caché deben escribirse en las unidades. Debe esperar a que este LED se apague antes de quitar el compartimento de controladoras. + image::../media/e5700_ib_hic_w_cache_led_callouts_maint-e5700.gif[e5700 ib ha w cache de callouts maint e5700] + *(1)* _Cache Active LED_ . Apriete el pestillo de la palanca de leva hasta que se suelte y, a continuación, abra la palanca de leva a la derecha para liberar el contenedor del controlador de la bandeja. + La siguiente figura muestra un ejemplo de una bandeja de controladoras E5724: + image::../media/28_dwg_e2824_remove_controller_canister_maint-e5700.gif[28 dwg e2824 retire la mant. del contenedor de la controladora e5700] + *(1)* _Controller canister_ + *(2)* _Cam handle_ + En la siguiente figura, se muestra un ejemplo de bandeja de controladoras E5760: + image::../media/28_dwg_e2860_add_controller_canister_maint-e5700.gif[28 dwg e2860 añada la mant del contenedor de controladora e5700] + *(1)* _Controller canister_ + *(2)* _Cam handle_ . Con dos manos y el asa de leva, deslice el recipiente del controlador para sacarlo del estante. + CAUTION: Utilice siempre dos manos para admitir el peso de un compartimento de controladoras. + Si va a retirar el compartimento de controladoras de una bandeja de controladoras E5724, una solapa se balancea hasta bloquearlo para ayudar a mantener el flujo de aire y la refrigeración. . Gire el contenedor del controlador de manera que la cubierta extraíble quede orientada hacia arriba. . Coloque el contenedor del controlador sobre una superficie plana y libre de estática. == Paso 3: Instale una HIC Instale la tarjeta de interfaz del host (HIC) para aumentar la cantidad de puertos de host en la cabina de almacenamiento. CAUTION: *Posible pérdida de acceso a los datos*: No instale nunca una HIC en un contenedor de controladora E5700 si esa HIC estaba diseñada para otra controladora E-Series. Además, si tiene una configuración doble, ambas controladoras y ambas HIC deben ser idénticas. La presencia de HIC incompatible o con discrepancias hará que las controladoras se bloqueen cuando aplique alimentación. .Pasos . Desembale la nueva HIC y la nueva placa frontal de HIC. . Pulse el botón de la cubierta del compartimento del controlador y deslice la cubierta hacia fuera. . Confirme que el LED verde dentro del controlador (por los DIMM) está apagado. + Si este LED verde está encendido, el controlador sigue utilizando la batería. Debe esperar a que este LED se apague antes de quitar los componentes. + image::../media/28_dwg_e2800_internal_cache_active_led_maint-e5700.gif[28 dwg e2800 caché interna activa led maint e5700] + *(1)* _Internal Cache Active_ + *(2)* _Battery_ . Con un destornillador Phillips del número 1, quite los cuatro tornillos que fijan la placa frontal vacía al compartimento de la controladora y quite la placa frontal. . Alinee los tres tornillos de ajuste manual de la HIC con los orificios correspondientes de la controladora y alinee el conector de la parte inferior de la HIC con el conector de la interfaz HIC de la tarjeta controladora. + Tenga cuidado de no arañar ni golpear los componentes en la parte inferior de la HIC o en la parte superior de la tarjeta de la controladora. . Baje con cuidado la HIC en su lugar y coloque el conector de la HIC presionando suavemente en la HIC. + CAUTION: *Posible daño en el equipo* -- tenga mucho cuidado de no pellizcar el conector de la cinta de oro para los LED del controlador entre la HIC y los tornillos de mariposa. + image::../media/28_dwg_e2800_hic_thumbscrews_maint-e5700.gif[28 dwg e2800 tornillos digitales hic. mint e5700] + *(1)* _Tarjeta de interfaz del host (HIC)_ + *(2)* _thumbtornillos_ . Apriete a mano los tornillos de mariposa HIC. + No utilice un destornillador, o puede apretar los tornillos en exceso. . Con un destornillador Phillips del número 1, conecte la nueva placa frontal de la HIC al compartimento de la controladora con los cuatro tornillos que quitó anteriormente. + image::../media/28_dwg_e2800_hic_faceplace_screws_maint-e5700.gif[28 dwg e2800 hic tornillos face2800 maint e5700] == Paso 4: Vuelva a instalar el compartimento de la controladora Vuelva a instalar el compartimento de controladoras en la bandeja de controladoras después de instalar la nueva HIC. .Pasos . Gire el contenedor del controlador de manera que la cubierta extraíble quede orientada hacia abajo. . Con el asa de leva en la posición abierta, deslice completamente el contenedor del controlador en la bandeja del controlador. + La siguiente figura muestra un ejemplo de una bandeja de controladoras E5724: + image::../media/28_dwg_e2824_remove_controller_canister_maint-e5700.gif[28 dwg e2824 retire la mant. del contenedor de la controladora e5700] + *(1)* _Controller canister_ + *(2)* _Cam handle_ + En la siguiente figura, se muestra un ejemplo de bandeja de controladoras E5760: + image::../media/28_dwg_e2860_add_controller_canister_maint-e5700.gif[28 dwg e2860 añada la mant del contenedor de controladora e5700] + *(1)* _Controller canister_ + *(2)* _Cam handle_ . Mueva la palanca de leva hacia la izquierda para bloquear el contenedor del controlador en su lugar. . Vuelva a conectar todos los cables que quitó. + CAUTION: No conecte los cables de datos a los puertos HIC nuevos en este momento. . (Opcional) Si va a añadir HIC a una configuración doble, repita todos los pasos para quitar el segundo compartimento de controladora, instale la segunda HIC y vuelva a instalar el segundo compartimento de controladora. == Paso 5: Adición de HIC completa Compruebe los LED de la controladora y la visualización de siete segmentos y confirme que el estado de la controladora es óptimo. .Pasos . Encienda los dos switches de alimentación que se encuentran en la parte posterior de la bandeja de controladoras. + ** No apague los interruptores de alimentación durante el proceso de encendido, que normalmente tarda 90 segundos o menos en completarse. ** Los ventiladores de cada bandeja son muy altos cuando se inician por primera vez. El ruido fuerte durante el arranque es normal. . Cuando se arranca la controladora, compruebe los LED de la controladora y la pantalla de siete segmentos. + ** La pantalla de siete segmentos muestra la secuencia de repetición *OS*, *SD*, *_blank_* para indicar que el controlador está realizando el procesamiento de comienzo del día (SOD). Una vez que se inició correctamente una controladora, su pantalla de siete segmentos debe mostrar el ID de soporte. ** El LED de atención ámbar del controlador se enciende y se apaga, a menos que se produzca un error. ** Los LED verde del enlace de host permanecen apagados hasta que se conectan los cables del host. + NOTE: La figura muestra un contenedor de controladora de ejemplo. La controladora puede tener un número diferente y otro tipo de puertos de host. + image::../media/e5700_hic_3_callouts_maint-e5700.gif[e5700 hic 3 callouts maint e5700] + *(1)* _Host Link LEDs_ + *(2)* _LED de atención (ámbar)_ + *(3)* _pantalla de siete segmentos_ . En SANtricity System Manager, confirme que el estado de la controladora es óptimo. + Si el estado no es óptimo o si alguno de los LED de atención está encendido, confirme que todos los cables están conectados correctamente y compruebe que la HIC y el compartimento de controladoras estén instalados correctamente. Si es necesario, quite y vuelva a instalar el compartimento de controladoras y la HIC. + NOTE: Si no puede resolver el problema, póngase en contacto con el soporte técnico. . Si los puertos HIC nuevos requieren transceptores SFP+, instale estos SFP. . Si se instaló una HIC con puertos SFP+ (ópticos), confirme que los nuevos puertos tienen el protocolo de host que espera. + .. En el Administrador del sistema de SANtricity, seleccione *hardware*. .. Si el gráfico muestra las unidades, haga clic en *Mostrar parte posterior de la bandeja*. .. Seleccione el gráfico de la controladora a o de la controladora B. .. Seleccione *Ver ajustes* en el menú contextual. .. Seleccione la ficha *interfaces de host*. .. Haga clic en *Mostrar más valores*. .. Revise los detalles mostrados para los puertos HIC (los puertos etiquetados *e0__x__* o *0__x__* en la ubicación de HIC *ranura 1*) para determinar si está listo para conectar los puertos host a los hosts de datos: + *** _Si los nuevos puertos HIC tienen el protocolo que espera_: + Está listo para conectar los nuevos puertos HIC a los hosts de datos; vaya al siguiente paso. *** _Si los nuevos puertos HIC *no* tienen el protocolo que espera_: + Debe aplicar un paquete de funciones de software para poder conectar los nuevos puertos HIC a los hosts de datos. Consulte link:hpp-change-host-protocol-task.html["Cambie el protocolo del host E5700"]. A continuación, conecte los puertos de host a los hosts de datos y reanude operaciones. . Conecte los cables entre los puertos de host de la controladora y los hosts de datos. + Si necesita instrucciones para configurar y utilizar un protocolo de host nuevo, consulte link:../config-linux/index.html["Configuración exprés de Linux"], link:../config-windows/index.html["Configuración exprés de Windows"], o. link:../config-vmware/index.html["Configuración exprés de VMware"]. .El futuro Se completa el proceso para añadir una tarjeta de interfaz del host a la cabina de almacenamiento. Es posible reanudar las operaciones normales.
Bytes : () , Integer size() -> /* number of bytes in the backing array */ , Octet each() -> /* callback function to process each octet in order */ , String =() -> each(format('%x ')) . String : (bytes: Bytes) , String +(s: String) -> String(Bytes(s) + Bytes()) , Integer characters() -> /* number of Unicode characters */ , Character each() -> /* callback on each character */ , Octet each() -> /* callback on each byte */ . /* Signed arbitrary precision numeric type */ Number : (n: Number) , String =() -> format('%f') . /* Signed Whole number */ Integer : (i: Number) : Number (i.floor() - i = 0 ? i : Error('{i} is not a valid Integer')) , String =() -> format('%d') . Day : (d: Integer) : Integer (d > 0 ? d : Error('Day {d} can not be less than 0')) , String =() -. format('%d') Hour : (h: Integer) : Integer ( 0 >= h < 24 ? h : Error('Hour {h} must be >= 0 and < 24')) , String =() -> format('%02d') . Minute : (m: Integer) : Integer ( 0 >= m < 60 ? m : Error('Minute {m} must be >= 0 and < 60')) , String =() -> format('%02d') . Second : (s: Integer) : Integer ( 0 >= i < 60 ? s : Error('Second {s} must be >= 0 and < 60')) , String =() -> format('%02d') . Millis : (m: Integer) : Integer ( 0 >= m < 1000 ? m : Error('Millis {m} must be >= 0 and < 1000')) , String =() -> format('%04d') . Time : (hour: Hour(0), minute: Minute(0), second: Second(0), millis: Millis(0)) , String =() -> format('{hour}:{minute}:{second}:{millis}') , Integer =() -> (hour * 3600000) + (minute * 60000) + (second * 1000) + millis . Duration : (ms: Integer) -> days: Day(ms - ((hours * 86400000) + (minutes * 86400000) + (seconds * 3600000) + (millis * 1000)) / 86400000) , hours: Hour(ms - ((minutes * 86400000) + (seconds * 3600000) + (millis * 1000)) % 86400000 / 3600000) , minutes: Minute(ms - ((seconds * 3600000) + (millis * 1000)) % 3600000 / 60000) , seconds: Second(ms - millis % 60000 / 1000) , millis: Millis(ms % 1000) . : (days: Day(0), hours: Hour(0), minutes: Minute(0), seconds: Second(0), millis: Millis(0)) , Duration +(d: Duration) -> Duration(Integer(d) + Integer(duration)) , String =() -> format('{days}:{hours}:{minutes}:{seconds}:{millis}') , Integer =() -> (days * 86400000) + (hours * 3600000) + (minutes * 60000) + (seconds * 1000) + millis .
import React from 'react' import './Product.css' import { useStateValue } from './StateProvider' function Product({id,title,image,price,rating}) { const [{basket},dispatch]= useStateValue(); console.log("this is the basket"); const addToBasket=()=>{ //dispatche the item into the data layer dispatch({ type:'ADD_TO_BASKET', item:{ id:id, title:title, image:image, price:price, rating:rating, }, }); }; return ( <div className='product'> <div className='product__info'> <p>{title}</p> <p className='product__price'> <small>$</small> <strong>{price}</strong> </p> <div className='product__rating'> {Array(rating).fill().map((_,i)=>( <p>🌟</p> ))} </div> </div> <img src={image} alt='' /> <button onClick={addToBasket}>Add to Basket</button> </div> ); } export default Product;
<script setup lang="ts"> import { NConfigProvider, type GlobalThemeOverrides } from 'naive-ui' import { ref } from 'vue' import Web3 from 'web3' import ABI from '../../../contract/ABI' const web3 = new Web3('https://rpc2.sepolia.org') const walletAddress = ref('') const ticketTokenAddress = ref('0x5F16813bAf39c710aFCB26F04Ef0E19a5ee1F653') const contract = new web3.eth.Contract(ABI, ticketTokenAddress.value) const walletCryptoBalance = ref<string | null>(null) const ticketBalance = ref(null) // Function to view the crypto balance of the attendee's wallet address const viewBalance = async () => { if (walletAddress.value === '') { alert('Please enter a wallet address') return } if (web3.utils.isAddress(walletAddress.value)) { const balance = await web3.eth.getBalance(walletAddress.value) const balanceInEther = web3.utils.fromWei(balance, 'ether') walletCryptoBalance.value = balanceInEther } else { alert('Invalid wallet address given') } } // Function to view the number of tickets owned by the attendee's wallet address const viewTickets = async () => { if (walletAddress.value === '') { alert('Please enter a wallet address') return } if (web3.utils.isAddress(ticketTokenAddress.value) && web3.utils.isAddress(walletAddress.value)) { console.log('Valid token addresses') contract.methods .balanceOf(walletAddress.value) .call() .then(function (balance: any) { ticketBalance.value = balance }) } else { alert('Invalid token address given') } } const themeOverrides: GlobalThemeOverrides = { Card: { titleTextColor: '#01328a', titleFontSizeMedium: '1.5rem', borderColor: 'none' }, Button: { colorHover: '#fe15c6', textColor: '#cce6ff', textColorHover: '#01328a', color: '#01328a', border: 'none', borderHover: 'none', colorPressed: '#fe15c6', borderPressed: 'none', textColorPressed: '#01328a', textColorGhostPressed: '#01328a', textColorTextPressed: '#01328a', textColorFocus: '#01328a' }, Input: { borderFocus: '#fe15c6', borderColor: '#fe15c6', boxShadowFocus: '#fe15c6', caretColor: '#01328a', textColor: '#01328a' }, Tag: { textColor: '#fe15c6' } } </script> <template> <n-config-provider :theme-overrides="themeOverrides"> <main> <n-card title="View account balance"> <label>Wallet address</label> <n-input-group> <n-input v-model:value="walletAddress" type="text" placeholder="Enter your wallet address" /> </n-input-group> <n-input-group style="display: flex; justify-content: space-around"> <n-button @click="viewBalance"> Account balance </n-button> <n-tag>{{ walletCryptoBalance ? `${walletCryptoBalance} SETH` : '- SETH' }}</n-tag> <n-button @click="viewTickets"> Ticket Balance </n-button> <n-tag>{{ ticketBalance ? `${ticketBalance} ticket(s)` : '- ticket(s)' }}</n-tag> </n-input-group> </n-card> </main> </n-config-provider> </template> <style scoped> label { font-size: 1rem; color: #01328a; } .n-input { text-transform: none; } .n-tag { text-transform: none; margin: 10px; } .n-button { text-transform: uppercase; margin: 10px; } </style>
import React, { useEffect } from "react"; import { Navigate } from "react-router-dom"; import useCheckAuth from "../../../hooks/useCheckAuth"; import Loading from "../../statuses/Loading/Loading"; export const ProtectedRoute = ({ children, mustAuth = true, }: { mustAuth?: boolean; children: JSX.Element; }) => { const { user, isLoaded, checkAuth, doResetLoaded } = useCheckAuth(); useEffect(() => { checkAuth(); return () => { doResetLoaded(); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); // Если пользователь должен быть авторизованным, а он не авторизован... if (mustAuth && isLoaded && !user) { return <Navigate to="/login" replace />; } // Если пользователь не должен быть авторизованным, а он авторизован... if (!mustAuth && isLoaded && user) { return <Navigate to="/" replace />; } if (isLoaded) { return children; } return <Loading />; };
import chai from 'chai'; import supertest from 'supertest'; import { mock_data } from './mock_data.js'; const requester = supertest('http://localhost:8080/api/sessions'); const expect = chai.expect; describe('Testing Sessions module', () => { it('registro como usuario', async () => { const { statusCode } = await requester.post('/register').send(mock_data.registerUser); expect(statusCode).to.equal(200); }); it('Registro como admin', async () => { const { statusCode } = await requester.post('/register').send(mock_data.registerAdmin); expect(statusCode).to.equal(404); }); it('Logeo como usuario', async () => { const { statusCode } = await requester.post('/login').send(mock_data.loginUser); expect(statusCode).to.equal(200); }); it('Logeo como admin', async () => { const { statusCode } = await requester.post('/login').send(mock_data.loginAdmin); expect(statusCode).to.equal(200); }); });
// // CustomTabBar.swift // CustomTabBarExample // // Created by Derlon Venancio on 18/12/2021. // import UIKit import RxSwift import RxCocoa import RxGesture final class CustomTabBar: UIStackView { var itemTapped: Observable<Int> { itemTappedSubject.asObservable() } private lazy var customItemViews: [CustomItemView] = [profileItem, searchItem, favoriteItem] private let profileItem = CustomItemView(with: .profile, index: 0) private let searchItem = CustomItemView(with: .search, index: 1) private let favoriteItem = CustomItemView(with: .favorite, index: 2) private let itemTappedSubject = PublishSubject<Int>() private let disposeBag = DisposeBag() init() { super.init(frame: .zero) setupHierarchy() setupProperties() bind() setNeedsLayout() layoutIfNeeded() selectItem(index: 0) } required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupHierarchy() { addArrangedSubviews([profileItem, searchItem, favoriteItem]) } private func setupProperties() { distribution = .fillEqually alignment = .center backgroundColor = .systemIndigo setupCornerRadius(30) customItemViews.forEach { $0.translatesAutoresizingMaskIntoConstraints = false $0.clipsToBounds = true } } private func selectItem(index: Int) { customItemViews.forEach { $0.isSelected = $0.index == index } itemTappedSubject.onNext(index) } //MARK: - Bindings private func bind() { profileItem.rx.tapGesture() .when(.recognized) .bind { [weak self] _ in guard let self = self else { return } self.profileItem.animateClick { self.selectItem(index: self.profileItem.index) } } .disposed(by: disposeBag) searchItem.rx.tapGesture() .when(.recognized) .bind { [weak self] _ in guard let self = self else { return } self.searchItem.animateClick { self.selectItem(index: self.searchItem.index) } } .disposed(by: disposeBag) favoriteItem.rx.tapGesture() .when(.recognized) .bind { [weak self] _ in guard let self = self else { return } self.favoriteItem.animateClick { self.selectItem(index: self.favoriteItem.index) } } .disposed(by: disposeBag) } }
from __future__ import annotations from datetime import datetime from flask import jsonify from .. import db class Base(db.Model): # type: ignore """ Base model """ __abstract__ = True __tablename__ = "base" id = db.Column(db.Integer, primary_key=True, autoincrement=True) created_at = db.Column(db.DateTime, nullable=False, default=datetime.now()) updated_at = db.Column( db.DateTime, nullable=False, default=datetime.now(), onupdate=datetime.now() ) deleted_at = db.Column(db.DateTime, nullable=True) def __init__( self, created_at: datetime = datetime.now(), updated_at: datetime = datetime.now(), ): self.created_at = created_at self.updated_at = updated_at @classmethod def first_by(cls, **kwargs) -> Base: """ Get first entity that matches to criterion """ return cls.query.filter_by(deleted_at=None, **kwargs).first() @classmethod def first(cls, *criterion) -> Base: """ Get first entity that matches to criterion """ return cls.query.filter(*criterion).first() @classmethod def exists(cls, *criterion) -> bool: """ Check if entry with criterion exists """ return cls.query.filter(*criterion).scalar() @classmethod def get(cls, _id: int) -> Base: """ Get the entity that matches the id """ return cls.query.get(_id) # This must be overridden by derived classes def json(self) -> dict: """ Get model data in JSON format """ return { "id": self.id, "created_at": str(self.created_at), "updated_at": str(self.updated_at), } def delete(self) -> None: """ Delete the entity """ self.deleted_at = datetime.now() db.session.commit()
import { ReactElement, useMemo } from 'react' import { useCachedState } from '@/utils/hooks' import { setJSON } from '@/utils/storage' import * as v2exClient from '@/utils/v2ex-client' import { HomeTabOption } from '@/utils/v2ex-client/types' import { AppSettingsContext } from './context' import { AppSettings, AppSettingsService } from './types' const CACHE_KEY = '$app$/settings' const DEFAULT_SETTINGS: AppSettings = { homeTabs: undefined, // Array<TabDesc> showHasViewed: true, showHasNewReply: true, theme: 'r2v', // themeColor: '', // 主题强调色 feedLayout: 'normal', // normal | tide feedShowAvatar: true, feedShowLastReplyMember: true, feedShowViewedHint: true, feedTitleStyle: 'normal', // normal | emphasized autoRefresh: true, autoRefreshDuration: 10, refreshHaptics: true, maxContainerWidth: 600, payLayoutEnabled: true, searchProvider: 'google', } const TODAY_HOT_TAB = { value: 'today_hots', label: '今日热议', type: 'home', disabled: true, } export default function AppSettingsServiceProvider(props: { children: ReactElement }) { const [settings, setSettings] = useCachedState<AppSettings>( CACHE_KEY, undefined, (data = {}) => { const merged = { ...DEFAULT_SETTINGS, ...data, } if ( merged.homeTabs && merged.homeTabs.findIndex( (item: HomeTabOption) => item.type === TODAY_HOT_TAB.type && item.value === TODAY_HOT_TAB.value, ) === -1 ) { merged.homeTabs.push(TODAY_HOT_TAB) } return merged }, ) const service = useMemo(() => { return { data: settings, update: setSettings, staticUpdate: (data) => setJSON(CACHE_KEY, data), initHomeTabs: async () => { const { data } = await v2exClient.getHomeTabs() const mapped: HomeTabOption[] = [ { value: 'recent', label: '最近', type: 'home', }, TODAY_HOT_TAB, ...data, ] .filter((item) => item.value !== 'nodes') .map((item) => ({ ...item, type: 'home' })) setSettings((prev) => ({ ...prev, homeTabs: mapped, })) return mapped }, } as AppSettingsService }, [settings]) return ( <AppSettingsContext.Provider value={service}> {props.children} </AppSettingsContext.Provider> ) }
@* * Copyright 2023 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *@ @import viewmodels.InputWidth._ @import components._ @import models.TraderDetailsWithCountryCode @import models.Country @this( layout: templates.Layout, formHelper: FormWithCSRF, govukErrorSummary: GovukErrorSummary, govukRadios: GovukRadios, caption: Caption, heading: Heading, headingH3: headingH3, subheading: Subheading, paragraph: Paragraph, cancelApplicationLink: CancelApplicationLink, saveButtons: SaveButtons, link: Link ) @(form: Form[_], mode: Mode, draftId: DraftId)(implicit request: Request[_], messages: Messages) @radioItems = @{ Seq( RadioItem( value = Some("true"), checked = form.value.fold(false)(_ == "true"), content = Text(messages("site.yes"))), RadioItem( value = Some("false"), checked = form.value.fold(false)(_ == "false"), content = Text(messages("site.no"))) ) } @layout(pageTitle = title(form, messages("haveYouReceivedADecision.heading")), draftId = Some(draftId)) { @formHelper(action = controllers.routes.HaveYouReceivedADecisionController.onSubmit(mode, draftId)) { @if(form.errors.nonEmpty) { @govukErrorSummary(ErrorSummaryViewModel(form)) } @caption(messages("caption.goods")) @heading(messages("haveYouReceivedADecision.heading")) <br></br> @paragraph(Html(messages("haveYouReceivedADecision.para.1"))) @paragraph(Html(messages("haveYouReceivedADecision.para.2"))) @govukRadios( RadiosViewModel( field = form("value"), legend = LegendViewModel(messages("haveYouReceivedADecision.legend")).asLegendHeading(), items = radioItems )) @saveButtons(draftId) } @cancelApplicationLink(draftId) }
#pragma once #include "CoreMinimal.h" #include "BaseCharacter.h" #include "InputActionValue.h" #include "CharacterTypes.h" #include "Interfaces/PickupInterface.h" #include "SlashCharacter.generated.h" class UInputMappingContext; class UInputAction; class USpringArmComponent; class UCameraComponent; class AItem; class ASoul; class ATreasure; class UAnimMontage; class USlashOverlay; UCLASS() class SLASH_API ASlashCharacter : public ABaseCharacter, public IPickupInterface { GENERATED_BODY() public: ASlashCharacter(); virtual void Tick(float DeltaTime) override; virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override; virtual void Jump() override; virtual float TakeDamage(float DamageAmount, struct FDamageEvent const& DamageEvent, class AController* EventInstigator, AActor* DamageCauser) override; virtual void GetHit_Implementation(const FVector& ImpactPoint, AActor* Hitter) override; virtual void SetOverlappingItem(AItem* Item) override; virtual void AddSouls(ASoul* Soul) override; virtual void AddGold(ATreasure* Treasure) override; private: virtual void BeginPlay() override; /** Callbacks for input */ void Move(const FInputActionValue& Value); void Look(const FInputActionValue& Value); void PickUp(); virtual void Attack() override; void DodgeLeft(); void DodgeRight(); /** Combat */ void EquipWeapon(AWeapon* Weapon); virtual void AttackEnd() override; virtual void DodgeEnd() override; virtual bool CanAttack() override; bool CanDisarm(); bool CanArm(); void Disarm(); void Arm(); void PlayEquipMontage(const FName& SectionName); virtual void Die_Implementation() override; bool HasEnoughStamina(); bool IsOccupied(); UFUNCTION(BlueprintCallable) void AttachWeaponToBack(); UFUNCTION(BlueprintCallable) void AttachWeaponToHand(); UFUNCTION(BlueprintCallable) void FinishEquipping(); UFUNCTION(BlueprintCallable) void HitReactEnd(); bool IsUnoccupied(); void InitializeSlashOverlay(); void SetHUDHealth(); /** Character components */ ECharacterState CharacterState = ECharacterState::ECS_Unequipped; UPROPERTY(BlueprintReadWrite, meta = (AllowPrivateAccess = "true")) EActionState ActionState = EActionState::EAS_Unoccupied; UPROPERTY() USlashOverlay* SlashOverlay; UPROPERTY(EditAnywhere, Category = Input) UInputMappingContext* SlashMappingContext; UPROPERTY(EditAnywhere, Category = Input) UInputAction* MovementAction; UPROPERTY(EditAnywhere, Category = Input) UInputAction* LookAction; UPROPERTY(EditAnywhere, Category = Input) UInputAction* JumpAction; UPROPERTY(EditAnywhere, Category = Input) UInputAction* AttackAction; UPROPERTY(EditAnywhere, Category = Input) UInputAction* PickUpAction; UPROPERTY(EditAnywhere, Category = Input) UInputAction* DodgeLeftAction; UPROPERTY(EditAnywhere, Category = Input) UInputAction* DodgeRightAction; UPROPERTY(VisibleAnywhere) USpringArmComponent* CameraBoom; UPROPERTY(VisibleAnywhere) UCameraComponent* ViewCamera; UPROPERTY(VisibleInstanceOnly) AItem* OverlappingItem; UPROPERTY(EditDefaultsOnly, Category = Montages) UAnimMontage* EquipMontage; public: FORCEINLINE ECharacterState GetCharacterState() const { return CharacterState; } FORCEINLINE EActionState GetActionState() const { return ActionState; } };
import config from 'config'; import {Request, Response} from 'express' import { createSession, findSessions, updateSession } from '../service/session.service'; import { validatePassword } from '../service/user.service' import { signJwt } from '../utils/jwt.utils'; export async function createUserSessionHandler(req: Request, res: Response){ const host = config.get<string>("host"); //validate user password const user = await validatePassword(req.body); if(!user){ return res.status(401).send("invalid email or password"); // password or email is invalid } //create session const session = await createSession(user._id, req.get("user-agent") || " "); const accessToken = signJwt({ ...user, session: session._id,}, {expiresIn: config.get("accessTokenTtl") }); const refreshToken = signJwt({ ...user, session: session._id,}, {expiresIn: config.get("refreshTokenTtl") }); res.cookie("refreshToken",refreshToken,{ //send refreshToken in cookie maxAge: 3.154e10, httpOnly: true, //can only access by http not by javascript domain: host, //should store in config file for production use path: '/', sameSite: 'strict', secure: false //secure false for http request }) res.cookie("accessToken",accessToken,{ //send accessToken in cookie maxAge: 90000, httpOnly: true, domain: host, path: '/', sameSite: 'strict', secure: false }); return res.send({accessToken, refreshToken}); } export async function getUserSessionsHandler( req: Request , res: Response ){ const userId = res.locals.user._id; const sessions = await findSessions({user: userId, valid: true}); return res.send(sessions); } export async function deleteSessionHandler(req: Request, res: Response) { const sessionId = res.locals.user.session; await updateSession({ _id: sessionId }, { valid: false }); return res.send({ accessToken: null, refreshToken: null, }); }
#ifndef RASPI_CAM_H #define RASPI_CAM_H // // Many source code lines are copied from RaspiVid.c // Copyright (c) 2012, Broadcom Europe Ltd // // Lines have been copied from GITHUB project // https://github.com/robidouille/robidouille of Emil Valkov // /** * @file raspi_cam.h * @author Gianluca D'Amico * @brief File containing RaspBerry Camera handling functions * * HANDLING CAMERA FUNCTIONS: It manages all the functions needed to capture * video frame from the raspberry camera. * * Utilizing the non static function, it is possible to create all the structure * to initilize the image frame buffer from the camera. In this file the Allegro * 4 library is utilize to show the captured images. * */ #include "common.h" #include "display.h" #include <pthread.h> /** * RETURN CONSTANT */ #define CAM_SUCCESS 0 #define CAM_ERROR 1 /** * GLOBAL STRUCT */ /**< Over write of the raspivid state struct. See userland library */ typedef struct _RASPIVID_STATE RASPIVID_STATE; /**< Basic camera configuration information. */ typedef struct { int width; int height; int bitrate; int framerate; int monochrome; } RASPIVID_CONFIG; /**< Capturing state struct. */ typedef struct { RASPIVID_STATE * pState; } raspi_cam_capture; /**< Enumaration for the basic camera information. */ enum { RPI_CAP_PROP_FRAME_WIDTH = 3, RPI_CAP_PROP_FRAME_HEIGHT = 4, RPI_CAP_PROP_FPS = 5, RPI_CAP_PROP_MONOCHROME = 19, RPI_CAP_PROP_BITRATE = 37 }; /**< Enumaration for the basic capture property. */ typedef enum { CONTRAST = 0, BRIGHTNESS, SATURATION, SHARPNESS } cam_property; /** * GLOBAL DATA */ extern unsigned char capture_buffer[CAM_HEIGHT * CAM_WIDTH]; extern int contrast_value; /**< Global contrast value.*/ extern int brightness_value; /**< Global brightness value.*/ extern int saturation_value; /**< Global saturation value.*/ extern int sharpness_value; /**< Global sharpness value.*/ /** * GLOBAL MUTEX */ extern pthread_mutex_t capture_buffer_mutex; extern pthread_mutex_t contrast_mutex; extern pthread_mutex_t brightness_mutex; extern pthread_mutex_t saturation_mutex; extern pthread_mutex_t sharpness_mutex; /** * GLOBAL FUNCTIONS */ /**< Create camera component. */ int raspi_cam_create_camera_capture(RASPIVID_CONFIG* config); /**< Release camera component. */ void raspi_cam_release_capture(); /**< Retrive frame image captured by the camera. */ void raspi_cam_query_frame(); #endif