text
stringlengths
184
4.48M
package jp.wasabeef.glide.transformations.gpu; import android.content.Context; import android.graphics.Bitmap; import com.bumptech.glide.Glide; import com.bumptech.glide.load.Transformation; import com.bumptech.glide.load.engine.Resource; import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool; import com.bumptech.glide.load.resource.bitmap.BitmapResource; import jp.co.cyberagent.android.gpuimage.GPUImage; import jp.co.cyberagent.android.gpuimage.GPUImageFilter; /* loaded from: classes.dex */ public class GPUFilterTransformation implements Transformation<Bitmap> { private BitmapPool mBitmapPool; private Context mContext; private GPUImageFilter mFilter; public GPUFilterTransformation(Context context, GPUImageFilter gPUImageFilter) { this(context, Glide.get(context).getBitmapPool(), gPUImageFilter); } public GPUFilterTransformation(Context context, BitmapPool bitmapPool, GPUImageFilter gPUImageFilter) { this.mContext = context.getApplicationContext(); this.mBitmapPool = bitmapPool; this.mFilter = gPUImageFilter; } @Override // com.bumptech.glide.load.Transformation public Resource<Bitmap> transform(Resource<Bitmap> resource, int i, int i2) { GPUImage gPUImage = new GPUImage(this.mContext); gPUImage.setImage(resource.get()); gPUImage.setFilter(this.mFilter); return BitmapResource.obtain(gPUImage.getBitmapWithFilterApplied(), this.mBitmapPool); } @Override // com.bumptech.glide.load.Transformation public String getId() { return getClass().getSimpleName(); } public <T> T getFilter() { return (T) this.mFilter; } }
<!-- Top navbar --> <mat-toolbar color="primary"> <button mat-icon-button class="example-icon" (click)="drawer.toggle()"> <mat-icon>menu</mat-icon> </button> <span>Fresh & Healthy</span> <span class="example-spacer"></span> <div *ngIf="!user"> <button mat-raised-button class="m-2" color="accent" [routerLink]="['/login']">Login</button> <button mat-raised-button color="warn" [routerLink]="['/register']">Register</button> </div> <div *ngIf="cart ? cart.length > 0 : false"> <button mat-icon-button [routerLink]="['/cart']"> <mat-icon matBadge="{{cart ? cart.length : 0}}" matBadgeColor="accent">shopping_cart</mat-icon> </button> </div> <div *ngIf="user" > <span *ngIf="notifications ? notifications.length > 0 : false"> <button mat-icon-button [matMenuTriggerFor]="notificationMenu"> <mat-icon matBadge="{{notifications ? notifications.length : 0}}" matBadgeColor="accent">notifications</mat-icon> </button> <mat-menu #notificationMenu="matMenu" xPosition="before" yPosition="above" [overlapTrigger]="false"> <a mat-menu-item *ngFor="let notify of notifications"> <span> <a [routerLink]="['/order/', notify.linkMessageTwo]"> {{notify.linkMessageTwo }}</a> {{notify.message}} <a [routerLink]="['/profile/', notify.linkMessageOne]"> {{notify.linkMessageOne }}</a> </span> <mat-divider></mat-divider> </a> </mat-menu> </span> <button mat-button [matMenuTriggerFor]="userMenu"> <mat-icon>person</mat-icon> <span fxShow fxHide.xs> {{user.firstName}} </span> </button> <mat-menu #userMenu="matMenu" xPosition="before" yPosition="above" [overlapTrigger]="false"> <a mat-menu-item [routerLink]="['/myaccount']"> <mat-icon>person</mat-icon> <span>Account</span> </a> <a mat-menu-item (click)="logout()"> <mat-icon>exit_to_app</mat-icon> <span >Log out</span> </a> </mat-menu> </div> </mat-toolbar> <mat-drawer-container hasBackdrop="false" role="navigation" class="navbar-container"> <mat-drawer #drawer mode="side" opened class="sidenav"> <mat-nav-list> <a mat-list-item [routerLink]="['/menu']" routerLinkActive="active"> <button mat-icon-button matListItemMeta> <mat-icon color="accent"> restaurant_menu</mat-icon> </button> <p matListItemTitle> Menu </p> </a> <a mat-list-item [routerLink]="['menu/myMenu']" routerLinkActive="active"> <button mat-icon-button matListItemMeta> <mat-icon color="accent"> <span class="material-symbols-outlined"> lunch_dining </span> </mat-icon> </button> <p matListItemTitle> Sell Food </p> </a> <a mat-list-item [routerLink]="['/myorder']" routerLinkActive="active"> <button mat-icon-button matListItemMeta> <mat-icon color="accent"> <span class="material-icons-two-tone"> menu_book </span></mat-icon> </button> <p matListItemTitle> My Orders </p> </a> <a mat-list-item [routerLink]="['/dashboard']" routerLinkActive="active"> <button mat-icon-button matListItemMeta> <mat-icon color="accent"> business</mat-icon> </button> <p matListItemTitle> Dashboard </p> </a> <span *ngIf="user?.adminUser === 1"> <a mat-list-item [routerLink]="['/admin']" routerLinkActive="active"> <button mat-icon-button matListItemMeta> <mat-icon color="accent"> people</mat-icon> </button> <p matListItemTitle> Admin </p> </a> </span> <a mat-list-item [routerLink]="['/myaccount']" routerLinkActive="active"> <button mat-icon-button matListItemMeta> <mat-icon color="accent"> person</mat-icon> </button> <p matListItemTitle> Account </p> </a> <a mat-list-item [routerLink]="['/about']" routerLinkActive="active"> <button mat-icon-button matListItemMeta> <mat-icon color="accent"> info_outline</mat-icon> </button> <p matListItemTitle> About </p> </a> <a mat-list-item (click)="logout()"> <button mat-icon-button matListItemMeta> <mat-icon color="accent"> exit_to_app</mat-icon> </button> <p matListItemTitle> Log out </p> </a> <mat-divider></mat-divider> </mat-nav-list> </mat-drawer> <mat-drawer-content role="main"> <div class="progress-bar-container"> <mat-progress-bar color="accent" mode="indeterminate" *ngIf="spinnerService.visibility | async"> </mat-progress-bar> <!-- <mat-spinner class="spinner" [diameter]="50" *ngIf="showSpinner"></mat-spinner> --> </div> <div class="container shadow p-3 m-3 bg-body rounded"> <router-outlet></router-outlet> </div> </mat-drawer-content> </mat-drawer-container>
using System; using System.Collections.Generic; using Actian.EFCore.Infrastructure.Internal; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage; namespace Actian.EFCore.Infrastructure { /// <summary> /// <para> /// Allows Actian specific configuration to be performed on <see cref="DbContextOptions" />. /// </para> /// </summary> public class ActianDbContextOptionsBuilder : RelationalDbContextOptionsBuilder<ActianDbContextOptionsBuilder, ActianOptionsExtension> { /// <summary> /// Initializes a new instance of the <see cref="ActianDbContextOptionsBuilder" /> class. /// </summary> /// <param name="optionsBuilder"> The options builder. </param> public ActianDbContextOptionsBuilder([NotNull] DbContextOptionsBuilder optionsBuilder) : base(optionsBuilder) { } /// <summary> /// Configures the context to use the default retrying <see cref="IExecutionStrategy" />. /// </summary> public virtual ActianDbContextOptionsBuilder EnableRetryOnFailure() => ExecutionStrategy(c => new ActianRetryingExecutionStrategy(c)); /// <summary> /// Configures the context to use the default retrying <see cref="IExecutionStrategy" />. /// </summary> public virtual ActianDbContextOptionsBuilder EnableRetryOnFailure(int maxRetryCount) => ExecutionStrategy(c => new ActianRetryingExecutionStrategy(c, maxRetryCount)); /// <summary> /// Configures the context to use the default retrying <see cref="IExecutionStrategy" />. /// </summary> /// <param name="maxRetryCount"> The maximum number of retry attempts. </param> /// <param name="maxRetryDelay"> The maximum delay between retries. </param> /// <param name="errorNumbersToAdd"> Additional SQL error numbers that should be considered transient. </param> public virtual ActianDbContextOptionsBuilder EnableRetryOnFailure( int maxRetryCount, TimeSpan maxRetryDelay, [CanBeNull] ICollection<int> errorNumbersToAdd) => ExecutionStrategy(c => new ActianRetryingExecutionStrategy(c, maxRetryCount, maxRetryDelay, errorNumbersToAdd)); } }
package com.tokopedia.shop.settings.notes.view.domain import com.tokopedia.graphql.coroutines.domain.interactor.GraphqlUseCase import com.tokopedia.graphql.coroutines.domain.repository.GraphqlRepository import com.tokopedia.shop.common.graphql.data.shopnote.ShopNoteModel import com.tokopedia.shop.common.graphql.data.shopnote.gql.ShopNoteQuery import com.tokopedia.usecase.RequestParams import javax.inject.Inject class GetShopNoteUseCase @Inject constructor( graphqlRepository: GraphqlRepository ) : GraphqlUseCase<ShopNoteQuery>(graphqlRepository) { companion object { const val query = """ query ShopNotes { shopNotes { result { id title content isTerms updateTime } error { message } } } """ } init { setGraphqlQuery(query) setTypeClass(ShopNoteQuery::class.java) } suspend fun execute(): List<ShopNoteModel> { setRequestParams(RequestParams.create().parameters) return executeOnBackground().result?.result.orEmpty() } }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <%@ page import="javax.servlet.http.HttpSession" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/js/bootstrap.bundle.min.js"></script> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Nanum+Myeongjo:wght@700&display=swap" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="../css/board/board.css"> <title>게시판</title> </head> <% String sessionId = (String) session.getAttribute("sessionID"); if(sessionId == null || sessionId == "") { response.sendRedirect("/members/login.do"); } %> <script> var totalPage = ${totalPage}; </script> <script src="../js/board/board.js"></script> <body> <h1>게시판</h1> <div class="user-info"> <a href="/members/mypage.do?ID=${sessionScope.sessionID}"><span id="user-id">${sessionScope.sessionID} 님!</span></a> </div> <div class="btn_group"> <button type="button" class="btnGroup" onclick="boardWirte()">글 작성하기</button> <button type="button" class="btnGroup" onclick="loginGo()">로그인하기</button> <button type="button" class="btnGroup" onclick="logout()">로그아웃하기</button> </div> <div class="search"> <select class="search_gubun" id="search_gubun"> <option value="all" selected>-- 제목+내용 --</option> <option value="title">제목</option> <option value="content">내용</option> </select> <input type="text" name="searchContent" id="searchContent" placeholder="검색어를 입력하세요."> <button type="button" id="searchBtn" onclick="search(1)">검색</button> </div> <div class="sort"> <select class="sort_gubun" id="sort_gubun"> <option value="recent" selected>-- 최신순 --</option> <option value="past">과거순</option> </select> </div> <div class="size"> <select class="size_gubun" id="size_gubun"> <option value="10" selected>-- 10개씩 출력 --</option> <option value="20">20개씩 출력</option> <option value="30">30개씩 출력</option> </select> </div> <table class="table table-bordered"> <thead> <tr> <th width="13%">글 번호</th> <th width="34%">제목</th> <th width="15%">작성자</th> <th width="8%">첨부파일</th> <th width="17%">등록일</th> <th width="13%">조회수</th> </tr> </thead> <tbody class="table-group-divider"> <c:if test="${totalBoardList == 0}"> <tr> <td colspan="6" style="text-align: center;">등록된 게시물이 없습니다.</td> </tr> </c:if> <c:if test="${!response.searchYN}"> <c:forEach items="${result}" var="result"> <tr> <td>${result.idx}</td> <td><a href="/boards/detail.do?Idx=${result.idx}">${result.title}</a></td> <c:choose> <c:when test="${result.anony eq '1'}"> <td>${result.id}</td> </c:when> <c:when test="${result.anony eq '2'}"> <td>익명</td> </c:when> </c:choose> <td>Y</td> <td><fmt:formatDate pattern="yyyy-MM-dd" value="${result.rdate}" /></td> <td>${result.hits}</td> </tr> </c:forEach> </c:if> </tbody> </table> <nav aria-label="Page navigation example" class="pageGroup"> <ul class="pagination justify-content-center"> <%-- 이전 --%> <c:if test="${pageNum > 1}"> <li class="page-item"> <a class="page-link" href="/boards/list.do?pageNum=${pageNum -1}">이전</a> </li> </c:if> <c:forEach var="i" begin="${startPage}" end="${endPage}" step="1"> <li class="page-item"> <a class="page-link pageNum" href="/boards/list.do?pageNum=${i}">${i}</a> </li> </c:forEach> <%-- 다음 --%> <c:if test="${pageNum < totalPage}"> <li class="page-item"> <a class="page-link" href="/boards/list.do?pageNum=${pageNum +1}">다음</a> </li> </c:if> </ul> </nav> </body> </html>
// // StorageManager.swift // Test_task // // Created by max on 20.06.2022. // import UIKit import CoreData class StorageManager { static let shared = StorageManager() private init() {} let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext var likedPhotos: [LikedPhoto] = [] func saveContext() { guard context.hasChanges else { return } do { try context.save() } catch let error as NSError { print ("Error: \(error)") } } func retieveLikedPhotos(completion: @escaping ([LikedPhoto]) -> Void) { do { likedPhotos = try context.fetch(LikedPhoto.fetchRequest()) completion(likedPhotos) } catch { print ("Error retrieving: \(error)") } } func save(author: String?, photoUrl: String?, downloads: String?, location: String?, creationDate: String?) { let likedPhoto = LikedPhoto(context: context) likedPhoto.author = author likedPhoto.location = location likedPhoto.downloads = downloads likedPhoto.photo = photoUrl likedPhoto.creationDate = creationDate do { try context.save() print ("SAVED SUCCESSFULLY") } catch { print (error) } } func delete(photo: LikedPhoto) { context.delete(photo) do { try context.save() } catch { print (error) } } func searchInCoreData(with currentImage: String?) -> Bool { guard let searchQuery = currentImage else { return false } let fetchRequest: NSFetchRequest<LikedPhoto> fetchRequest = LikedPhoto.fetchRequest() fetchRequest.predicate = NSPredicate(format: "photo == %@", searchQuery) return ((try? context.count(for: fetchRequest)) ?? 0) > 0 } func retrieveSingleObject(with currentImage: String?) -> LikedPhoto? { guard let searchQuery = currentImage else { return nil } let fetchRequest: NSFetchRequest<LikedPhoto> fetchRequest = LikedPhoto.fetchRequest() fetchRequest.fetchLimit = 1 fetchRequest.predicate = NSPredicate(format: "photo == %@", searchQuery) do { return try context.fetch(fetchRequest).first } catch { print (error) return nil } } }
import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:kwekwana/screens/bottom_nav_bar_screens.dart'; import 'package:kwekwana/screens/signingUpProcess/enable_location.dart'; import 'package:pinput/pinput.dart'; import '../../globals/global_vars.dart'; import '../../services/firebase_auth.dart'; import '../../widgets/backbutton.dart'; import '../../widgets/num_pad.dart'; class VerificationCode extends StatefulWidget { const VerificationCode({Key? key}) : super(key: key); @override State<VerificationCode> createState() => _VerificationCodeState(); } class _VerificationCodeState extends State<VerificationCode> { TextEditingController otpController = TextEditingController(); final _authService = FirebaseAuthService(); @override Widget build(BuildContext context) { const focusedBorderColor = Colors.pink; const fillColor = Color.fromRGBO(243, 246, 249, 0); const borderColor = Color.fromRGBO(23, 171, 144, 0.4); final defaultPinTheme = PinTheme( width: 56, height: 56, textStyle: const TextStyle( fontSize: 22, color: Color.fromRGBO(30, 60, 87, 1), ), decoration: BoxDecoration( borderRadius: BorderRadius.circular(19), border: Border.all(color: borderColor), ), ); return Scaffold( resizeToAvoidBottomInset: false, body: Container( padding: const EdgeInsets.fromLTRB(20, 48.0, 20, 0), width: double.infinity, decoration: const BoxDecoration( // color: Color.fromRGBO(255, 244, 245, 1), gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: <Color>[ Color.fromRGBO(249, 231, 255, 1), Color.fromRGBO(254, 239, 246, 1), Color.fromRGBO(253, 249, 255, 1), Color.fromRGBO(253, 249, 255, 1), Color.fromRGBO(251, 216, 234, 1), Color.fromRGBO(251, 216, 234, 1), ], // Gradient from https://learnui.design/tools/gradient-generator.html tileMode: TileMode.mirror, ), ), child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ Row( mainAxisAlignment: MainAxisAlignment.start, children: [ MyBackButton( onTap: () { Navigator.pop(context); }, ), ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( '00', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 30, ), ), Text( ':', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 30, ), ), Text( '42', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 30, ), ), ], ), Container( margin: EdgeInsets.only(top: 10, bottom: 30), width: 200, child: Text( 'Type the verification code we have sent you', textAlign: TextAlign.center, style: TextStyle(color: Color.fromRGBO(76, 74, 77, 1)), ), ), Container( // width: 270, margin: EdgeInsets.only(bottom: 30), child: Directionality( // Specify direction if desired textDirection: TextDirection.ltr, child: Pinput( keyboardType: TextInputType.none, length: 6, controller: otpController, // focusNode: focusNode, androidSmsAutofillMethod: AndroidSmsAutofillMethod.smsUserConsentApi, listenForMultipleSmsOnAndroid: true, // defaultPinTheme: defaultPinTheme, validator: (value) { // return value == '2222' ? null : 'Pin is incorrect'; }, onClipboardFound: (value) { otpController.setText(value); }, hapticFeedbackType: HapticFeedbackType.lightImpact, onCompleted: (pin) async { bool result = await _authService.verifyCode(pin); if (result) { if (goToHome) { Navigator.push( context, MaterialPageRoute(builder: (context) => BottomNavBarScreens()), ); } else { Navigator.push( context, MaterialPageRoute(builder: (context) => EnableLocation()), ); } } else { ScaffoldMessenger.of(context) .showSnackBar(SnackBar(content: Text('Wrong Code. please try again'))); } }, onChanged: (value) { // debugPrint('onChanged: $value'); }, cursor: Column( mainAxisAlignment: MainAxisAlignment.end, children: [ Container( margin: const EdgeInsets.only(bottom: 9), width: 22, height: 1, color: Colors.pink, ), ], ), focusedPinTheme: defaultPinTheme.copyWith( decoration: defaultPinTheme.decoration!.copyWith( borderRadius: BorderRadius.circular(8), border: Border.all(color: focusedBorderColor), ), ), submittedPinTheme: defaultPinTheme.copyWith( decoration: defaultPinTheme.decoration!.copyWith( color: fillColor, // borderRadius: BorderRadius.circular(19), border: Border.all(color: focusedBorderColor), ), ), errorPinTheme: defaultPinTheme.copyBorderWith( border: Border.all(color: Colors.redAccent), ), ), ), ), NumPad( buttonSize: 70, buttonColor: Color.fromRGBO(255, 83, 169, 0.08), iconColor: Color.fromRGBO(255, 83, 169, 0.2), controller: otpController, delete: () { otpController.text = otpController.text == "" ? "" : otpController.text.substring(0, otpController.text.length - 1); }, // do something with the input numbers ), Padding( padding: const EdgeInsets.only(top: 45.0), child: Text( 'Resend Code', style: TextStyle(color: Colors.red, fontWeight: FontWeight.bold), ), ), ], ), ), ); } }
classdef EscooterDyn properties simLength % Length of simulation mass % mass of the vehicle voltageM % voltage of the BLDC motor t % simulation time and step dT a % acceleration end methods function obj = EscooterDyn(simLength, mass, voltageM) % init function obj.simLength = simLength; obj.mass = mass; obj.voltageM = voltageM; obj.t = linspace(0, simLength, 1+simLength*10); obj.dT = 0.1 ; obj.a = 0.483; % default to WOT end function [V, I, PW] = accelerate(obj, Vfinal, Vinit, sample) % returns Velocity , motor current and power during acc maxL = 1+obj.simLength*10; % Initialization V = zeros(1, maxL); % velocity I = zeros(1, maxL); % current PW = zeros(1, maxL); % Power V(1,1) = Vinit ; reached = false; for n= 1:obj.simLength*10 if V(n) >= Vfinal reached = true; end if V(n)<10.8 && floor(V(n)) < Vfinal && reached ~= true V(n+1) = V(n) + obj.dT*(1.57 - (0.00145*(V(n)^2))); elseif V(n)>=10.8 && floor(V(n)) < Vfinal && reached ~= true V(n+1)=V(n)+obj. dT*(7.30-(0.53*V(n))-(0.00145*(V(n)^2))); elseif reached == true V(n+1) = Vfinal; end % end if end % end for if sample == true Vreturn = zeros(1,obj.simLength); Vreturn(1,1) = Vinit; j=1; for i =2:obj.simLength*10 -2 j = mod(i,10); if j == 0 Vreturn(floor((i+1)/10)+1) = V(i+1); end end end % Current calculation I(1,1) = (obj.a*Vinit*obj.mass)/obj.voltageM; for n=2:maxL I(n) = (obj.a*V(n)*obj.mass)/obj.voltageM; end if sample == true Ireturn = zeros(1,obj.simLength); Ireturn(1,1) = I(1,1); for i =2:obj.simLength*10 -2 j = mod(i,10); if j == 0 Ireturn(floor((i+1)/10) + 1) = I(i+1); end % second if end % for end % % power profile calculation: PW(1,1) = obj.voltageM * I(1,1); for n=1:maxL-1 PW(n+1) = obj.voltageM * I(n+1); end if sample == true PWreturn = zeros(1,obj.simLength); PWreturn(1,1) = obj.voltageM *I(1,1); for i =2:obj.simLength*10-2 j = mod(i,10); if j == 0 PWreturn(floor((i+1)/10)+1) = obj.voltageM* I(i+1); end % second if end % for end % if sample == true V = Vreturn; I = Ireturn; PW = PWreturn; end end % end function function [V, I, PW ]= decelerate(obj, Vfinal, Vinit, sample) % returns Velocity , motor current and power during braking maxL = 1+obj.simLength*10; % Initialization V = zeros(1, maxL); % velocity I = zeros(1, maxL); % current PW = zeros(1, maxL); % Power V(1,1) = Vinit ; reached = false; ind = 0; % when motor power flow is postive agin -- final cruise speed counter = 0; for n= 1:obj.simLength*10 if le(V(n), Vfinal) && counter == 0 reached = true; ind = n; counter = 1; end if V(n)<10.8 && round(V(n)) > Vfinal && reached ~= true fctr = obj.dT*(1.57 - (0.00145*(V(n)^2))); V(n+1) = V(n) - fctr ; elseif V(n)<10.8 && reached ~= true fctr = obj.dT*(1.57 - (0.00145*(V(n)^2))); V(n+1) = V(n) - fctr ; elseif V(n)>=10.8 && round(V(n)) > Vfinal && reached ~= true fctr = obj. dT*(7.30-(0.53*V(n))-(0.00145*(V(n)^2))) ; V(n+1)= V(n) - fctr ; elseif reached == true V(n+1) = Vfinal; end % end if end % end for if sample == true Vreturn = zeros(1,obj.simLength); Vreturn(1,1) = Vinit; for i =2:obj.simLength*10 -2 j = mod(i,10); if j == 0 Vreturn(floor((i+1)/10)+1) = V(i+1); end end end % Current calculation I(1,1) = - ((obj.a*Vinit*obj.mass)/obj.voltageM); for n=2:maxL I_step = (obj.a*V(n)*obj.mass)/obj.voltageM; if n <= ind I(n) = - I_step; else I(n) = I_step; end end %I = - I; % motor working as generator, thus negative current if sample == true Ireturn = zeros(1,obj.simLength); Ireturn(1,1) = I(1,1); for i =2:obj.simLength*10 - 2 j = mod(i,10); if j == 0 Ireturn(floor((i+1)/10)+1) = I(i+1); end % second if end % for end % % power profile calculation: PW(1,1) = obj.voltageM * I(1,1); for n=1:maxL-1 PW(n+1) = obj.voltageM * I(n+1); end if sample == true PWreturn = zeros(1,obj.simLength); PWreturn(1,1) = obj.voltageM * I(1,1); for i =2:obj.simLength*10 - 2 j = mod(i,10); if j == 0 PWreturn(floor((i+1)/10)+1) = obj.voltageM* I(i+1); end % second if end % for end % if sample == true V = Vreturn; I = Ireturn; PW = PWreturn; end end % end function function plots(obj, Vfinal, Vinit, acc) if acc ~= false [V, I, PW] = obj.accelerate(Vfinal, Vinit, false); figure(1); %plot(t,vel); axis([0 30 0 20]); plot(obj.t,V, 'r') grid on xlabel('Time [seconds]'); ylabel('Velocity [kph]'); title("velocity of ES: acc " + string(obj.a) + "m/s^2"); figure(2); %plot(t,Imotor); axis([0 30 0 30]); plot(obj.t, I) grid on xlabel('Time [seconds]'); ylabel('Motor Current [A]'); title('Current drawm by the BLDC motor'); figure(3); %plot(t,Imotor); axis([0 30 0 30]); plot(obj.t, PW, 'm') grid on xlabel('Time [seconds]'); ylabel('Power required [W]'); title('Power required by the E-motor'); figure(4); %plot(t,Imotor); axis([0 30 0 30]); scatter(PW, V*3.6,"k") grid on ylabel('Velocity [kph]'); xlabel('Power required [W]'); title('Power required by the E-motor vs vehicle velocity'); else [V, I, PW] = obj.decelerate(Vfinal, Vinit, false); figure(5); %plot(t,vel); axis([0 30 0 20]); plot(obj.t,V*3.6, 'r') grid on xlabel('Time [seconds]'); ylabel('Velocity [kph]'); title("braking of ES: acc -" + string(obj.a) + " m/s^2"); figure(6); %plot(t,Imotor); axis([0 30 0 30]); plot(obj.t, I) grid on xlabel('Time [seconds]'); ylabel('Motor Current [A]'); title('Current drawm by the BLDC motor'); figure(7); %plot(t,Imotor); axis([0 30 0 30]); plot(obj.t, PW, 'k') grid on xlabel('Time [seconds]'); ylabel('Power required [W]'); title('Power required by the E-motor'); figure(8); %plot(t,Imotor); axis([0 30 0 30]); scatter( PW, V*3.6, "m") grid on ylabel('Velocity [kph]'); xlabel('Power required [W]'); title('Power required by the E-motor vs vehicle velocity'); end end % end function end % end methods end % end class
<!-- This file is part of the Open MIDATA Server. The Open MIDATA Server 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 any later version. The Open MIDATA Server 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 the Open MIDATA Server. If not, see <http://www.gnu.org/licenses/>. --> <template> <panel :title="$t('admin_study.title')" :busy="isBusy"> <error-box :error="error"></error-box> <table class="table"> <tr> <td v-t="'admin_study.name'"></td> <td>{{ study.name }}</td> </tr> <tr> <td v-t="'admin_study.type'"></td> <td>{{ $t('enum.studytype.' + study.type) }}</td> </tr> <tr> <td v-t="'admin_study.created_at'"></td> <td>{{ $filters.date(study.createdAt) }}</td> </tr> <tr> <td v-t="'admin_study.created_by'"></td> <td>{{ creator.firstname }} {{ creator.lastname }} ({{ creator.email }})</td> </tr> <tr> <td v-t="'admin_study.description'"></td> <td>{{ study.description }}</td> </tr> <tr> <td v-t="'admin_study.code'"></td> <td>{{ study.code }}</td> </tr> <tr> <td v-t="'admin_study.startDate'"></td> <td>{{ $filters.date(study.startDate) }}</td> </tr> <tr> <td v-t="'admin_study.endDate'"></td> <td>{{ $filters.date(study.endDate)}}</td> </tr> <tr> <td v-t="'admin_study.dataCreatedBefore'"></td> <td>{{ $filters.date(study.dataCreatedBefore) }}</td> </tr> <tr> <td v-t="'admin_study.joinmethods'"></td> <td> <ul> <li v-for="method in study.joinMethods" :key="method">{{ $t('enum.joinmethod.'+method) }}</li> </ul> </td> </tr> <tr> <td v-t="'admin_study.consent_observers'"></td> <td> <ul> <li v-for="appName in study.consentObserverNames" :key="appName">{{ appName }}</li> </ul> </td> </tr> <tr> <td v-t="'admin_study.leavePolicy'"></td> <td>{{ $t('enum.projectleavepolicy.' + (study.leavePolicy || 'FREEZE')) }}</td> </tr> <tr> <td v-t="'admin_study.rejoinPolicy'"></td> <td>{{ $t('enum.rejoinpolicy.' + (study.rejoinPolicy || 'NO_REJOIN')) }}</td> </tr> </table> </panel> <panel :title="$t('admin_study.infos')" :busy="isBusy"> <div v-for="(info,idx) in study.infos" :key="idx"> <h4>{{ $t('enum.infos.'+info.type) }}</h4> <div v-for="(v,k) in info.value" :key="k"> <p><b>{{k}}:</b><br>{{v}}</p> </div> </div> </panel> <panel v-if="study && study.infosInternal && study.infosInternal.length" :title="$t('admin_study.infos_internal')" :busy="isBusy"> <div v-for="(info,idx) in study.infosInternal" :key="idx"> <h4>{{ $t('enum.infos.'+info.type) }}</h4> <div v-for="(v,k) in info.value" :key="k"> <p><b>{{k}}:</b><br>{{v}}</p> </div> </div> </panel> <panel v-if="study && study.infosPart && study.infosPart.length" :title="$t('admin_study.infos_part')" :busy="isBusy"> <div v-for="(info,idx) in study.infosPart" :key="idx"> <h4>{{ $t('enum.infos.'+info.type) }}</h4> <div v-for="(v,k) in info.value" :key="k"> <p><b>{{k}}:</b><br>{{v}}</p> </div> </div> </panel> <panel :title="$t('admin_study.required_information')" :busy="isBusy"> <p><span v-t="'admin_study.required_information'"></span>: <b>{{ study.requiredInformation }}</b></p> <p><span v-t="'admin_study.anonymous'"></span>: <b>{{ $t('common.yesno.'+study.anonymous) }}</b></p> <p><span v-t="'admin_study.required_assistance'"></span>: <b>{{ study.assistance }}</b></p> <p><span v-t="'admin_study.termsOfUse'"></span>: <b><router-link :to="{ path : './terms', query : { which:study.termsOfUse} }">{{ study.termsOfUse }}</router-link></b></p> <p><span v-t="'admin_study.sharing_query'"></span>:</p> <access-query :query="study.recordQuery" details="true"></access-query> <pre>{{ JSON.stringify(study.recordQuery, null, 2) }} </pre> <p v-t="'admin_study.requirements'"></p> <ul> <li v-for="req in study.requirements" :key="req">{{ $t('enum.userfeature.'+req) }}</li> </ul> </panel> <panel :title="$t('admin_study.groups')" :busy="isBusy"> <table class="table table-striped"> <tr> <th v-t="'admin_study.group_name'"></th> <th v-t="'admin_study.group_description'"></th> </tr> <tr v-for="(group,idx) in study.groups" :key="idx"> <td>{{ group.name }}</td> <td>{{ group.description }}</td> </tr> </table> </panel> <panel :title="$t('admin_study.team')" :busy="isBusy"> <pagination v-model="members"></pagination> <table class="table table-striped"> <tr> <Sorter v-model="members" sortby="user.firstname" v-t="'common.user.firstname'"></Sorter> <Sorter v-model="members" sortby="user.lastname" v-t="'common.user.lastname'"></Sorter> <Sorter v-model="members" sortby="user.email" v-t="'common.user.email'"></Sorter> <Sorter v-model="members" sortby="role" v-t="'admin_study.role'"></Sorter> <th></th> </tr> <tr v-for="member in members.filtered" :key="member.user._id"> <td>{{ member.user.firstname }}</td> <td>{{ member.user.lastname }}</td> <td>{{ member.user.email }}</td> <td>{{ member.role.roleName }}</td> <td> {{ matrix(member.role) }} </td> </tr> </table> </panel> <panel :title="$t('admin_study.links')" :busy="isBusy"> <p v-t="'studyactions.empty'" v-if="!links.length"></p> <table class="table table-striped table-hover" v-if="links.length"> <tr> <th v-t="'studyactions.app'"></th> <th v-t="'studyactions.type'"></th> <th v-t="'studyactions.validation'"></th> <th></th> </tr> <tr v-for="(link,idx) in links" :key="idx"> <td @click="select(link);">{{ link.app.filename }}</td> <td> <div v-for="type in link.type" :key="type">{{ $t('studyactions.types_short.'+type) }}</div> </td> <td> <div v-if="link.validationResearch != 'VALIDATED'"> <span class="fas fa-times text-danger"></span> <span v-t="'studyactions.status.not_validated_research'"></span> </div> <div v-if="link.validationDeveloper != 'VALIDATED'"> <span class="fas fa-times text-danger"></span> <span v-t="'studyactions.status.not_validated_developer'"></span> </div> <div v-if="link.validationDeveloper == 'VALIDATED' && link.validationResearch == 'VALIDATED'"> <span class="fas fa-check text-success"></span> <span v-t="'studyactions.status.validated'"></span> </div> <div v-if="link.usePeriod.indexOf(study.executionStatus)<0"> <span class="fas fa-times text-danger"></span> <span v-t="'studyactions.status.study_wrong_status'"></span> </div> <div v-if="link.type.indexOf('REQUIRE_P')>=0 && study.participantSearchStatus != 'SEARCHING'"> <span class="fas fa-times text-danger"></span> <span v-t="'error.closed.study'"></span> </div> <div v-if="(link.type.indexOf('REQUIRE_P')>=0 || link.type.indexOf('OFFER_P')>=0) && link.study.joinMethods.indexOf('APP') < 0"> <span class="fas fa-times text-danger"></span> <span v-t="'studyactions.status.study_no_app_participation'"></span> </div> </td> <td> <button type="button" class="btn btn-sm btn-default" @click="validate(link);" v-t="'studyactions.validate_btn'"></button> <button type="button" class="btn btn-sm btn-danger" @click="remove(link);" v-t="'common.delete_btn'"></button> </td> </tr> </table> </panel> <panel :title="$t('admin_study.history')" :busy="isBusy"> <audit-log :entity="study._id"></audit-log> </panel> <router-link class="btn btn-default mr-1" :to="{ path : './astudies' }" v-t="'common.back_btn'"></router-link> <button v-if="study.validationStatus == 'VALIDATION'" class="btn btn-primary mr-1" @click="finishValidation()" v-t="'admin_study.end_validation_btn'"></button> <button v-if="study.validationStatus == 'VALIDATION'" class="btn btn-default mr-1" @click="backToDraft()" v-t="'admin_study.back_to_draft_btn'"></button> <button v-if="study.validationStatus != 'DRAFT'" class="btn btn-default mr-1" @click="exportStudy()" v-t="'admin_study.export_btn'"></button> <button v-if="readyForDelete()" class="btn btn-danger mr-1" @click="doDelete()" v-t="'admin_study.delete_study_btn'"></button> </template> <script> import Panel from "components/Panel.vue" import AuditLog from "components/AuditLog.vue" import AccessQuery from "components/tiles/AccessQuery.vue" import server from "services/server.js" import users from "services/users.js" import usergroups from "services/usergroups.js" import ENV from "config" import { status, rl, ErrorBox } from 'basic-vue3-components' export default { data: () => ({ studyid : null, study : {}, creator : null, members : null, links : null }), components: { Panel, ErrorBox, AuditLog, AccessQuery }, mixins : [ status, rl ], methods : { reload() { const { $data, $route } = this, me = this; me.doBusy(server.get(jsRoutes.controllers.research.Studies.getAdmin($data.studyid).url) .then(function(data) { $data.study = data.data.study; me.doBusy(users.getMembers({ _id : $data.study.createdBy, "role" : ["RESEARCH","DEVELOPER","ADMIN"] }, users.MINIMAL) .then(function(data2) { $data.creator = data2.data[0]; })); me.doBusy(usergroups.listUserGroupMembers($data.studyid) .then(function(data) { let members = data.data; for (let member of members) { member.role.unpseudo = !member.role.pseudo; } $data.members = me.process(members, { filter : { status : 'ACTIVE'} }); })); me.doBusy(server.get(jsRoutes.controllers.Market.getStudyAppLinks("study", $data.studyid).url) .then(function(data) { $data.links = data.data; })); })); }, finishValidation() { const { $data, $router } = this, me = this; me.doAction("validation", server.post(jsRoutes.controllers.research.Studies.endValidation($data.studyid).url). then(function(data) { $router.push({ path : './astudies' }); })); }, backToDraft() { const { $data, $router } = this, me = this; me.doAction("back", server.post(jsRoutes.controllers.research.Studies.backToDraft($data.studyid).url). then(function(data) { $router.push({ path : './astudies' }); })); }, doDelete() { const { $data, $router } = this, me = this; me.doAction("delete", server.post(jsRoutes.controllers.admin.Administration.deleteStudy($data.studyid).url). then(function(data) { $router.push({ path : './astudies' }); })); }, matrix(role) { var r = ""; r += role.setup ? "S" : "-"; r += role.readData ? "R" : "-"; r += role.writeData ? "W" : "-"; r += role.unpseudo ? "U" : "-"; r += role["export"] ? "E" : "-"; r += role.changeTeam ? "T" : "-"; r += role.participants ? "P" : "-"; r += role.auditLog ? "L" : "-"; r += role.applications ? "A" : "-"; return r; }, readyForDelete() { return true; }, remove(link) { const { $data, $route } = this, me = this; me.doAction("delete", server.delete(jsRoutes.controllers.Market.deleteStudyAppLink(link._id).url) .then(function() { me.reload(); })); }, validate(link) { const { $data, $route } = this, me = this; me.doAction("validate", server.post(jsRoutes.controllers.Market.validateStudyAppLink(link._id).url) .then(function() { me.reload(); })); }, exportStudy() { const { $data, $route } = this, me = this; me.doAction("download", server.token()) .then(function(response) { document.location.href = ENV.apiurl + jsRoutes.controllers.research.Studies.exportStudy($data.studyid).url + "?token=" + encodeURIComponent(response.data.token); }); } }, created() { const { $data, $route } = this, me = this; $data.studyid = $route.query.studyId; me.reload(); } } </script>
--- title: El juego del unicornio 🦄 - Solo CSS description: 'Creando un juego con CSS desde cero. El juego del unicornio es un mini juego creado completamente con CSS y HTML. ¿Es posible crear un juego con CSS? ¿Cuáles son los límites del lenguaje?' created: 2021-12-01 type: blog author: Jorge Baumann tags: - CSS - HTML - Juego --- CSS no es un lenguaje de programación como lo es, por ejemplo, JavaScript. A nadie se le ocurriría crear un juego con CSS; no es algo muy sensato. Sin embargo, esta es la parte divertida. Al igual que cuando hacemos dibujos con CSS en [twitch](https://twitch.tv/baumannzone), se trata de experimentar y exprimir el lenguaje. En este artículo me gustaría explorar los límites del lenguaje CSS. Quiero ver si es posible crear un juego con CSS sin usar JavaScript, escribiendo solo HTML y CSS. ¿Qué te parece? ## 🦄 Antonio, el unicornio [Antonio](https://youtu.be/x2kLLNFh-1k) es el nombre con el que la comunidad, a través de una encuesta, bautizó al unicornio que fue creado durante un streaming en mi canal de [twitch](https://twitch.tv/baumannzone) usando solo HTML y CSS. Antonio buscaba una vida llena de alegría y color. Le gustaba explorar el mundo y dar largos paseos por las nubes; contemplar las estrellas y sentir la brisa en la cara era algo que le encantaba. En uno de esos paseos, se despistó y se desorientó. De repende no sabía dónde estaba, no entendía que estaba pasando. Cuando se dio cuenta, vio que estaba atrapado en una mazmorra de la que no sabía salir. ## Objetivo del juego El objetivo del juego es guiar al unicornio hasta el final de la mazmorra, usando el _ratón_ de tu ordenador. El único inconveniente es que las paredes de la mazmorra están malditas y el unicornio morirá si las toca. Estoy seguro de que no quieres que la culpa de la muerte del unicornio recaiga sobre ti. ## Controles del juego Para jugar al _juego del unicornio_ solo necesitas el ratón, una mente fría y un poco de destreza. En cuanto pongas el cursor sobre el triangulo verde, la pantalla empezará a moverse y el juego habrá empezado. Recuerda, no se pueden tocar las paredes. ## El juego <blog-unicorn-game></blog-unicorn-game> ## HTML La estructura HTML del juego es la siguiente: ```html <div class="game"> <div class="dungeon"> <div class="dungeon-wall-left"></div> <div class="dungeon-wall-right"></div> <div class="n00b" data-text="El pobre unicornio ha muerto por tu culpa ☠️ ☠️ ☠️" /> <div class="gg" data-text="¡Bien hecho! 🎉 El unicornio ha escapado 🌈 🌈 🌈" /> </div> </div> ``` La capa `.game`, es la capa contenedora del juego. Dentro de esta es donde estará la magia ✨. La capa `.dungeon` es la capa principal, la que le da perspectiva 3D al juego, queriendo simular un efecto de punto de fuga. Las capas `.dungeon-wall-left` y `.dungeon-wall-right` son las capas que representan las paredes de la mazmorra. La capa `.n00b` es la capa que se verá cuando pierdas. Contiene el texto que se muestra cuando tocas las paredes malditas. La capa `.gg` es la capa que verás si ganas. Contiene el texto que se muestra cuando el unicornio consigue salir de la mazmorra. ## CSS Para crear el juego usaremos, entre otras cosas: - `clip-path` para darle la forma a las paredes. - `transform` para el desplazamiento y efecto 3D. - `animation` y `@keyframes` para mover y animar los elementos. - Pseudo-elementos y funciones de CSS. 🤯 La capa `.game` es solo el contenedor del juego. La capa `.dungeon` le da ese toque de perspectiva al juego. Las paredes de la mazmorra usan `background-image` con SVG para simular los ladrillos, que hemos recortado y dado forma con `clip-path`. El juego comienza cuando pones el ratón en el triángulo verde: las paredes empiezan a moverse, [el cursor](https://baumannzone.github.io/cursores-css/) se convierte en un unicornio y se inicia la animación que muestra la pantalla de victoria. El truco del juego es sencillo. Si tocas las paredes de la mazmorra (`:hover`), se muestra la pantalla de derrota. Si consigues salir de la mazmorra, se muestra la pantalla de victoria. Es así porque la animación de mostrar pantalla de victoria tiene 5 segundos de _delay_, que coincide con la duración del juego. Es decir que cuando llegas al final de la mazmorra ha pasado el tiempo necesario para que se muestre la pantalla de victoria. ```css /* Mueve las paredes durante 5 segundos */ .dungeon:hover .dungeon-wall-left, .dungeon:hover .dungeon-wall-right { animation: move-walls 5s linear; } /* Muestra la pantalla de victoria despues de 5 segundos */ .dungeon:hover .gg { animation: show-gg 0s 5s linear forwards; } ``` Al finalizar la partida verás una pantalla con texto, tanto si ganas (`.gg`) como si pierdes (`.n00b`). El texto lo sacamos del atributo `data-text` de cada capa usando la función CSS `attr()`. Sinceramente, ¡me parece super potente esta función de CSS! ```css .gg::after, .n00b::after { /* ... */ content: attr(data-text); } ``` Esto es todo lo que necesitas saber para crear un juego con CSS. Ahora te toca jugar y ver qué pasa. ¡Que lo disfrutes!
import { useState } from "react"; function useForm(inputValues = {}) { const [values, setValues] = useState(inputValues); const handleChange = (event) => { const { value, name } = event.target; setValues({ ...values, [name]: value }); }; return { values, handleChange, setValues }; } export default useForm /* Можно сделать универсальный кастомный хук для контроля любого количества инпутов в любых формах: export function useForm(inputValues={}) { const [values, setValues] = useState(inputValues); const handleChange = (event) => { const {value, name} = event.target; setValues({...values, [name]: value}); }; return {values, handleChange, setValues}; } Этот код помещают в отдельный файл useForm.js в папке hooks и импортируют функцию туда, где нужно контролировать инпуты И Вам не нужно будет теперь вручную создавать функции обработки инпутов и т д. Все будет в одной строчке кода: const {values, handleChange, setValues} = useForm({}); */
package com.northbrain.product.basic.service.impl; import com.northbrain.base.common.exception.*; import com.northbrain.base.common.model.bo.Errors; import com.northbrain.base.common.model.vo.basic.ServiceVO; import com.northbrain.base.common.model.vo.atom.ProductVO; import com.northbrain.base.common.util.StackTracerUtil; import com.northbrain.product.basic.domain.IProductDomain; import com.northbrain.product.basic.exception.ProductException; import com.northbrain.product.basic.service.IProductService; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.BadSqlGrammarException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.interceptor.TransactionAspectSupport; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Date; /** * 类名:产品服务接口的实现类 * 用途:封装产品等Domain,管理事务,并封装ServiceVO * @author Jiakun * */ @Service public class ProductService implements IProductService { private static Logger logger = Logger.getLogger(ProductService.class); private final IProductDomain productDomain; @Autowired public ProductService(IProductDomain productDomain) { this.productDomain = productDomain; } /** * 方法:创建一条产品 * * @param productVO 产品值对象 * @return 是否操作成功(用ServiceVO封装) */ @Override @Transactional public ServiceVO createProduct(ProductVO productVO) { ServiceVO serviceVO = new ServiceVO(); try { if(productVO == null) { logger.error(Errors.ERROR_BUSINESS_COMMON_ARGUMENT_INPUT_NULL + "productVO"); serviceVO.setResponseCodeAndDesc(Errors.ERROR_BUSINESS_COMMON_ARGUMENT_INPUT_EXCEPTION); return serviceVO; } if(productDomain == null) { logger.error(Errors.ERROR_BUSINESS_COMMON_OBJECT_NULL + "productDomain"); serviceVO.setResponseCodeAndDesc(Errors.ERROR_BUSINESS_COMMON_OBJECT_NULL_EXCEPTION); return serviceVO; } serviceVO.setResponse(productDomain.createProduct(productVO)); serviceVO.setResponseCodeAndDesc(Errors.SUCCESS_EXECUTE); } catch (NumberFormatException numberFormatException) { logger.error(StackTracerUtil.getExceptionInfo(numberFormatException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_SYSTEM_NUMBER_FORMAT_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (InterruptedException interruptedException) { logger.error(StackTracerUtil.getExceptionInfo(interruptedException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_SYSTEM_INTERRUPTED_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (FileNotFoundException fileNotFoundException) { logger.error(StackTracerUtil.getExceptionInfo(fileNotFoundException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_SYSTEM_FILE_NOT_FOUND_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (IOException iOException) { logger.error(StackTracerUtil.getExceptionInfo(iOException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_SYSTEM_IO_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (IllegalAccessException illegalAccessException) { logger.error(StackTracerUtil.getExceptionInfo(illegalAccessException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_SYSTEM_ILLEGAL_ACCESS_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (IllegalArgumentException illegalArgumentException) { logger.error(StackTracerUtil.getExceptionInfo(illegalArgumentException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_SYSTEM_ILLEGAL_ARGUMENT_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (ArgumentInputException argumentInputException) { logger.error(StackTracerUtil.getExceptionInfo(argumentInputException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_BUSINESS_COMMON_ARGUMENT_INPUT_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (CollectionEmptyException collectionEmptyException) { logger.error(StackTracerUtil.getExceptionInfo(collectionEmptyException)); serviceVO.setResponseCodeAndDesc(Errors.EROOR_BUSINESS_COMMON_COLLECTION_EMPTY_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (NumberScopeException numberScopeException) { logger.error(StackTracerUtil.getExceptionInfo(numberScopeException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_BUSINESS_COMMON_NUMBER_SCOPE_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (ObjectNullException objectNullException) { logger.error(StackTracerUtil.getExceptionInfo(objectNullException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_BUSINESS_COMMON_OBJECT_NULL_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (ParameterConfigException parameterConfigException) { logger.error(StackTracerUtil.getExceptionInfo(parameterConfigException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_BUSINESS_COMMON_PARAMETER_CONFIG_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (ParametersStateException parametersStateException) { logger.error(StackTracerUtil.getExceptionInfo(parametersStateException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_BUSINESS_COMMON_PARAMETER_STATUS_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (RedisSessionException redisSessionException) { logger.error(StackTracerUtil.getExceptionInfo(redisSessionException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_STORAGE_REDIS_SESSION_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (ThreadPoolExecutorException threadPoolExecutorException) { logger.error(StackTracerUtil.getExceptionInfo(threadPoolExecutorException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_SYSTEM_THREAD_POOL_EXECUTOR_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (ZooKeeperSessionException zooKeeperSessionException) { logger.error(StackTracerUtil.getExceptionInfo(zooKeeperSessionException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_STORAGE_ZOOKEEPER_SESSION_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (OperationRecordException operationRecordInsertException) { logger.error(StackTracerUtil.getExceptionInfo(operationRecordInsertException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_BUSINESS_RELATION_OPERATION_RECORD_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (BadSqlGrammarException badSqlGrammarException) { logger.error(StackTracerUtil.getExceptionInfo(badSqlGrammarException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_STORAGE_BAD_SQL_GRAMMAR_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (ProductException productException) { logger.error(StackTracerUtil.getExceptionInfo(productException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_BUSINESS_COMMON_SECURITY_STRATEGY_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (Exception exception) { logger.error(StackTracerUtil.getExceptionInfo(exception)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_OTHER_UNKNOW_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (Throwable throwable) { logger.error(StackTracerUtil.getExceptionInfo(throwable)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_OTHER_UNKNOW_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } serviceVO.setResponseTime(new Date()); return serviceVO; } /** * 方法:更新一条产品 * * @param productVO 产品值对象 * @return 是否操作成功(用ServiceVO封装) */ @Override @Transactional public ServiceVO updateProduct(ProductVO productVO) { ServiceVO serviceVO = new ServiceVO(); try { if(productVO == null) { logger.error(Errors.ERROR_BUSINESS_COMMON_ARGUMENT_INPUT_NULL + "productVO"); serviceVO.setResponseCodeAndDesc(Errors.ERROR_BUSINESS_COMMON_ARGUMENT_INPUT_EXCEPTION); return serviceVO; } if(productDomain == null) { logger.error(Errors.ERROR_BUSINESS_COMMON_OBJECT_NULL + "productDomain"); serviceVO.setResponseCodeAndDesc(Errors.ERROR_BUSINESS_COMMON_OBJECT_NULL_EXCEPTION); return serviceVO; } serviceVO.setResponse(productDomain.updateProduct(productVO)); serviceVO.setResponseCodeAndDesc(Errors.SUCCESS_EXECUTE); } catch (NumberFormatException numberFormatException) { logger.error(StackTracerUtil.getExceptionInfo(numberFormatException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_SYSTEM_NUMBER_FORMAT_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (InterruptedException interruptedException) { logger.error(StackTracerUtil.getExceptionInfo(interruptedException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_SYSTEM_INTERRUPTED_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (FileNotFoundException fileNotFoundException) { logger.error(StackTracerUtil.getExceptionInfo(fileNotFoundException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_SYSTEM_FILE_NOT_FOUND_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (IOException iOException) { logger.error(StackTracerUtil.getExceptionInfo(iOException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_SYSTEM_IO_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (IllegalAccessException illegalAccessException) { logger.error(StackTracerUtil.getExceptionInfo(illegalAccessException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_SYSTEM_ILLEGAL_ACCESS_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (IllegalArgumentException illegalArgumentException) { logger.error(StackTracerUtil.getExceptionInfo(illegalArgumentException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_SYSTEM_ILLEGAL_ARGUMENT_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (ArgumentInputException argumentInputException) { logger.error(StackTracerUtil.getExceptionInfo(argumentInputException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_BUSINESS_COMMON_ARGUMENT_INPUT_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (CollectionEmptyException collectionEmptyException) { logger.error(StackTracerUtil.getExceptionInfo(collectionEmptyException)); serviceVO.setResponseCodeAndDesc(Errors.EROOR_BUSINESS_COMMON_COLLECTION_EMPTY_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (NumberScopeException numberScopeException) { logger.error(StackTracerUtil.getExceptionInfo(numberScopeException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_BUSINESS_COMMON_NUMBER_SCOPE_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (ObjectNullException objectNullException) { logger.error(StackTracerUtil.getExceptionInfo(objectNullException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_BUSINESS_COMMON_OBJECT_NULL_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (ParameterConfigException parameterConfigException) { logger.error(StackTracerUtil.getExceptionInfo(parameterConfigException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_BUSINESS_COMMON_PARAMETER_CONFIG_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (ParametersStateException parametersStateException) { logger.error(StackTracerUtil.getExceptionInfo(parametersStateException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_BUSINESS_COMMON_PARAMETER_STATUS_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (RedisSessionException redisSessionException) { logger.error(StackTracerUtil.getExceptionInfo(redisSessionException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_STORAGE_REDIS_SESSION_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (ThreadPoolExecutorException threadPoolExecutorException) { logger.error(StackTracerUtil.getExceptionInfo(threadPoolExecutorException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_SYSTEM_THREAD_POOL_EXECUTOR_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (ZooKeeperSessionException zooKeeperSessionException) { logger.error(StackTracerUtil.getExceptionInfo(zooKeeperSessionException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_STORAGE_ZOOKEEPER_SESSION_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (OperationRecordException operationRecordInsertException) { logger.error(StackTracerUtil.getExceptionInfo(operationRecordInsertException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_BUSINESS_RELATION_OPERATION_RECORD_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (BadSqlGrammarException badSqlGrammarException) { logger.error(StackTracerUtil.getExceptionInfo(badSqlGrammarException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_STORAGE_BAD_SQL_GRAMMAR_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (ProductException productException) { logger.error(StackTracerUtil.getExceptionInfo(productException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_BUSINESS_COMMON_SECURITY_STRATEGY_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (Exception exception) { logger.error(StackTracerUtil.getExceptionInfo(exception)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_OTHER_UNKNOW_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (Throwable throwable) { logger.error(StackTracerUtil.getExceptionInfo(throwable)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_OTHER_UNKNOW_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } serviceVO.setResponseTime(new Date()); return serviceVO; } /** * 方法:删除一条产品 * * @param productVO 产品值对象 * @return 是否操作成功(用ServiceVO封装) */ @Override @Transactional public ServiceVO deleteProduct(ProductVO productVO) { ServiceVO serviceVO = new ServiceVO(); try { if(productVO == null) { logger.error(Errors.ERROR_BUSINESS_COMMON_ARGUMENT_INPUT_NULL + "productVO"); serviceVO.setResponseCodeAndDesc(Errors.ERROR_BUSINESS_COMMON_ARGUMENT_INPUT_EXCEPTION); return serviceVO; } if(productDomain == null) { logger.error(Errors.ERROR_BUSINESS_COMMON_OBJECT_NULL + "productDomain"); serviceVO.setResponseCodeAndDesc(Errors.ERROR_BUSINESS_COMMON_OBJECT_NULL_EXCEPTION); return serviceVO; } serviceVO.setResponse(productDomain.deleteProduct(productVO)); serviceVO.setResponseCodeAndDesc(Errors.SUCCESS_EXECUTE); } catch (NumberFormatException numberFormatException) { logger.error(StackTracerUtil.getExceptionInfo(numberFormatException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_SYSTEM_NUMBER_FORMAT_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (InterruptedException interruptedException) { logger.error(StackTracerUtil.getExceptionInfo(interruptedException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_SYSTEM_INTERRUPTED_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (FileNotFoundException fileNotFoundException) { logger.error(StackTracerUtil.getExceptionInfo(fileNotFoundException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_SYSTEM_FILE_NOT_FOUND_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (IOException iOException) { logger.error(StackTracerUtil.getExceptionInfo(iOException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_SYSTEM_IO_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (IllegalAccessException illegalAccessException) { logger.error(StackTracerUtil.getExceptionInfo(illegalAccessException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_SYSTEM_ILLEGAL_ACCESS_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (IllegalArgumentException illegalArgumentException) { logger.error(StackTracerUtil.getExceptionInfo(illegalArgumentException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_SYSTEM_ILLEGAL_ARGUMENT_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (ArgumentInputException argumentInputException) { logger.error(StackTracerUtil.getExceptionInfo(argumentInputException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_BUSINESS_COMMON_ARGUMENT_INPUT_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (CollectionEmptyException collectionEmptyException) { logger.error(StackTracerUtil.getExceptionInfo(collectionEmptyException)); serviceVO.setResponseCodeAndDesc(Errors.EROOR_BUSINESS_COMMON_COLLECTION_EMPTY_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (NumberScopeException numberScopeException) { logger.error(StackTracerUtil.getExceptionInfo(numberScopeException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_BUSINESS_COMMON_NUMBER_SCOPE_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (ObjectNullException objectNullException) { logger.error(StackTracerUtil.getExceptionInfo(objectNullException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_BUSINESS_COMMON_OBJECT_NULL_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (ParameterConfigException parameterConfigException) { logger.error(StackTracerUtil.getExceptionInfo(parameterConfigException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_BUSINESS_COMMON_PARAMETER_CONFIG_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (ParametersStateException parametersStateException) { logger.error(StackTracerUtil.getExceptionInfo(parametersStateException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_BUSINESS_COMMON_PARAMETER_STATUS_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (RedisSessionException redisSessionException) { logger.error(StackTracerUtil.getExceptionInfo(redisSessionException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_STORAGE_REDIS_SESSION_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (ThreadPoolExecutorException threadPoolExecutorException) { logger.error(StackTracerUtil.getExceptionInfo(threadPoolExecutorException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_SYSTEM_THREAD_POOL_EXECUTOR_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (ZooKeeperSessionException zooKeeperSessionException) { logger.error(StackTracerUtil.getExceptionInfo(zooKeeperSessionException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_STORAGE_ZOOKEEPER_SESSION_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (OperationRecordException operationRecordInsertException) { logger.error(StackTracerUtil.getExceptionInfo(operationRecordInsertException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_BUSINESS_RELATION_OPERATION_RECORD_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (BadSqlGrammarException badSqlGrammarException) { logger.error(StackTracerUtil.getExceptionInfo(badSqlGrammarException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_STORAGE_BAD_SQL_GRAMMAR_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (ProductException productException) { logger.error(StackTracerUtil.getExceptionInfo(productException)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_BUSINESS_COMMON_SECURITY_STRATEGY_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (Exception exception) { logger.error(StackTracerUtil.getExceptionInfo(exception)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_OTHER_UNKNOW_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } catch (Throwable throwable) { logger.error(StackTracerUtil.getExceptionInfo(throwable)); serviceVO.setResponseCodeAndDesc(Errors.ERROR_OTHER_UNKNOW_EXCEPTION); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } serviceVO.setResponseTime(new Date()); return serviceVO; } }
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from .models import User from .serializers import UserProfileSerializer from drf_spectacular.utils import extend_schema class UserProfileView(APIView): permission_classes = [IsAuthenticated] @extend_schema(responses=UserProfileSerializer) def get(self, request): """ Get User Profile """ serializer = UserProfileSerializer(request.user) return Response(serializer.data)
$(function() { //调用getUserInfo函数获取用户基本信息 getUserInfo() // 点击按钮,实现退出功能 var layer = layui.layer $('#btnLogout').on('click', function() { // 提示用户是否确认退出 layer.confirm('确定退出登录?', { icon: 3, title: '提示' }, function(index) { // 1.清空本地存储中的token localStorage.removeItem('token') // 2.重新跳转到登录页面 location.href = 'login.html' // 3.关闭confirm讯问框 layer.close(index); }); }) }) // 获取用户的基本信息 function getUserInfo() { $.ajax({ method: 'GET', url: '/my/userinfo', // headers就是请求头配置对象 success: function(res) { if (res.status !== 0) { return layui.layer.msg('获取用户信息失败!') } //调用renderAvatar()渲染用户头像 renderAvatar(res.data) }, // complete: function(res) { // if (res.responseJSON.status === 1 && res.responseJSON.message === '身份证失败!') { // localStorage.removeItem('token') // location.href = './login.html' // } // } }) } //渲染用户的头像 function renderAvatar(user) { // 1、获取用户的名称 var name = user.nickname || user.username // 2、设置欢迎的文本 $('#welcome').html('欢迎&nbsp;&nbsp;' + name) // 3、按需渲染用户的头像 if (user.user_pic !== null) { // 3.1渲染图片头像 $('.layui-nav-img').attr('src', user.user_pic).show() $('.text-avatar').hide() } else { // 3.2渲染文本头像 $('.layui-nav-img').hide() var first = name[0].toUpperCase() $('.text-avatar').html(first).show() } }
import { getAllDescriptorsForPart, getDescriptorLevel, getInteractionLevel, getReactionBetweenTwoItems } from '../helpers'; import { Descriptor, Interaction, IItemConfig } from '../interfaces'; const getCorroder: (level: number, corrodesLevel: number) => IItemConfig = (level: number, corrodesLevel: number) => ({ name: `Level ${level} Corroder`, parts: [ { name: 'Acid Flask', primaryDescriptor: Descriptor.Corrosive, descriptors: { [Descriptor.Corrosive]: { level } } } ], interaction: { name: Interaction.Corrodes, level: corrodesLevel } }); test('A level 2 corroder should combine with blood to make goo', () => { const source = getCorroder(1, 2); const target: IItemConfig = { name: 'Level 2 Blood', parts: [ { name: 'Blood', primaryDescriptor: Descriptor.Bloody, descriptors: { [Descriptor.Bloody]: { level: 2 } } } ] }; const result = getReactionBetweenTwoItems(source, target); expect(result.success).toBe(true); expect(getInteractionLevel(result.newSource, Interaction.Corrodes)).toEqual(1); expect(result.newTarget.parts.length).toEqual(1); expect(getDescriptorLevel(result.newTarget, Descriptor.Bloody)).toEqual(1); expect(getAllDescriptorsForPart(result.newTarget.parts[0]).length).toEqual(1); expect(result.extraItems.length).toEqual(1); expect(getDescriptorLevel(result.extraItems[0], Descriptor.Sticky)).toEqual(1); }); test('A level 2 corroder should turn level 1 blood into goo', () => { const source = getCorroder(1, 2); const target: IItemConfig = { name: 'Level 1 Blood', parts: [ { name: 'Blood', primaryDescriptor: Descriptor.Bloody, descriptors: { [Descriptor.Bloody]: { level: 1 } } } ] }; const result = getReactionBetweenTwoItems(source, target); expect(result.success).toBe(true); expect(getInteractionLevel(result.newSource, Interaction.Corrodes)).toEqual(1); expect(result.newTarget).toEqual(undefined); expect(result.extraItems.length).toEqual(1); expect(getDescriptorLevel(result.extraItems[0], Descriptor.Sticky)).toEqual(1); }); test('A level 2 corroder should partially dissolve level 2 clay', () => { const source = getCorroder(1, 2); const target: IItemConfig = { name: 'Level 2 Clay', parts: [ { name: 'Clay', primaryDescriptor: Descriptor.Clay, descriptors: { [Descriptor.Clay]: { level: 2 } } } ] }; const result = getReactionBetweenTwoItems(source, target); expect(result.success).toBe(true); expect(getInteractionLevel(result.newSource, Interaction.Corrodes)).toEqual(1); expect(result.newTarget.parts.length).toEqual(1); expect(getDescriptorLevel(result.newTarget, Descriptor.Clay)).toEqual(1); expect(getAllDescriptorsForPart(result.newTarget.parts[0]).length).toEqual(1); }); test('A level 2 corroder should fully dissolve level 1 clay', () => { const source = getCorroder(1, 2); const target: IItemConfig = { name: 'Level 1 Clay', parts: [ { name: 'Clay', primaryDescriptor: Descriptor.Clay, descriptors: { [Descriptor.Clay]: { level: 1 } } } ] }; const result = getReactionBetweenTwoItems(source, target); expect(result.success).toBe(true); expect(getInteractionLevel(result.newSource, Interaction.Corrodes)).toEqual(1); expect(result.newTarget).toEqual(undefined); }); test('A level 2 corroder should partially dissolve level 2 dirt', () => { const source = getCorroder(1, 2); const target: IItemConfig = { name: 'Level 2 Dirt', parts: [ { name: 'Dirt', primaryDescriptor: Descriptor.Dirt, descriptors: { [Descriptor.Dirt]: { level: 2 } } } ] }; const result = getReactionBetweenTwoItems(source, target); expect(result.success).toBe(true); expect(getInteractionLevel(result.newSource, Interaction.Corrodes)).toEqual(1); expect(result.newTarget.parts.length).toEqual(1); expect(getDescriptorLevel(result.newTarget, Descriptor.Dirt)).toEqual(1); expect(getAllDescriptorsForPart(result.newTarget.parts[0]).length).toEqual(1); }); test('A level 2 corroder should fully dissolve level 1 dirt', () => { const source = getCorroder(1, 2); const target: IItemConfig = { name: 'Level 1 Dirt', parts: [ { name: 'Dirt', primaryDescriptor: Descriptor.Dirt, descriptors: { [Descriptor.Dirt]: { level: 1 } } } ] }; const result = getReactionBetweenTwoItems(source, target); expect(result.success).toBe(true); expect(getInteractionLevel(result.newSource, Interaction.Corrodes)).toEqual(1); expect(result.newTarget).toEqual(undefined); }); test('A level 2 corroder should partially dissolve level 2 fiber', () => { const source = getCorroder(1, 2); const target: IItemConfig = { name: 'Level 2 Fiber', parts: [ { name: 'Fiber', primaryDescriptor: Descriptor.Fiber, descriptors: { [Descriptor.Fiber]: { level: 2 } } } ] }; const result = getReactionBetweenTwoItems(source, target); expect(result.success).toBe(true); expect(getInteractionLevel(result.newSource, Interaction.Corrodes)).toEqual(1); expect(result.newTarget.parts.length).toEqual(1); expect(getDescriptorLevel(result.newTarget, Descriptor.Fiber)).toEqual(1); expect(getAllDescriptorsForPart(result.newTarget.parts[0]).length).toEqual(1); }); test('A level 2 corroder should fully dissolve level 1 fiber', () => { const source = getCorroder(1, 2); const target: IItemConfig = { name: 'Level 1 Fiber', parts: [ { name: 'Fiber', primaryDescriptor: Descriptor.Fiber, descriptors: { [Descriptor.Fiber]: { level: 1 } } } ] }; const result = getReactionBetweenTwoItems(source, target); expect(result.success).toBe(true); expect(getInteractionLevel(result.newSource, Interaction.Corrodes)).toEqual(1); expect(result.newTarget).toEqual(undefined); }); test('A level 2 corroder should not affect normal glass', () => { const source = getCorroder(1, 2); const target: IItemConfig = { name: 'Level 99 Glass', parts: [ { name: 'Glass', primaryDescriptor: Descriptor.Glass, descriptors: { [Descriptor.Glass]: { level: 99 } } } ] }; const result = getReactionBetweenTwoItems(source, target); expect(result.success).toBe(false); }); test('A level 2 corroder poured into a glass container should create an acid flask', () => { const source = getCorroder(1, 2); const target: IItemConfig = { name: 'Level 3 Glass Bottle', parts: [ { name: 'Glass Bottle', primaryDescriptor: Descriptor.Glass, foundational: true, descriptors: { [Descriptor.Glass]: { level: 3 }, [Descriptor.Container]: { level: 1 } } } ] }; const result = getReactionBetweenTwoItems(source, target); expect(result.success).toBe(true); expect(getInteractionLevel(result.newSource, Interaction.Corrodes)).toEqual(1); expect(result.newTarget).toEqual(undefined); expect(result.extraItems.length).toEqual(1); expect(result.extraItems[0].parts.length).toEqual(2); expect(getDescriptorLevel(result.extraItems[0], Descriptor.Corrosive)).toEqual(1); expect(getDescriptorLevel(result.extraItems[0], Descriptor.Glass)).toEqual(3); }); test('A level 2 corroder should damage level 2 leather', () => { const source = getCorroder(1, 2); const target: IItemConfig = { name: 'Level 2 Leather', parts: [ { name: 'Leather', primaryDescriptor: Descriptor.Leather, descriptors: { [Descriptor.Leather]: { level: 2 } } } ] }; const result = getReactionBetweenTwoItems(source, target); expect(result.success).toBe(true); expect(getInteractionLevel(result.newSource, Interaction.Corrodes)).toEqual(1); expect(result.newTarget.parts.length).toEqual(1); expect(getDescriptorLevel(result.newTarget, Descriptor.Leather)).toEqual(1); expect(getAllDescriptorsForPart(result.newTarget.parts[0]).length).toEqual(1); }); test('A level 2 corroder should destroy level 1 leather', () => { const source = getCorroder(1, 2); const target: IItemConfig = { name: 'Level 1 Leather', parts: [ { name: 'Leather', primaryDescriptor: Descriptor.Leather, descriptors: { [Descriptor.Leather]: { level: 1 } } } ] }; const result = getReactionBetweenTwoItems(source, target); expect(result.success).toBe(true); expect(getInteractionLevel(result.newSource, Interaction.Corrodes)).toEqual(1); expect(result.newTarget).toEqual(undefined); }); test('A level 2 corroder should turn raw meat into rotten meat', () => { const source = getCorroder(1, 2); const target: IItemConfig = { name: 'Level 99 Meat Slab', parts: [ { name: 'Meat', primaryDescriptor: Descriptor.Meat, descriptors: { [Descriptor.Meat]: { level: 99 } } } ] }; const result = getReactionBetweenTwoItems(source, target); expect(result.success).toBe(true); expect(getInteractionLevel(result.newSource, Interaction.Corrodes)).toEqual(1); expect(result.newTarget).toEqual(undefined); expect(result.extraItems.length).toEqual(1); expect(getDescriptorLevel(result.extraItems[0], Descriptor.Rotten)).toEqual(1); }); test('A level 2 corroder should turn cooked meat into rotten meat', () => { const source = getCorroder(1, 2); const target: IItemConfig = { name: 'Level 99 Ribeye Steak', parts: [ { name: 'Steak', primaryDescriptor: Descriptor.Meat, descriptors: { [Descriptor.Meat]: { level: 0 }, [Descriptor.Cooked]: { level: 99 } } } ] }; const result = getReactionBetweenTwoItems(source, target); expect(result.success).toBe(true); expect(getInteractionLevel(result.newSource, Interaction.Corrodes)).toEqual(1); expect(result.newTarget).toEqual(undefined); expect(result.extraItems.length).toEqual(1); expect(getDescriptorLevel(result.extraItems[0], Descriptor.Rotten)).toEqual(1); }); test('A level 2 corroder should tarnish level 2 metal', () => { const source = getCorroder(1, 2); const target: IItemConfig = { name: 'Level 2 Steel', parts: [ { name: 'Steel', primaryDescriptor: Descriptor.Metal, descriptors: { [Descriptor.Metal]: { level: 2 } } } ] }; const result = getReactionBetweenTwoItems(source, target); expect(result.success).toBe(true); expect(getInteractionLevel(result.newSource, Interaction.Corrodes)).toEqual(1); expect(result.newTarget.parts.length).toEqual(1); expect(getDescriptorLevel(result.newTarget, Descriptor.Metal)).toEqual(1); expect(getAllDescriptorsForPart(result.newTarget.parts[0]).length).toEqual(1); }); test('A level 2 corroder should destroy level 1 metal', () => { const source = getCorroder(1, 2); const target: IItemConfig = { name: 'Level 1 Steel', parts: [ { name: 'Steel', primaryDescriptor: Descriptor.Metal, descriptors: { [Descriptor.Metal]: { level: 1 } } } ] }; const result = getReactionBetweenTwoItems(source, target); expect(result.success).toBe(true); expect(getInteractionLevel(result.newSource, Interaction.Corrodes)).toEqual(1); expect(result.newTarget).toEqual(undefined); }); test('A level 2 corroder should partially dissolve level 2 mud', () => { const source = getCorroder(1, 2); const target: IItemConfig = { name: 'Level 2 Mud', parts: [ { name: 'Mud', primaryDescriptor: Descriptor.Mud, descriptors: { [Descriptor.Mud]: { level: 2 } } } ] }; const result = getReactionBetweenTwoItems(source, target); expect(result.success).toBe(true); expect(getInteractionLevel(result.newSource, Interaction.Corrodes)).toEqual(1); expect(result.newTarget.parts.length).toEqual(1); expect(getDescriptorLevel(result.newTarget, Descriptor.Mud)).toEqual(1); expect(getAllDescriptorsForPart(result.newTarget.parts[0]).length).toEqual(1); }); test('A level 2 corroder should fully dissolve level 1 mud', () => { const source = getCorroder(1, 2); const target: IItemConfig = { name: 'Level 1 Mud', parts: [ { name: 'Mud', primaryDescriptor: Descriptor.Mud, descriptors: { [Descriptor.Mud]: { level: 1 } } } ] }; const result = getReactionBetweenTwoItems(source, target); expect(result.success).toBe(true); expect(getInteractionLevel(result.newSource, Interaction.Corrodes)).toEqual(1); expect(result.newTarget).toEqual(undefined); }); test('A level 2 corroder should reduce wetness', () => { const source = getCorroder(1, 2); const target: IItemConfig = { name: 'Wet Rock', parts: [ { name: 'Wet Rock', primaryDescriptor: Descriptor.Wet, foundational: true, descriptors: { [Descriptor.Rock]: { level: 99 }, [Descriptor.Wet]: { level: 2 } } } ] }; const result = getReactionBetweenTwoItems(source, target); expect(result.success).toBe(true); expect(getInteractionLevel(result.newSource, Interaction.Corrodes)).toEqual(1); expect(result.newTarget.parts.length).toEqual(1); expect(getDescriptorLevel(result.newTarget, Descriptor.Wet)).toEqual(1); expect(getAllDescriptorsForPart(result.newTarget.parts[0]).length).toEqual(2); }); test('A level 2 corroder should rot level 2 wood', () => { const source = getCorroder(1, 2); const target: IItemConfig = { name: 'Level 2 Wood', parts: [ { name: 'Wood', primaryDescriptor: Descriptor.Wood, descriptors: { [Descriptor.Wood]: { level: 2 } } } ] }; const result = getReactionBetweenTwoItems(source, target); expect(result.success).toBe(true); expect(getInteractionLevel(result.newSource, Interaction.Corrodes)).toEqual(1); expect(result.newTarget.parts.length).toEqual(1); expect(getDescriptorLevel(result.newTarget, Descriptor.Rotten)).toEqual(1); expect(getAllDescriptorsForPart(result.newTarget.parts[0]).length).toEqual(2); }); test('A level 2 corroder should destroy level 1 rotten wood', () => { const source = getCorroder(1, 2); const target: IItemConfig = { name: 'Level 1 Rotten Wood', parts: [ { name: 'Rotten Wood', primaryDescriptor: Descriptor.Wood, descriptors: { [Descriptor.Wood]: { level: 1 }, [Descriptor.Rotten]: { level: 1 } } } ] }; const result = getReactionBetweenTwoItems(source, target); expect(result.success).toBe(true); expect(getInteractionLevel(result.newSource, Interaction.Corrodes)).toEqual(1); expect(result.newTarget).toEqual(undefined); });
<?php namespace App\Http\Controllers; use App\Models\Venta; use Illuminate\Http\Request; class VentaController extends Controller { public function show(){ $items = Venta::where('activo', true)->get(); if ($items->count() > 0) { return response()->json($items); } else { return response()->json([ 'message' => 'No records found' ], 200); } } public function getById(int $id) { $item = Venta::where('id', $id)->get(); if ($item->count() > 0) { return response()->json($item); } else { return response()->json([ 'message' => 'No records found' ], 200); } } public function create(Request $request) { $item = new Venta(); $item->client_id = $request->client_id; $item->worker_id = $request->worker_id; $item->fecha = $request->fecha; $item->tipo_comprobante = $request->tipo_comprobante; $item->serie = $request->serie; $item->correlativo = $request->correlativo; $item->save(); return "La venta se registro exitosamente"; } public function update(Request $request, int $id) { $item = Venta::find($id); if ($item) { $item->client_id = $request->client_id; $item->worker_id = $request->worker_id; $item->fecha = $request->fecha; $item->tipo_comprobante = $request->tipo_comprobante; $item->serie = $request->serie; $item->correlativo = $request->correlativo; $item->save(); return "La venta se ha modificado !! "; } else { return response()->json([ 'message' => 'No records found' ], 200); } } public function delete(int $id) { $item = Venta::find($id); if ($item) { $item->activo = 0; $item->save(); return "La venta se ha borrado !! "; } else { return response()->json([ 'message' => 'No records found' ], 200); } } }
This is the source code of the Linux/Unix version of David Radford's Data Analysis Software. Latest update: 7 Dec 2020 This release is portable between linux, Mac OS X, and many unix variants. For more details on installing in Mac OS X you may wish to look at README.macosx. A brief description of what each program does is in the file doc/aa_radware.lis. More documentation can also be found at http://radware.phy.ornl.gov/ and in other files in the doc directory. You can find demonstration data files in the demo directory. To compile rw05, you should be able to use almost any C compiler. == To download the source code: == From github: The rw05 git repository is on https://github.com/dcr-radware/rw05 By svn: ======= An less-frequently-updated version is available using Subversion (svn). If you have svn installed, you can use the command svn co https://radware.phy.ornl.gov/rw05 to check out the latest rw05 source tree. == Required Software Development Packages: == Radware will be compiled from scratch. That means that you need to have some "development packages" installed on your system, or the compile will fail. You will always want to have readline and X11 installed. If you want to use GUI versions of gls, escl8r, levit8r and 4dg8r, then you will also need GTK2 and/or lesstif (or openmotif) packages installed. On some modern linux distributions, you will also need to install X11 fonts. On my Kubuntu system, I need at least to install the following: gcc (C compiler) make (to build the programs) libreadline-dev libgtk2.0-dev lesstif2-dev == To Compile: == There is a separate README files for Mac OS X, namely README.macosx. If you are installing on a mac, read that file too. 1) Type: cd rw05/src cp Makefile.sys Makefile where "sys" corresponds tpo your system, namely "linux", "macosx", "solaris", etc. Edit the top level Makefile (the one you just made with the cp command). If needed, change any of the lines that depend specifically on your local filesystem, for example the definitions of X_WIN_TOP and MOTIF_TOP. Change INSTALL_DIR, INSTALL and INSTALL_BIN if you wish to install the files in a separate directory (see step 4). 2) RadWare can read spectra from ORNL-format .his histogram files. Most users will not be interested in this feature; if this includes you, skip to step 3. If you want to be able to read .his files, your system needs to have the ORPHLIB library installed, and you need to change your Makefile to link some of the programs with orphlib.a and some FORTRAN run-time libraries. Here is what you need to do: Edit your top level Makefile, and uncomment the line that defines HISLIBS, changing the FORTRAN libraries and the location of orphlib.a as needed. If (and only if) orphlib.a was compiled with g77, you also need to uncomment the line redefining FC = g77 3) To make the standard (non-GUI) codes, type: make all If your system is missing development libraries, such as X11 or readline, the make will fail. There will be compile errors, usually beginning with something like "error: readline/readline.h: No such file or directory" If this happens, speak to your system administrator, and/or try to find out whcih packages to install, and how to do it. GTK versions: If your system has the GTK2 development libraries installed, and you wish to use the GTK versions of gls, escl8r, etc., then type: make gtk Motif versions If your system has the Motif development libraries installed, and you wish to use the Motif versions of gf3, gls, escl8r, etc., then type: make xm 4) You can install the executables and data files in a separate directory. THIS IS NOT NECESSARY to run the programs; if you choose not to do the install, you can just run them directly from the src directory of steps 1) and 3). To install, check the definition of INSTALL_DIR, INSTALL and INSTALL_BIN in the Makefile and type: make install If the install fails for some reason, try editing your top level Makefile, to replace the line near the end: include Makefile.install_sysv or include Makefile.install_ucb by: include Makefile.install_cp and try again. 5) Edit the .radwarerc file so that the pathname variables are properly defined to $(INSTALL_DIR)/font, etc., or whatever. These definitions will allow the various programs to find files that they need, such as icc/icctbl.dat, font/font.dat, and doc/gfonline.hlp. There are some other environment variables in there, too, that you might like to play with. See WHATS_NEW for details. .radwarerc can be found in either the src directory, or in $(INSTALL_DIR). There is also a bash version, .radware.bashrc, for those who prefer bash to tcsh or csh. 6) Make sure that your .login, .bashrc, or .cshrc, or the system .login, includes source $(INSTALL_DIR)/.radwarerc or copy the .radwarerc to your home directory and have it executed from there. Also make sure that $(INSTALL_DIR)/bin (or the src directory, if you didn't do the install) is in your path. Then you are set to go; try gf3, gtkgls etc. Have a look in the demo directory for sample files. You should also copy demo/gfinit.dat into your home directory. 7) To clean up the source directory: make clean To clean up the source and all subdirectories, leaving only the source code: make very-clean ------------------------------------------------------------------- Please send any bug reports and suggestions to radforddc@ornl.gov ------------------------------------------------------------------- D.C. Radford Dec 2020
using LocationAPI.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Threading.Tasks; namespace LocationAPI.Controllers { [ApiController] [Route("api/[controller]")] public class LocationController : ControllerBase { private readonly ILocationService _locationService; private readonly ILogger<LocationController> _logger; public LocationController(ILocationService locationService, ILogger<LocationController> logger) { _locationService = locationService ?? throw new ArgumentNullException(nameof(locationService)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } /// <summary> /// Get location information by IP address. /// </summary> /// <param name="ipAddress">The IP address to look up.</param> /// <returns>Returns location information if found, otherwise NotFound.</returns> [HttpGet("{ipAddress}")] public async Task<IActionResult> GetLocation(string ipAddress) { try { var location = await _locationService.GetLocationByIpAddressAsync(ipAddress); if (location == null) { _logger.LogWarning($"Location not found for IP address: {ipAddress}"); return NotFound(); } return Ok(location); } catch (Exception ex) { _logger.LogError($"An error occurred while processing the request: {ex.Message}"); return StatusCode(500, "An error occurred while processing the request."); } } } }
import * as anchor from "@project-serum/anchor"; // ** Comment this to use solpg imported IDL ** import { MintNft } from "../target/types/mint_nft"; describe("nft-marketplace", async () => { const testNftTitle = "Beta"; const testNftSymbol = "BETA"; const testNftUri = "https://raw.githubusercontent.com/Coding-and-Crypto/Solana-NFT-Marketplace/master/assets/example.json"; const provider = anchor.AnchorProvider.env() const wallet = provider.wallet as anchor.Wallet; anchor.setProvider(provider); // ** Un-comment this to use solpg imported IDL ** const program = new anchor.Program( require("../solpg/idl.json"), new anchor.web3.PublicKey("7NpT6MAcQXSAVWvAAxMHLrouHhjX93JXg1xHAtJHAbhm"), ); // ** Comment this to use solpg imported IDL ** const TOKEN_METADATA_PROGRAM_ID = new anchor.web3.PublicKey( "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s" ); it("Mint!", async () => { // Derive the mint address and the associated token account address const mintKeypair: anchor.web3.Keypair = anchor.web3.Keypair.generate(); const tokenAddress = await anchor.utils.token.associatedAddress({ mint: mintKeypair.publicKey, owner: wallet.publicKey }); console.log(`New token: ${mintKeypair.publicKey}`); // Derive the metadata and master edition addresses const metadataAddress = (await anchor.web3.PublicKey.findProgramAddress( [ Buffer.from("metadata"), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mintKeypair.publicKey.toBuffer(), ], TOKEN_METADATA_PROGRAM_ID ))[0]; console.log("Metadata initialized"); const masterEditionAddress = (await anchor.web3.PublicKey.findProgramAddress( [ Buffer.from("metadata"), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mintKeypair.publicKey.toBuffer(), Buffer.from("edition"), ], TOKEN_METADATA_PROGRAM_ID ))[0]; console.log("Master edition metadata initialized"); // Transact with the "mint" function in our on-chain program await program.methods.mint( testNftTitle, testNftSymbol, testNftUri ) .accounts({ masterEdition: masterEditionAddress, metadata: metadataAddress, mint: mintKeypair.publicKey, tokenAccount: tokenAddress, mintAuthority: wallet.publicKey, tokenMetadataProgram: TOKEN_METADATA_PROGRAM_ID, }) .signers([mintKeypair]) .rpc(); }); });
using FluentValidation; using ImageHub.Api.Features.Images.AddImage; using ImageHub.Api.Infrastructure.Behaviors; using ImageHub.Api.Infrastructure.MessageBroker; using ImageHub.Api.Infrastructure.Middlewares; using ImageHub.Api.Infrastructure.Persistence; using ImageHub.Api.Infrastructure.Services; using MassTransit; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; using Serilog; namespace ImageHub.Api.Infrastructure; public static class InfrastructureExtnesions { public static WebApplicationBuilder RegisterInfrastructureServices(this WebApplicationBuilder builder) { builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddProblemDetails(); var assembly = typeof(Program).Assembly; builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseNpgsql(builder.Configuration.GetConnectionString("Database"))); builder.Services.AddCarter(); builder.Services.AddValidatorsFromAssembly(assembly); builder.Services.AddExceptionHandler<GlobalExceptionHandler>(); builder.Services.AddTransient<TimingMiddleware>(); builder.Services.AddDistributedMemoryCache(); builder.Services.AddSingleton<ICacheService, CacheService>(); builder.Services.AddHostedService<ProcessingMonitorService>(); builder.Services.AddMediatR(config => config.RegisterServicesFromAssembly(assembly)); builder.Services.AddScoped(typeof(IPipelineBehavior<,>), typeof(LoggingBehaviour<,>)); builder.Services.AddScoped(typeof(IPipelineBehavior<,>), typeof(ValidationBehaviour<,>)); builder.Host.UseSerilog((context, configuration) => configuration.ReadFrom.Configuration(context.Configuration)); builder.Services.Configure<MessageBrokerSettings>( builder.Configuration.GetSection("MessageBroker")); builder.Services.AddSingleton(sp => sp.GetRequiredService<IOptions<MessageBrokerSettings>>().Value); builder.Services.AddMassTransit(bus => { bus.SetKebabCaseEndpointNameFormatter(); bus.AddConsumer<AddImageEventConsumer>(); bus.UsingRabbitMq((context,config) => { var settings = context.GetRequiredService<MessageBrokerSettings>(); config.ReceiveEndpoint("addimage", endpoint => { endpoint.ConfigureConsumer<AddImageEventConsumer>(context); }); config.Host(new Uri(settings.Host), host => { host.Username(settings.Username); host.Password(settings.Password); }); }); }); builder.Services.AddTransient<IEventBus, EventBus>(); builder.Services.AddSignalR(); return builder; } public static WebApplication UseInfrastructure(this WebApplication app) { if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } else { app.UseHttpsRedirection(); } app.UseMiddleware<TimingMiddleware>(); app.UseExceptionHandler(); app.UseRouting(); app.MapCarter(); return app; } }
<?php namespace App\Http\Controllers\API; use App\Http\Controllers\Controller; use App\Models\Product; use Illuminate\Http\Request; use Validator; class ProductController extends Controller { //List/show books public function index() { $products = Product::latest()->get(); if (is_null($products->first())) { return response()->json([ 'status' => 'failed', 'message' => 'No product found!', ], 200); } $response = [ 'status' => 'success', 'message' => 'Products are retrieved successfully.', 'data' => $products, ]; return response()->json($response, 200); } public function store(Request $request) { //add new book $validate = Validator::make($request->all(), [ 'title' => 'required|string|max:250', 'author' => 'required|string|max:50', 'price' => 'required|string|' ]); if($validate->fails()){ return response()->json([ 'status' => 'failed', 'message' => 'Validation Error!', 'data' => $validate->errors(), ], 403); } $product = Product::create($request->all()); $response = [ 'status' => 'success', 'message' => 'Product is added successfully.', 'data' => $product, ]; return response()->json($response, 200); } public function show($id) { //showing book bby ID $product = Product::find($id); if (is_null($product)) { return response()->json([ 'status' => 'failed', 'message' => 'Product is not found!', ], 200); } $response = [ 'status' => 'success', 'message' => 'Product is retrieved successfully.', 'data' => $product, ]; return response()->json($response, 200); } public function update(Request $request, $id) { //edit book by ID $validate = Validator::make($request->all(), [ 'title' => 'required', 'author' => 'required', 'price' => 'required' ]); if($validate->fails()){ return response()->json([ 'status' => 'failed', 'message' => 'Validation Error!', 'data' => $validate->errors(), ], 403); } $product = Product::find($id); if (is_null($product)) { return response()->json([ 'status' => 'failed', 'message' => 'Product is not found!', ], 200); } $product->update($request->all()); $response = [ 'status' => 'success', 'message' => 'Product is updated successfully.', 'data' => $product, ]; return response()->json($response, 200); } public function destroy($id) { //Deleting book by ID $product = Product::find($id); if (is_null($product)) { return response()->json([ 'status' => 'failed', 'message' => 'Product is not found!', ], 200); } Product::destroy($id); return response()->json([ 'status' => 'success', 'message' => 'Product is deleted successfully.' ], 200); } public function search($title) { //searching book by name $products = Product::where('title', 'like', '%'.$title.'%') ->latest()->get(); if (is_null($products->first())) { return response()->json([ 'status' => 'failed', 'message' => 'No product found!', ], 200); } $response = [ 'status' => 'success', 'message' => 'Products are retrieved successfully.', 'data' => $products, ]; return response()->json($response, 200); } }
import React, { useState, useEffect } from "react"; import "./Questions.css"; import questions from "./Question-data"; import { BrowserRouter as Router, Link } from "react-router-dom"; function Questions() { const [list, setList] = useState([]); const [currentPage, setCurrentPage] = useState(1); const [pageSize, setPageSize] = useState(15); const pageSizeOptions = [15, 30, 50]; const handleChangePageSize = (size) => { setPageSize(size); setCurrentPage(1); }; const handlePageClick = (page) => { setCurrentPage(page); }; useEffect(() => { const storedList = JSON.parse(localStorage.getItem("questionList")); if (storedList) { setList(storedList); } else { localStorage.setItem("questionList", JSON.stringify(questions)); setList(questions); } }, []); const totalPages = Math.ceil(list.length / pageSize); const visiblePages = 5; // number of pagination buttons to show const getPageRange = () => { let startPage = Math.max(1, currentPage - Math.floor(visiblePages / 2)); let endPage = Math.min(totalPages, startPage + visiblePages - 1); if (endPage - startPage < visiblePages - 1) { startPage = Math.max(1, endPage - visiblePages + 1); } return [...Array(endPage - startPage + 1).keys()].map((i) => startPage + i); }; const paginatedList = list.slice((currentPage - 1) * pageSize, currentPage * pageSize); return ( <div> <div id="mainbar"> <div className="d-flex mb12"> <h1 className="fs-headline1">All Questions</h1> <div className="margin-top-10 aside-cta mb12"> <Link to={`/addquestion`} className="btn btn-primary"> Ask Question </Link> </div> </div> <div className="d-flex mb12"> <div className="fs-body3 fl1">{questions.length} questions</div> <div className="uql-nav "> <div className="d-flex"> <div className="btn-group"> <a className="btn sm-btn-border sm-btn d-flex is-selected"> {" "} Newest{" "} </a> <a className="btn sm-btn-border sm-btn d-flex"> Active </a> <a className="btn sm-btn-border sm-btn d-flex uql-nav--expanded-item"> Bountied <div className="s-badge">212</div> </a> <a className="btn sm-btn-border sm-btn d-flex">Unanswered</a> <button className="btn sm-btn-border sm-btn border-right-inset"> More </button> </div> <div> <button className="btn filter-button sm-btn btn-icon"> <svg className="svg-icon" width="18" height="18"> <path d="M2 4h14v2H2V4Zm2 4h10v2H4V8Zm8 4H6v2h6v-2Z"></path> </svg> Filter </button> </div> </div> </div> </div> </div> <div className="list-margin" data-testid='list'> {paginatedList.map((question) => ( <div className="question" id='list'> <div className="question-stats"> <div className="question-stats-item question-stats-item__emphasized"> <span className="question-stats-item-number"> {question?.votes[0]?.up + question?.votes[0]?.down} </span> <span className="question-stats-item-unit">votes</span> </div> <div className="question-stats-item"> <span className="question-stats-item-number">0</span> <span className="question-stats-item-unit">answers</span> </div> <div className="question-stats-item" title="2 views"> <span className="question-stats-item-number">2</span> <span className="question-stats-item-unit">views</span> </div> </div> <div className="question-content"> <h3 className="question-content-title"> <Link to={`/question/${question.id}`} className="s-link"> {question.title} </Link> </h3> <div className="question-content-excerpt"> <div dangerouslySetInnerHTML={{ __html: question.body }} /> </div> <div className=""> <div> {question.skills.map((chipText) => ( <div className="chip">{chipText.label}</div> ))} </div> <div className="user-card float-right "> <div className="user-card-info"> <div className="user-card-link d-flex gs4"> <a > Erik_90x{" "} <time className="user-card-time"> asked 1 min ago </time> </a> </div> </div> </div> </div> </div> </div> ))} <div className="pagination site1 themed page-sizer float-right"> {pageSizeOptions.map((size) => ( <a key={size} onClick={() => handleChangePageSize(size)} title={`Show ${size} items per page`} className={`pagination-content ${pageSize === size ? "is-selected" : ""}`} > {size} </a> ))} <span className="pagination-content pagination-content-clear">per page</span> </div> <div className="pagination site1 themed pager float-left"> {/* <div className="pagination-content is-selected" aria-current="page"> {currentPage} </div> */} {getPageRange().map((page) => ( <a key={page} href="#" onClick={() => handlePageClick(page)} className={`pagination-content jpagination-item ${ currentPage === page ? "is-selected" : "" }`} > {page} </a> ))} {currentPage < totalPages && ( <a onClick={() => handlePageClick(currentPage + 1)} className="pagination-content jpagination-item" rel="next" title="Go to next page" > Next </a> )} </div> </div> </div> ); } export default Questions;
import { useDispatch, useSelector } from "react-redux"; import "./App.css"; import { decrement, increment, incrementCustom, } from "./redux/features/counter/counterSlice"; import { useEffect } from "react"; import { getCountry } from "./redux/features/country/countrySlice"; function App() { const dispatch = useDispatch(); console.log(useSelector((state) => state)); const { counter } = useSelector((state) => state.counter); const { country, loading } = useSelector((state) => state.country); console.log(country); useEffect(() => { dispatch(getCountry()); }, []); return ( <div className="App"> <span onClick={() => dispatch(decrement())}>-</span> <span>{counter}</span> <span onClick={() => dispatch(increment())}>+</span> <span onClick={() => dispatch(incrementCustom(2))}>custom</span> </div> ); } export default App;
package ru.netology.nmedia.ui.event import android.content.Intent import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.OnBackPressedCallback import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.annotation.RequiresApi import androidx.core.net.toFile import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.navigation.fragment.findNavController import com.github.dhaval2404.imagepicker.ImagePicker import com.google.android.material.snackbar.Snackbar import ru.netology.nmedia.R import ru.netology.nmedia.databinding.FragmentNewEventBinding import ru.netology.nmedia.enumeration.AttachmentType import ru.netology.nmedia.enumeration.EventType import ru.netology.nmedia.ui.DatePickerFragment import ru.netology.nmedia.ui.TimePickerFragment import ru.netology.nmedia.util.AndroidUtils import ru.netology.nmedia.viewmodel.EventViewModel import java.util.Calendar class NewEventFragment : Fragment() { private val viewModel: EventViewModel by activityViewModels() private var imageLauncher: ActivityResultLauncher<Intent>? = null private val onBackPressedCallback: OnBackPressedCallback = object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { viewModel.clearEdited() findNavController().navigateUp() } } @RequiresApi(Build.VERSION_CODES.O) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val binding = FragmentNewEventBinding.inflate(inflater, container, false) binding.eventGroup.isVisible = true requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, onBackPressedCallback) val event = viewModel.getEditEvent() event?.let { binding.editNewPost.setText(it.content) binding.textDate.text = AndroidUtils.formatDate(it.datetime) binding.textViewTime.text = AndroidUtils.formatTime(it.datetime) if (it.type == EventType.OFFLINE) { binding.offline.isChecked = true } else { binding.online.isChecked = true } binding.editTextLink.setText(it.link) if (it.attachment?.type == AttachmentType.IMAGE) { binding.textViewImage.text = it.attachment.url } } binding.createPost.setOnClickListener { val content = binding.editNewPost.text.toString() val datetime = if (binding.textDate.text.isNotBlank() && binding.textViewTime.text.isNotBlank()) { binding.textDate.text.toString() + "T" + binding.textViewTime.text.toString() + ":00.000000Z" } else event?.datetime ?: "" if (datetime.isBlank()) { Snackbar.make( binding.root, R.string.empty_date, Snackbar.LENGTH_LONG ).show() return@setOnClickListener } val eventType = if (binding.offline.isChecked) { EventType.OFFLINE } else { EventType.ONLINE } val link = AndroidUtils.checkLink(binding.editTextLink.text.toString()) if (link == "") { Snackbar.make(binding.root, R.string.invalid_link, Snackbar.LENGTH_LONG).show() return@setOnClickListener } viewModel.changeContent( content = content, datetime = datetime, eventType = eventType, link = link, ) viewModel.save() AndroidUtils.hideKeyboard(requireView()) } viewModel.eventCreated.observe(viewLifecycleOwner) { findNavController().navigateUp() } binding.addDate.setOnClickListener { val datePickerFragment = DatePickerFragment { day, month, year -> val selectedDate = Calendar.getInstance() selectedDate.set(Calendar.YEAR, year) selectedDate.set(Calendar.MONTH, month - 1) selectedDate.set(Calendar.DAY_OF_MONTH, day) val date = AndroidUtils.formatDatePicker(selectedDate.time) binding.textDate.text = date } datePickerFragment.show(childFragmentManager, "datePicker") } binding.addTime.setOnClickListener { val timePickerFragment = TimePickerFragment { hour, minute -> val selectedTime = Calendar.getInstance() selectedTime.set(Calendar.HOUR_OF_DAY, hour) selectedTime.set(Calendar.MINUTE, minute) val time = AndroidUtils.formatTimePicker(selectedTime.time) binding.textViewTime.text = time } timePickerFragment.show(childFragmentManager, "timePicker") } imageLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { when (it.resultCode) { ImagePicker.RESULT_ERROR -> { Snackbar.make(binding.root, R.string.error_loading, Snackbar.LENGTH_LONG) .show() } else -> { val uri = it.data?.data ?: return@registerForActivityResult viewModel.addMedia(uri, uri.toFile(), AttachmentType.IMAGE) } } } binding.addImageButton.setOnClickListener { ImagePicker.with(this) .crop() .compress(2048) .createIntent(imageLauncher!!::launch) } binding.clearImage.setOnClickListener { viewModel.clearMedia() } viewModel.media.observe(viewLifecycleOwner) { media -> media?.let { binding.textViewImage.text = media.file.name } } return binding.root } override fun onDestroyView() { super.onDestroyView() imageLauncher = null } }
--- title: "\"From Silence to Soundscape Embedding MP3s in Presentations\"" date: 2024-05-24T06:52:04.492Z updated: 2024-05-25T06:52:04.492Z tags: - screen-recording - ai video - ai audio - ai auto categories: - ai - screen description: "\"This Article Describes From Silence to Soundscape: Embedding MP3s in Presentations\"" excerpt: "\"This Article Describes From Silence to Soundscape: Embedding MP3s in Presentations\"" keywords: "\"Steps in Auditioning,From Quietude To Sounds,Soundscapes Beginnings,Silence to Auditory Learning,Step-by-Step Audition Guide,Transforming Silent Spaces,Auditory Experience Growth\"" thumbnail: https://www.lifewire.com/thmb/gZnowx2JtDk-nfa-Qpq0XcIEObA=/400x300/filters:no_upscale():max_bytes(150000):strip_icc()/GettyImages-640608114-590235945f9b5810dcabd4b5.jpg --- ## From Silence to Soundscape: Embedding MP3s in Presentations "I am looking to create a compelling assignment, and I need someone who can help me promptly answer how to add music to PowerPoint.” Adding a music piece helps the PPT be attractive and enjoyable. Any presentation needs to be understood by the audience who is wandering it. Picking the viewers' interest is the standard task for the person presenting the presentation. Thus, make the PowerPoint as creative as possible. Without any further ado, let’s read a quick step-by-step tutorial to add music to PowerPoint as follows. #### In this article 01 [How to add music to PowerPoint?](#Part 1) 02 [Can I play music automatically on PowerPoint](#Part 2) 03 [Get music to play throughout a PowerPoint](#Part 3) 04 [Add more songs to a PowerPoint presentation](#Part 4) ## Part 1 How to add music to PowerPoint? Before you add music to PowerPoint, note specific points. Your presentation size will increase by the size of the MP3 music file you add after the audio files are embedded directly into PPT. For instance, the size of your presentation will magnify by 17MB if you add a song of 17MB to the presentation. So, the solution is that you need to compress your file size accordingly. ![add music to ppt 1](https://images.wondershare.com/filmora/article-images/2022/02/add-music-to-ppt-1.jpg) ### Steps on how to insert music in PowerPoint presentation ##### Step1 Navigate to your Title slide (or wherever you want your music to start) ##### Step2 Click the Insert tab ##### Step3 Open the Audio drop-down (in the Media group) ##### Step4 Select Audio on My PC ##### Step5 Visit the folder on your computer ##### Step6 Select the Audio file ##### Step7 Hit the Insert tab Consequently, the audio file gets embedded in your presentation. ![ppt audio options](https://images.wondershare.com/filmora/article-images/2022/02/ppt-audio-options.jpg) After the music embeds in your presentation, anyone who opens the presentation can access and play the music inside PowerPoint. Your song will play within the Click Sequence of your presentation by default. After inserting music into your presentation, you can then convert your entire presentation into a video and share it with your colleagues. ## Part 2 Can I play music automatically on PowerPoint Yes, you can start the audio in the click sequence or immediately. <di ##### Step1Click the audio icon on the slide in the Normal view while you edit the slides ##### Step2 Choose Automatically or In Click Sequence in the Start list within the Audio Options of Audio Tools Playback tab ![play automatic ppt](https://images.wondershare.com/filmora/article-images/2022/02/play-automatic-ppt.jpg) ##### Step3 Remember that the In Click Sequence function is only available in PowerPoint 2016 and the latest versions Click From Beginning to test the sound over the Slide Show tab. Reminder: It would help if you keep your computer equipped with speakers or sound cards to hear sounds or music. ## Part 3 Get music to play throughout a PowerPoint You can add music to your PowerPoint and play it across slides in the slide show background. If you wish to add audio or music from the web, you have to download it to your computer before using it in a presentation. ### Steps to play a song across slides ##### Step1 Select Audio on the Insert tab and choose Audio on My PC ##### Step2 Browse to the music file you want to use within the File Explorer, and then select Insert ##### Step3 Select Play in Background within the audio icon chosen over the slide ![ppt playback](https://images.wondershare.com/filmora/article-images/2022/02/ppt-playback.jpg) Play in Background helps automatically start the audio file during a slide show and makes the audio play throughout the multiple slides. ## Part 4 Add more songs to a PowerPoint presentation You can add more songs if your slide show plays longer than one song. Yet, find that you're having difficulty synchronizing the Audio with the PowerPoint slideshow. For this purpose, you can use a third-party audio editing tool, such as Wondershare Filmora, to combine the Audio into one file and enjoy it all together. And, this makes how to insert music in PowerPoint even easier than before. Here, we'd like to show you a tutorial on using Wondershare Filmora to add music to PowerPoint indirectly but more interestingly so that you don't have to work for longer. ##### Step1 Download Filmora and launch it Click the Free Download button in the Wondershare Filmora to install it on your PC and then launch it. Before you do a new project, you can select the aspect ratio as per the requirements. And hit the New Project and continue. ##### Step2 Import Photos and Music You can import music media to the Media Library and then directly drag and drop them to the timeline. ##### Step3 Add Transitions ![add transitions filmora](https://images.wondershare.com/filmora/article-images/filmora9-slideshow-transitions.jpg) There are multiples of transitions available in Filmora to choose among. You can apply a particular transition between each selected photo or apply random transitions as per your interests. Filmora features 30 plus transitions, especially for Slideshow or PowerPoint presentations, such as cross split, cross merge, swap, and sweep clockwise. You can also use 3D transition, speed blur, or ripple and dissolve transitions. Moreover, you can accordingly adjust the duration of the transition. To make your photos slideshow look amazing, applying filters and overlays effects is highly recommended. ##### Step4 Add background music You can select the sound effect or background music from the inbuilt audio library in Filmora or drag and drop these media or files to the timeline directly. Filmora features the voiceover recording tool, which assists you in recording your voice easily. ![add background music filmora](https://images.wondershare.com/filmora/article-images/create-music-slideshow-filmora9.jpg) ##### Step5 Export and Save Now, it's time to save and export the music slideshow as you see fit. You have several options where you can save the final project within your PC in different formats, or you can share it to various social media platforms directly, or you can burn it to DVD. Why choose Filmora to add music to the PowerPoint presentation? ● Compatibility with different formats. ● It helps you crop, zoom, and pan the PowerPoint slideshow automatically or manually by applying Pan & Zoom Photo Placement. ● It has a massive library of sound effects, music tracks, stunning transitions, elements presets, and effects. ● Here, you can record your voiceover and apply fade-in and fade-out effects. ### Conclusion So, we're now concluding on how to add music to PowerPoint along with describing the most straightforward yet proficient way of making things simpler. We've discussed a quick yet straightforward to absorb step-by-step guide on how to put music in PowerPoint. If you wish to add a fully edited video directly into the PowerPoint presentation, try using Wondershare Filmora and enjoy your greatest wonders! 02 [Can I play music automatically on PowerPoint](#Part 2) 03 [Get music to play throughout a PowerPoint](#Part 3) 04 [Add more songs to a PowerPoint presentation](#Part 4) ## Part 1 How to add music to PowerPoint? Before you add music to PowerPoint, note specific points. Your presentation size will increase by the size of the MP3 music file you add after the audio files are embedded directly into PPT. For instance, the size of your presentation will magnify by 17MB if you add a song of 17MB to the presentation. So, the solution is that you need to compress your file size accordingly. ![add music to ppt 1](https://images.wondershare.com/filmora/article-images/2022/02/add-music-to-ppt-1.jpg) ### Steps on how to insert music in PowerPoint presentation ##### Step1 Navigate to your Title slide (or wherever you want your music to start) ##### Step2 Click the Insert tab ##### Step3 Open the Audio drop-down (in the Media group) ##### Step4 Select Audio on My PC ##### Step5 Visit the folder on your computer ##### Step6 Select the Audio file ##### Step7 Hit the Insert tab Consequently, the audio file gets embedded in your presentation. ![ppt audio options](https://images.wondershare.com/filmora/article-images/2022/02/ppt-audio-options.jpg) After the music embeds in your presentation, anyone who opens the presentation can access and play the music inside PowerPoint. Your song will play within the Click Sequence of your presentation by default. After inserting music into your presentation, you can then convert your entire presentation into a video and share it with your colleagues. ## Part 2 Can I play music automatically on PowerPoint Yes, you can start the audio in the click sequence or immediately. <di ##### Step1Click the audio icon on the slide in the Normal view while you edit the slides ##### Step2 Choose Automatically or In Click Sequence in the Start list within the Audio Options of Audio Tools Playback tab ![play automatic ppt](https://images.wondershare.com/filmora/article-images/2022/02/play-automatic-ppt.jpg) ##### Step3 Remember that the In Click Sequence function is only available in PowerPoint 2016 and the latest versions Click From Beginning to test the sound over the Slide Show tab. Reminder: It would help if you keep your computer equipped with speakers or sound cards to hear sounds or music. ## Part 3 Get music to play throughout a PowerPoint You can add music to your PowerPoint and play it across slides in the slide show background. If you wish to add audio or music from the web, you have to download it to your computer before using it in a presentation. ### Steps to play a song across slides ##### Step1 Select Audio on the Insert tab and choose Audio on My PC ##### Step2 Browse to the music file you want to use within the File Explorer, and then select Insert ##### Step3 Select Play in Background within the audio icon chosen over the slide ![ppt playback](https://images.wondershare.com/filmora/article-images/2022/02/ppt-playback.jpg) Play in Background helps automatically start the audio file during a slide show and makes the audio play throughout the multiple slides. ## Part 4 Add more songs to a PowerPoint presentation You can add more songs if your slide show plays longer than one song. Yet, find that you're having difficulty synchronizing the Audio with the PowerPoint slideshow. For this purpose, you can use a third-party audio editing tool, such as Wondershare Filmora, to combine the Audio into one file and enjoy it all together. And, this makes how to insert music in PowerPoint even easier than before. Here, we'd like to show you a tutorial on using Wondershare Filmora to add music to PowerPoint indirectly but more interestingly so that you don't have to work for longer. ##### Step1 Download Filmora and launch it Click the Free Download button in the Wondershare Filmora to install it on your PC and then launch it. Before you do a new project, you can select the aspect ratio as per the requirements. And hit the New Project and continue. ##### Step2 Import Photos and Music You can import music media to the Media Library and then directly drag and drop them to the timeline. ##### Step3 Add Transitions ![add transitions filmora](https://images.wondershare.com/filmora/article-images/filmora9-slideshow-transitions.jpg) There are multiples of transitions available in Filmora to choose among. You can apply a particular transition between each selected photo or apply random transitions as per your interests. Filmora features 30 plus transitions, especially for Slideshow or PowerPoint presentations, such as cross split, cross merge, swap, and sweep clockwise. You can also use 3D transition, speed blur, or ripple and dissolve transitions. Moreover, you can accordingly adjust the duration of the transition. To make your photos slideshow look amazing, applying filters and overlays effects is highly recommended. ##### Step4 Add background music You can select the sound effect or background music from the inbuilt audio library in Filmora or drag and drop these media or files to the timeline directly. Filmora features the voiceover recording tool, which assists you in recording your voice easily. ![add background music filmora](https://images.wondershare.com/filmora/article-images/create-music-slideshow-filmora9.jpg) ##### Step5 Export and Save Now, it's time to save and export the music slideshow as you see fit. You have several options where you can save the final project within your PC in different formats, or you can share it to various social media platforms directly, or you can burn it to DVD. Why choose Filmora to add music to the PowerPoint presentation? ● Compatibility with different formats. ● It helps you crop, zoom, and pan the PowerPoint slideshow automatically or manually by applying Pan & Zoom Photo Placement. ● It has a massive library of sound effects, music tracks, stunning transitions, elements presets, and effects. ● Here, you can record your voiceover and apply fade-in and fade-out effects. ### Conclusion So, we're now concluding on how to add music to PowerPoint along with describing the most straightforward yet proficient way of making things simpler. We've discussed a quick yet straightforward to absorb step-by-step guide on how to put music in PowerPoint. If you wish to add a fully edited video directly into the PowerPoint presentation, try using Wondershare Filmora and enjoy your greatest wonders! 02 [Can I play music automatically on PowerPoint](#Part 2) 03 [Get music to play throughout a PowerPoint](#Part 3) 04 [Add more songs to a PowerPoint presentation](#Part 4) ## Part 1 How to add music to PowerPoint? Before you add music to PowerPoint, note specific points. Your presentation size will increase by the size of the MP3 music file you add after the audio files are embedded directly into PPT. For instance, the size of your presentation will magnify by 17MB if you add a song of 17MB to the presentation. So, the solution is that you need to compress your file size accordingly. ![add music to ppt 1](https://images.wondershare.com/filmora/article-images/2022/02/add-music-to-ppt-1.jpg) ### Steps on how to insert music in PowerPoint presentation ##### Step1 Navigate to your Title slide (or wherever you want your music to start) ##### Step2 Click the Insert tab ##### Step3 Open the Audio drop-down (in the Media group) ##### Step4 Select Audio on My PC ##### Step5 Visit the folder on your computer ##### Step6 Select the Audio file ##### Step7 Hit the Insert tab Consequently, the audio file gets embedded in your presentation. ![ppt audio options](https://images.wondershare.com/filmora/article-images/2022/02/ppt-audio-options.jpg) After the music embeds in your presentation, anyone who opens the presentation can access and play the music inside PowerPoint. Your song will play within the Click Sequence of your presentation by default. After inserting music into your presentation, you can then convert your entire presentation into a video and share it with your colleagues. ## Part 2 Can I play music automatically on PowerPoint Yes, you can start the audio in the click sequence or immediately. <di ##### Step1Click the audio icon on the slide in the Normal view while you edit the slides ##### Step2 Choose Automatically or In Click Sequence in the Start list within the Audio Options of Audio Tools Playback tab ![play automatic ppt](https://images.wondershare.com/filmora/article-images/2022/02/play-automatic-ppt.jpg) ##### Step3 Remember that the In Click Sequence function is only available in PowerPoint 2016 and the latest versions Click From Beginning to test the sound over the Slide Show tab. Reminder: It would help if you keep your computer equipped with speakers or sound cards to hear sounds or music. ## Part 3 Get music to play throughout a PowerPoint You can add music to your PowerPoint and play it across slides in the slide show background. If you wish to add audio or music from the web, you have to download it to your computer before using it in a presentation. ### Steps to play a song across slides ##### Step1 Select Audio on the Insert tab and choose Audio on My PC ##### Step2 Browse to the music file you want to use within the File Explorer, and then select Insert ##### Step3 Select Play in Background within the audio icon chosen over the slide ![ppt playback](https://images.wondershare.com/filmora/article-images/2022/02/ppt-playback.jpg) Play in Background helps automatically start the audio file during a slide show and makes the audio play throughout the multiple slides. ## Part 4 Add more songs to a PowerPoint presentation You can add more songs if your slide show plays longer than one song. Yet, find that you're having difficulty synchronizing the Audio with the PowerPoint slideshow. For this purpose, you can use a third-party audio editing tool, such as Wondershare Filmora, to combine the Audio into one file and enjoy it all together. And, this makes how to insert music in PowerPoint even easier than before. Here, we'd like to show you a tutorial on using Wondershare Filmora to add music to PowerPoint indirectly but more interestingly so that you don't have to work for longer. ##### Step1 Download Filmora and launch it Click the Free Download button in the Wondershare Filmora to install it on your PC and then launch it. Before you do a new project, you can select the aspect ratio as per the requirements. And hit the New Project and continue. ##### Step2 Import Photos and Music You can import music media to the Media Library and then directly drag and drop them to the timeline. ##### Step3 Add Transitions ![add transitions filmora](https://images.wondershare.com/filmora/article-images/filmora9-slideshow-transitions.jpg) There are multiples of transitions available in Filmora to choose among. You can apply a particular transition between each selected photo or apply random transitions as per your interests. Filmora features 30 plus transitions, especially for Slideshow or PowerPoint presentations, such as cross split, cross merge, swap, and sweep clockwise. You can also use 3D transition, speed blur, or ripple and dissolve transitions. Moreover, you can accordingly adjust the duration of the transition. To make your photos slideshow look amazing, applying filters and overlays effects is highly recommended. ##### Step4 Add background music You can select the sound effect or background music from the inbuilt audio library in Filmora or drag and drop these media or files to the timeline directly. Filmora features the voiceover recording tool, which assists you in recording your voice easily. ![add background music filmora](https://images.wondershare.com/filmora/article-images/create-music-slideshow-filmora9.jpg) ##### Step5 Export and Save Now, it's time to save and export the music slideshow as you see fit. You have several options where you can save the final project within your PC in different formats, or you can share it to various social media platforms directly, or you can burn it to DVD. Why choose Filmora to add music to the PowerPoint presentation? ● Compatibility with different formats. ● It helps you crop, zoom, and pan the PowerPoint slideshow automatically or manually by applying Pan & Zoom Photo Placement. ● It has a massive library of sound effects, music tracks, stunning transitions, elements presets, and effects. ● Here, you can record your voiceover and apply fade-in and fade-out effects. ### Conclusion So, we're now concluding on how to add music to PowerPoint along with describing the most straightforward yet proficient way of making things simpler. We've discussed a quick yet straightforward to absorb step-by-step guide on how to put music in PowerPoint. If you wish to add a fully edited video directly into the PowerPoint presentation, try using Wondershare Filmora and enjoy your greatest wonders! 02 [Can I play music automatically on PowerPoint](#Part 2) 03 [Get music to play throughout a PowerPoint](#Part 3) 04 [Add more songs to a PowerPoint presentation](#Part 4) ## Part 1 How to add music to PowerPoint? Before you add music to PowerPoint, note specific points. Your presentation size will increase by the size of the MP3 music file you add after the audio files are embedded directly into PPT. For instance, the size of your presentation will magnify by 17MB if you add a song of 17MB to the presentation. So, the solution is that you need to compress your file size accordingly. ![add music to ppt 1](https://images.wondershare.com/filmora/article-images/2022/02/add-music-to-ppt-1.jpg) ### Steps on how to insert music in PowerPoint presentation ##### Step1 Navigate to your Title slide (or wherever you want your music to start) ##### Step2 Click the Insert tab ##### Step3 Open the Audio drop-down (in the Media group) ##### Step4 Select Audio on My PC ##### Step5 Visit the folder on your computer ##### Step6 Select the Audio file ##### Step7 Hit the Insert tab Consequently, the audio file gets embedded in your presentation. ![ppt audio options](https://images.wondershare.com/filmora/article-images/2022/02/ppt-audio-options.jpg) After the music embeds in your presentation, anyone who opens the presentation can access and play the music inside PowerPoint. Your song will play within the Click Sequence of your presentation by default. After inserting music into your presentation, you can then convert your entire presentation into a video and share it with your colleagues. ## Part 2 Can I play music automatically on PowerPoint Yes, you can start the audio in the click sequence or immediately. <di ##### Step1Click the audio icon on the slide in the Normal view while you edit the slides ##### Step2 Choose Automatically or In Click Sequence in the Start list within the Audio Options of Audio Tools Playback tab ![play automatic ppt](https://images.wondershare.com/filmora/article-images/2022/02/play-automatic-ppt.jpg) ##### Step3 Remember that the In Click Sequence function is only available in PowerPoint 2016 and the latest versions Click From Beginning to test the sound over the Slide Show tab. Reminder: It would help if you keep your computer equipped with speakers or sound cards to hear sounds or music. ## Part 3 Get music to play throughout a PowerPoint You can add music to your PowerPoint and play it across slides in the slide show background. If you wish to add audio or music from the web, you have to download it to your computer before using it in a presentation. ### Steps to play a song across slides ##### Step1 Select Audio on the Insert tab and choose Audio on My PC ##### Step2 Browse to the music file you want to use within the File Explorer, and then select Insert ##### Step3 Select Play in Background within the audio icon chosen over the slide ![ppt playback](https://images.wondershare.com/filmora/article-images/2022/02/ppt-playback.jpg) Play in Background helps automatically start the audio file during a slide show and makes the audio play throughout the multiple slides. ## Part 4 Add more songs to a PowerPoint presentation You can add more songs if your slide show plays longer than one song. Yet, find that you're having difficulty synchronizing the Audio with the PowerPoint slideshow. For this purpose, you can use a third-party audio editing tool, such as Wondershare Filmora, to combine the Audio into one file and enjoy it all together. And, this makes how to insert music in PowerPoint even easier than before. Here, we'd like to show you a tutorial on using Wondershare Filmora to add music to PowerPoint indirectly but more interestingly so that you don't have to work for longer. ##### Step1 Download Filmora and launch it Click the Free Download button in the Wondershare Filmora to install it on your PC and then launch it. Before you do a new project, you can select the aspect ratio as per the requirements. And hit the New Project and continue. ##### Step2 Import Photos and Music You can import music media to the Media Library and then directly drag and drop them to the timeline. ##### Step3 Add Transitions ![add transitions filmora](https://images.wondershare.com/filmora/article-images/filmora9-slideshow-transitions.jpg) There are multiples of transitions available in Filmora to choose among. You can apply a particular transition between each selected photo or apply random transitions as per your interests. Filmora features 30 plus transitions, especially for Slideshow or PowerPoint presentations, such as cross split, cross merge, swap, and sweep clockwise. You can also use 3D transition, speed blur, or ripple and dissolve transitions. Moreover, you can accordingly adjust the duration of the transition. To make your photos slideshow look amazing, applying filters and overlays effects is highly recommended. ##### Step4 Add background music You can select the sound effect or background music from the inbuilt audio library in Filmora or drag and drop these media or files to the timeline directly. Filmora features the voiceover recording tool, which assists you in recording your voice easily. ![add background music filmora](https://images.wondershare.com/filmora/article-images/create-music-slideshow-filmora9.jpg) ##### Step5 Export and Save Now, it's time to save and export the music slideshow as you see fit. You have several options where you can save the final project within your PC in different formats, or you can share it to various social media platforms directly, or you can burn it to DVD. Why choose Filmora to add music to the PowerPoint presentation? ● Compatibility with different formats. ● It helps you crop, zoom, and pan the PowerPoint slideshow automatically or manually by applying Pan & Zoom Photo Placement. ● It has a massive library of sound effects, music tracks, stunning transitions, elements presets, and effects. ● Here, you can record your voiceover and apply fade-in and fade-out effects. ### Conclusion So, we're now concluding on how to add music to PowerPoint along with describing the most straightforward yet proficient way of making things simpler. We've discussed a quick yet straightforward to absorb step-by-step guide on how to put music in PowerPoint. If you wish to add a fully edited video directly into the PowerPoint presentation, try using Wondershare Filmora and enjoy your greatest wonders! <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://extra-lessons.techidaily.com/cut-the-clutter-not-quality-explore-top-37-apps-for-mobile-videos-downsize/"><u>Cut the Clutter, Not Quality Explore Top 37 Apps for Mobile Videos Downsize</u></a></li> <li><a href="https://extra-lessons.techidaily.com/new-a-musical-guide-to-enhancing-slides-with-tunes/"><u>[New] A Musical Guide to Enhancing Slides with Tunes</u></a></li> <li><a href="https://extra-lessons.techidaily.com/a-comprehensive-look-at-securing-background-visuals-for-2024/"><u>A Comprehensive Look at Securing Background Visuals for 2024</u></a></li> <li><a href="https://extra-lessons.techidaily.com/2024-approved-background-beats-guide-tunes-for-visuals/"><u>2024 Approved Background Beats Guide Tunes for Visuals</u></a></li> <li><a href="https://extra-lessons.techidaily.com/above-and-beyond-vertical-panoramas-made-easy-for-2024/"><u>Above and Beyond Vertical Panoramas Made Easy for 2024</u></a></li> <li><a href="https://extra-lessons.techidaily.com/android-essentials-for-immersive-video-and-vr-content-for-2024/"><u>Android Essentials for Immersive Video and VR Content for 2024</u></a></li> <li><a href="https://extra-lessons.techidaily.com/2024-approved-10-commandments-of-eye-catching-podcast-album-imagery/"><u>2024 Approved 10 Commandments of Eye-Catching Podcast Album Imagery</u></a></li> <li><a href="https://extra-lessons.techidaily.com/excellent-20-anime-opening-anthems/"><u>Excellent 20 Anime Opening Anthems</u></a></li> <li><a href="https://extra-lessons.techidaily.com/new-5-best-toy-drones/"><u>[New] 5 Best Toy Drones</u></a></li> <li><a href="https://extra-lessons.techidaily.com/distinguished-cinematic-foreshadowing-collection/"><u>Distinguished Cinematic Foreshadowing Collection</u></a></li> <li><a href="https://extra-lessons.techidaily.com/visionary-video-sculpting-stylish-deformed-words/"><u>Visionary Video Sculpting Stylish, Deformed Words</u></a></li> <li><a href="https://extra-lessons.techidaily.com/premier-essentials-seamless-audio-switching/"><u>Premier Essentials Seamless Audio Switching</u></a></li> <li><a href="https://extra-lessons.techidaily.com/2024-approved-a-full-analysis-of-the-lightroom-application-for-android/"><u>2024 Approved A Full Analysis of the Lightroom Application for Android</u></a></li> <li><a href="https://extra-lessons.techidaily.com/2024-approved-1-to-10-superior-4k-screen-selections/"><u>2024 Approved 1 to #10 Superior 4K Screen Selections</u></a></li> <li><a href="https://extra-lessons.techidaily.com/updated-cognitive-clash-ultimate-gk-video-quizzes/"><u>[Updated] Cognitive Clash - Ultimate GK Video Quizzes</u></a></li> <li><a href="https://extra-lessons.techidaily.com/asmr-a-harmonious-journey-to-wellbe-point-for-2024/"><u>ASMR A Harmonious Journey to Wellbe Point for 2024</u></a></li> <li><a href="https://extra-lessons.techidaily.com/new-an-anthology-of-admiration-highlighting-top-10-reddit-threads/"><u>[New] An Anthology of Admiration Highlighting Top 10 Reddit Threads</u></a></li> <li><a href="https://extra-lessons.techidaily.com/updated-2023s-elite-professionals-choosing-360-cameras/"><u>[Updated] 2023'S Elite Professionals Choosing 360 Cameras</u></a></li> <li><a href="https://extra-lessons.techidaily.com/unveiling-the-best-lipos-a-drone-buyers-bible/"><u>Unveiling the Best LiPos - A Drone Buyer's Bible</u></a></li> <li><a href="https://extra-lessons.techidaily.com/complete-evaluation-of-slomo-recording-software-for-2024/"><u>Complete Evaluation of SloMo Recording Software for 2024</u></a></li> <li><a href="https://extra-lessons.techidaily.com/dynamic-panzoid-assembly-resources/"><u>Dynamic Panzoid Assembly Resources</u></a></li> <li><a href="https://extra-lessons.techidaily.com/wit-whisperer-visual-snap/"><u>Wit Whisperer Visual Snap</u></a></li> <li><a href="https://extra-lessons.techidaily.com/professional-tricks-efficiently-cropping-photos-online/"><u>Professional Tricks Efficiently Cropping Photos Online</u></a></li> <li><a href="https://extra-lessons.techidaily.com/a-comprehensive-breakdown-of-yis-ultra-hd-action-for-2024/"><u>A Comprehensive Breakdown of Yi's Ultra HD Action for 2024</u></a></li> <li><a href="https://extra-lessons.techidaily.com/in-2024-creating-captivating-hdr-portraits-in-10-steps/"><u>In 2024, Creating Captivating HDR Portraits in 10 Steps</u></a></li> <li><a href="https://extra-lessons.techidaily.com/action-cam-buyers-guide-affordable-high-definition/"><u>Action Cam Buyer’s Guide - Affordable, High Definition</u></a></li> <li><a href="https://extra-lessons.techidaily.com/in-2024-augment-slides-with-sonic-enhancements/"><u>In 2024, Augment Slides with Sonic Enhancements</u></a></li> <li><a href="https://extra-lessons.techidaily.com/essential-steps-for-online-vhs-image-transformation/"><u>Essential Steps for Online VHS Image Transformation</u></a></li> <li><a href="https://extra-lessons.techidaily.com/in-2024-best-15-programs-to-edit-gopro-footage/"><u>In 2024, Best 15 Programs to Edit GoPro Footage</u></a></li> <li><a href="https://extra-lessons.techidaily.com/the-ultimate-guide-for-amateurs-and-pros-on-windows-11-video-creation/"><u>The Ultimate Guide for Amateurs & Pros on Windows 11 Video Creation</u></a></li> <li><a href="https://extra-lessons.techidaily.com/in-2024-captivating-books-in-video-form/"><u>In 2024, Captivating Books in Video Form</u></a></li> <li><a href="https://extra-lessons.techidaily.com/10-masterpiece-scenes-to-perfect-your-edits/"><u>10 Masterpiece Scenes to Perfect Your Edits</u></a></li> <li><a href="https://extra-lessons.techidaily.com/uncomplicated-guide-to-smooth-easy-to-create-nfts/"><u>Uncomplicated Guide To Smooth, Easy-to-Create NFTs</u></a></li> <li><a href="https://extra-lessons.techidaily.com/all-inclusive-guide-what-is-googles-podcast-service-in-2024/"><u>All-Inclusive Guide What Is Google's Podcast Service, In 2024</u></a></li> <li><a href="https://extra-lessons.techidaily.com/in-2024-boost-your-youtube-video-to-million-views-quickly/"><u>In 2024, Boost Your YouTube Video to Million Views Quickly</u></a></li> <li><a href="https://extra-lessons.techidaily.com/enhancing-imagery-a-look-at-samsung-image-studio-tools/"><u>Enhancing Imagery A Look at Samsung Image Studio Tools</u></a></li> <li><a href="https://extra-lessons.techidaily.com/quick-profit-on-reddit-here-are-your-13-most-accessible-ways/"><u>Quick Profit on Reddit? Here Are Your 13 Most Accessible Ways</u></a></li> <li><a href="https://extra-lessons.techidaily.com/updated-cost-outline-for-composing-sounds-to-screen-titles/"><u>[Updated] Cost Outline for Composing Sounds to Screen-Titles</u></a></li> <li><a href="https://extra-lessons.techidaily.com/the-audio-alchemists-handbook-creating-custom-auditory-alerts-on-android-phones/"><u>The Audio Alchemist's Handbook Creating Custom Auditory Alerts on Android Phones</u></a></li> <li><a href="https://extra-lessons.techidaily.com/mastering-close-up-cinematography-techniques-with-kinemaster-pro/"><u>Mastering Close-Up Cinematography Techniques with Kinemaster Pro</u></a></li> <li><a href="https://extra-lessons.techidaily.com/choice-collection-high-quality-virtual-reality-titles-for-cardboard-for-2024/"><u>Choice Collection High-Quality Virtual Reality Titles for Cardboard for 2024</u></a></li> <li><a href="https://extra-lessons.techidaily.com/bridging-content-and-commerce-a-youtubers-guide-to-sponsorship/"><u>Bridging Content and Commerce A Youtuber's Guide to Sponsorship</u></a></li> <li><a href="https://extra-lessons.techidaily.com/2024-approved-building-your-brand-on-instagram-the-top-9-actions-of-industry-stars/"><u>2024 Approved Building Your Brand on Instagram The Top 9 Actions of Industry Stars</u></a></li> <li><a href="https://extra-lessons.techidaily.com/beyond-basics-professional-tips-from-vidas-features-for-2024/"><u>Beyond Basics Professional Tips From Vida's Features for 2024</u></a></li> <li><a href="https://extra-lessons.techidaily.com/audiovisual-adaptability-in-free-fire-for-2024/"><u>Audiovisual Adaptability in Free Fire for 2024</u></a></li> <li><a href="https://extra-lessons.techidaily.com/in-2024-activatingdeactivating-picture-in-picture-youtube-viewing-on-iphone/"><u>In 2024, Activating/Deactivating Picture In Picture YouTube Viewing on iPhone</u></a></li> <li><a href="https://extra-lessons.techidaily.com/unleash-creativity-best-android-edits/"><u>Unleash Creativity Best Android Edits</u></a></li> <li><a href="https://extra-lessons.techidaily.com/mastering-selective-image-blurring-techniques/"><u>Mastering Selective Image Blurring Techniques</u></a></li> <li><a href="https://twitter-clips.techidaily.com/updated-supercharge-your-tweet-views-for-flawless-hd/"><u>[Updated] Supercharge Your Tweet Views for Flawless HD</u></a></li> <li><a href="https://change-location.techidaily.com/honor-x50-gt-camera-not-working-unexpected-error-fix-it-now-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>Honor X50 GT Camera Not Working Unexpected Error? Fix It Now | Dr.fone</u></a></li> <li><a href="https://android-transfer.techidaily.com/how-to-transfer-photos-from-poco-x5-pro-to-new-android-drfone-by-drfone-transfer-from-android-transfer-from-android/"><u>How to Transfer Photos from Poco X5 Pro to New Android? | Dr.fone</u></a></li> <li><a href="https://fake-location.techidaily.com/methods-to-change-gps-location-on-tecno-pova-5-drfone-by-drfone-virtual-android/"><u>Methods to Change GPS Location On Tecno Pova 5 | Dr.fone</u></a></li> <li><a href="https://tiktok-clips.techidaily.com/new-learn-the-art-of-pairing-captions-with-visuals-for-tiktoks/"><u>[New] Learn the Art of Pairing Captions with Visuals for TikToks</u></a></li> <li><a href="https://ai-topics.techidaily.com/updated-2024-approved-how-to-make-talking-emoji-on-iphone-in-easy-steps/"><u>Updated 2024 Approved How To Make Talking Emoji on iPhone in Easy Steps</u></a></li> <li><a href="https://smart-video-editing.techidaily.com/new-2024-approved-gif-mastery-28-top-video-to-gif-converter-recommendations/"><u>New 2024 Approved GIF Mastery 28 Top Video to GIF Converter Recommendations</u></a></li> <li><a href="https://visual-screen-recording.techidaily.com/updated-in-2024-ultimate-checklist-streamlining-and-maximizing-screencast-quality-with-mobizen/"><u>[Updated] In 2024, Ultimate Checklist Streamlining and Maximizing Screencast Quality with Mobizen</u></a></li> <li><a href="https://bypass-frp.techidaily.com/in-2024-about-honor-80-pro-straight-screen-edition-frp-bypass-by-drfone-android/"><u>In 2024, About Honor 80 Pro Straight Screen Edition FRP Bypass</u></a></li> <li><a href="https://screen-activity-recording.techidaily.com/in-2024-discovering-new-ways-to-use-bandicam-a-deep-dive/"><u>In 2024, Discovering New Ways to Use Bandicam – A Deep Dive</u></a></li> <li><a href="https://ai-voice-clone.techidaily.com/updated-what-is-an-ai-presentation-maker-wondershare-virbo-glossary-for-2024/"><u>Updated What Is an AI Presentation Maker? | Wondershare Virbo Glossary for 2024</u></a></li> <li><a href="https://facebook-videos.techidaily.com/updated-unseen-wealth-the-underground-auction-of-elusive-artifacts-2023-edition-for-2024/"><u>[Updated] Unseen Wealth The Underground Auction of Elusive Artifacts, 2023 Edition for 2024</u></a></li> <li><a href="https://video-ai-editor.techidaily.com/updated-2024-approved-best-slow-mo-and-fast-mo-video-editors-for-windows-and-mac/"><u>Updated 2024 Approved Best Slow-Mo and Fast-Mo Video Editors for Windows and Mac</u></a></li> <li><a href="https://discord-videos.techidaily.com/new-the-insiders-guide-to-clearer-communication-via-voicemod-on-discord/"><u>[New] The Insider's Guide to Clearer Communication via VoiceMod on Discord</u></a></li> <li><a href="https://discord-videos.techidaily.com/2024-approved-voice-modding-on-discord-a-step-by-step-guide/"><u>2024 Approved Voice Modding on Discord A Step-by-Step Guide</u></a></li> <li><a href="https://bypass-frp.techidaily.com/is-gsm-flasher-adb-legit-full-review-to-bypass-your-google-pixel-8-phone-frp-lock-by-drfone-android/"><u>Is GSM Flasher ADB Legit? Full Review To Bypass Your Google Pixel 8 Phone FRP Lock</u></a></li> <li><a href="https://screen-capture.techidaily.com/updated-2024-approved-best-windows-11-capture-tools-top-15-selections/"><u>[Updated] 2024 Approved Best Windows 11 Capture Tools Top 15 Selections</u></a></li> <li><a href="https://android-location-track.techidaily.com/how-to-track-whatsapp-messages-on-xiaomi-14-without-them-knowing-drfone-by-drfone-virtual-android/"><u>How to Track WhatsApp Messages on Xiaomi 14 Without Them Knowing? | Dr.fone</u></a></li> <li><a href="https://review-topics.techidaily.com/infinix-music-recovery-recover-deleted-music-from-infinix-by-fonelab-android-recover-music/"><u>Infinix Music Recovery - Recover Deleted Music from Infinix</u></a></li> <li><a href="https://on-screen-recording.techidaily.com/new-in-2024-webcam-advancements-revolutionizing-video-capture-at-home/"><u>[New] In 2024, WebCam Advancements Revolutionizing Video Capture at Home</u></a></li> <li><a href="https://location-social.techidaily.com/how-to-change-vivo-x-flip-location-on-skout-drfone-by-drfone-virtual-android/"><u>How to Change Vivo X Flip Location on Skout | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-to-change-your-apple-id-password-on-your-iphone-13-pro-drfone-by-drfone-ios/"><u>In 2024, How To Change Your Apple ID Password On your iPhone 13 Pro | Dr.fone</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/updated-give-your-videos-a-3d-makeover-tips-and-tricks-for-windows-users-for-2024/"><u>Updated Give Your Videos a 3D Makeover Tips and Tricks for Windows Users for 2024</u></a></li> <li><a href="https://android-unlock.techidaily.com/unlock-your-oppo-a59-5g-phone-with-ease-the-3-best-lock-screen-removal-tools-by-drfone-android/"><u>Unlock Your Oppo A59 5G Phone with Ease The 3 Best Lock Screen Removal Tools</u></a></li> <li><a href="https://smart-video-editing.techidaily.com/updated-online-video-editors-handbook-from-download-to-final-cut-for-2024/"><u>Updated Online Video Editors Handbook From Download to Final Cut for 2024</u></a></li> <li><a href="https://facebook-videos.techidaily.com/updated-2024-approved-optimized-visual-quality-black-bar-and-box-frame-for-social-media-posts/"><u>[Updated] 2024 Approved Optimized Visual Quality Black Bar & Box Frame for Social Media Posts</u></a></li> <li><a href="https://tiktok-clips.techidaily.com/updated-2024-approved-unveiling-the-essence-of-tiktok-movement-sound-and-humor/"><u>[Updated] 2024 Approved Unveiling the Essence of TikTok Movement, Sound, and Humor</u></a></li> <li><a href="https://ai-video-apps.techidaily.com/2024-approved-make-your-own-gif-loops-with-these-top-free-tools/"><u>2024 Approved Make Your Own GIF Loops with These Top Free Tools</u></a></li> <li><a href="https://techidaily.com/how-to-transfer-data-from-apple-iphone-12-pro-to-androidios-drfone-by-drfone-transfer-data-from-ios-transfer-data-from-ios/"><u>How To Transfer Data From Apple iPhone 12 Pro To Android/iOS? | Dr.fone</u></a></li> <li><a href="https://change-location.techidaily.com/in-2024-how-to-come-up-with-the-best-pokemon-team-on-xiaomi-redmi-a2-drfone-by-drfone-virtual-android/"><u>In 2024, How to Come up With the Best Pokemon Team On Xiaomi Redmi A2? | Dr.fone</u></a></li> <li><a href="https://screen-capture.techidaily.com/new-in-2024-peak-procurement-of-lecture-captures/"><u>[New] In 2024, Peak Procurement of Lecture Captures</u></a></li> </ul></div>
<!DOCTYPE html> <html> <head> <title>JS Form</title> </head> <body> <form name="myform" action="form_js.html" method="post" onsubmit="return validitation();"> Name : <input type="text" name="fname"> <input type="submit" value="Submit"> </form> <br> <h4>Please enter value from 1 to 20</h4> <input type="text" name="numInput" id="numInput"> <input type="submit" value="Check" onclick="checkNum();"> <br> <p id="demo"></p> <h4>Please select a number between (100 - 200) else there with be expection</h4> <input type="number" name="cnum" id="cnum" min="100" max="200" required> <input type="submit" value="Ok" onclick="selectNum()"> <p id="snum"></p> <script type="text/javascript"> function validitation() { var x = document.forms["myform"]["fname"].value; if(x == "") { alert("Please enter name!"); return false; } else { alert("Hello, " + x); return true; } } function checkNum() { var x = document.getElementById("numInput").value; if (isNaN(x) || x < 1 || x > 20) { document.getElementById("demo").innerHTML = "Out of range"; } else { document.getElementById("demo").innerHTML = "Number is " + x; } } function selectNum() { var getnum, text; getnum = document.getElementById("cnum"); /* if (!getnum.checkValidity()) // validity function { text = getnum.validitationMessage; // validation message } else */ if(getnum.validity.rangeOverflow) { text = "Range Overflow"; } else if(getnum.validity.rangeUnderflow) { text = "Range Underflow" } else { text = "Input is Ok"; } document.getElementById("snum").innerHTML = text; } </script> </body> </html>
package com.tokopedia.recommendation_widget_common.widget.productcard.carousel.viewholder import android.content.Context import android.view.View import com.tokopedia.abstraction.base.view.adapter.viewholders.AbstractViewHolder import com.tokopedia.analytics.byteio.EntranceForm import com.tokopedia.analytics.byteio.recommendation.AppLogRecommendation import com.tokopedia.kotlin.extensions.view.addOnImpression1pxListener import com.tokopedia.kotlin.extensions.view.addOnImpressionListener import com.tokopedia.productcard.ATCNonVariantListener import com.tokopedia.productcard.ProductCardClickListener import com.tokopedia.productcard.ProductCardGridView import com.tokopedia.productcard.layout.ProductConstraintLayout import com.tokopedia.recommendation_widget_common.R import com.tokopedia.recommendation_widget_common.byteio.TrackRecommendationMapper.asProductTrackModel import com.tokopedia.recommendation_widget_common.presentation.model.RecommendationWidget import com.tokopedia.recommendation_widget_common.widget.productcard.carousel.model.RecomCarouselProductCardDataModel import com.tokopedia.topads.sdk.utils.TopAdsUrlHitter /** * Created by yfsx on 5/3/21. */ class RecomCarouselProductCardViewHolder (view: View, val data: RecommendationWidget): AbstractViewHolder<RecomCarouselProductCardDataModel>(view) { companion object{ val LAYOUT = R.layout.item_recom_carousel_productcard private const val className = "com.tokopedia.recommendation_widget_common.widget.productcard.carousel.viewholder.RecomCarouselProductCardViewHolder" } private val productCardView: ProductCardGridView? by lazy { view.findViewById<ProductCardGridView>(R.id.productCardView) } override fun bind(element: RecomCarouselProductCardDataModel) { setLayout(element) setupListener(itemView.context, element) } override fun bind(element: RecomCarouselProductCardDataModel, payloads: MutableList<Any>) { val payload = payloads.firstOrNull().takeIf { it is Map<*, *> } as? Map<*, *> if (payload.isNullOrEmpty()) { bind(element) } else { if (payload.containsKey(RecomCarouselProductCardDataModel.PAYLOAD_FLAG_SHOULD_UPDATE_PRODUCT_CARD)) { setLayout(element) } if (payload.containsKey(RecomCarouselProductCardDataModel.PAYLOAD_FLAG_SHOULD_UPDATE_LISTENERS)) { setupListener(itemView.context, element) } } } private fun setLayout(element: RecomCarouselProductCardDataModel){ productCardView?.run{ applyCarousel() setProductModel(element.productModel) } } private fun setupListener(context: Context, element: RecomCarouselProductCardDataModel) { productCardView?.run { addOnImpression1pxListener(element.recomItem.appLogImpressHolder) { AppLogRecommendation.sendProductShowAppLog( element.recomItem.asProductTrackModel( entranceForm = EntranceForm.HORIZONTAL_GOODS_CARD, additionalParam = element.appLogAdditionalParam ) ) } addOnImpressionListener(element.recomItem) { if(element.recomItem.isTopAds){ TopAdsUrlHitter(context).hitImpressionUrl( className, element.recomItem.trackerImageUrl, element.recomItem.productId.toString(), element.recomItem.name, element.recomItem.imageUrl, element.componentName) } element.listener?.onProductCardImpressed(position = adapterPosition,data = data, recomItem = element.recomItem) } setVisibilityPercentListener(element.recomItem.isTopAds, object : ProductConstraintLayout.OnVisibilityPercentChanged { override fun onShow() { element.listener?.onViewAttachedToWindow(element.recomItem, bindingAdapterPosition) } override fun onShowOver(maxPercentage: Int) { element.listener?.onViewDetachedFromWindow(element.recomItem, bindingAdapterPosition, maxPercentage) } }) setOnClickListener(object : ProductCardClickListener { override fun onClick(v: View) { AppLogRecommendation.sendProductClickAppLog( element.recomItem.asProductTrackModel( entranceForm = EntranceForm.HORIZONTAL_GOODS_CARD, additionalParam = element.appLogAdditionalParam ) ) if (element.recomItem.isTopAds) { TopAdsUrlHitter(context).hitClickUrl( className, element.recomItem.clickUrl, element.recomItem.productId.toString(), element.recomItem.name, element.recomItem.imageUrl, element.componentName) } element.listener?.onProductCardClicked(position = adapterPosition,data = data, recomItem = element.recomItem, applink = element.recomItem.appUrl) } override fun onAreaClicked(v: View) { element.listener?.onAreaClicked(bindingAdapterPosition = bindingAdapterPosition, recomItem = element.recomItem) } override fun onProductImageClicked(v: View) { element.listener?.onProductImageClicked(bindingAdapterPosition = bindingAdapterPosition, recomItem = element.recomItem) } override fun onSellerInfoClicked(v: View) { element.listener?.onSellerInfoClicked(bindingAdapterPosition = bindingAdapterPosition, recomItem = element.recomItem) } }) setAddToCartNonVariantClickListener(object: ATCNonVariantListener { override fun onQuantityChanged(quantity: Int) { element.recomItem.onCardQuantityChanged(quantity) element.listener?.onRecomProductCardAddToCartNonVariant( data = data, recomItem = element.recomItem, adapterPosition = adapterPosition, quantity = quantity, ) } }) setAddVariantClickListener { element.listener?.onRecomProductCardAddVariantClick( data = data, recomItem = element.recomItem, adapterPosition = adapterPosition, ) } } } override fun onViewRecycled() { productCardView?.recycle() } }
import React, { useState, useEffect} from 'react'; import 'bootstrap/dist/css/bootstrap.min.css'; import './App.css'; import { Container, Row, Col } from 'react-bootstrap'; import Hero from './components/Hero'; import About from './components/About'; import Experience from './components/Experience'; import Skills from './components/Skills'; import Projects from './components/Projects'; import Contact from './components/Contact'; import Loading from './components/Loading'; import consoleMessage from './helpers/ConsoleMessage'; const App: React.FC = () => { const [isLoading, setIsLoading] = useState<boolean>(true); useEffect(() => { setTimeout(() => { setIsLoading(false); }, 2000); }, [isLoading]); if(isLoading){ console.log(consoleMessage); return <Loading />; } return ( <Container fluid className="App"> <div id="AppBgEffect" className="AppBgEffect"></div> <Row className="justify-content-md-center"> <Col xs={12} md={3}> <Hero /> </Col> <Col xs={1} md={1}></Col> <Col xs={12} md={7}> <About /> <Skills /> <Projects /> <Experience /> <Contact /> </Col> </Row> </Container> ) } export default App;
import React, { Component, Fragment } from 'react'; import PropTypes from 'prop-types'; import { addDays, format, isSameDay, parseISO, subDays, toDate, } from 'date-fns'; import de from 'date-fns/locale/de'; import { withTheme } from '@mui/material/styles'; import Button from '@mui/material/Button'; import Dialog from '@mui/material/Dialog'; import DialogActions from '@mui/material/DialogActions'; import DialogContent from '@mui/material/DialogContent'; import DialogTitle from '@mui/material/DialogTitle'; import EditIcon from '@mui/icons/Edit'; import SaveIcon from '@mui/icons/Save'; import RtgSeparator from '../RtgSeparator'; import GameCard from '../GameCard'; import NullGameCard from '../NullGameCard'; import GameCardGameInfo from '../GameCardGameInfo'; import GameCardBet, { SavingErrorType } from '../GameCardBet'; import Notification, { NotificationType } from '../Notification'; import './CurrentGameCard.scss'; class CurrentGameCard extends Component { static getFormattedKickoffDate(kickoff) { if (isSameDay(kickoff, subDays(new Date(), 1))) { return 'Gestern'; } if (isSameDay(new Date(), kickoff)) { return 'Heute'; } if (isSameDay(kickoff, addDays(new Date(), 1))) { return 'Morgen'; } return format(kickoff, 'EEEEEE. d. LLLL', { locale: de }); } constructor(props) { super(props); this.state = { betSaveFailed: false, betSaveFailedType: null, editingBet: false, editingBetSuccessful: false, shouldSaveBet: false, }; this.handleBetEdit = this.handleBetEdit.bind(this); this.handleBetEditCancel = this.handleBetEditCancel.bind(this); this.handleBetSave = this.handleBetSave.bind(this); this.handleBetSaveFailure = this.handleBetSaveFailure.bind(this); this.handleBetSaveSuccess = this.handleBetSaveSuccess.bind(this); this.handleBetSaveErrorInfoDialogClosed = this.handleBetSaveErrorInfoDialogClosed.bind(this); } handleBetEdit() { const { onBetEditStart } = this.props; this.setState({ betSaveFailed: false, editingBet: true, editingBetSuccessful: false }); onBetEditStart(); } handleBetEditCancel() { const { onBetEditCancel } = this.props; this.setState({ editingBet: false }, () => { onBetEditCancel(); }); } handleBetSave() { this.setState({ shouldSaveBet: true }); } handleBetSaveFailure(gameId, attemptedBet, type) { this.setState({ betSaveFailed: true, betSaveFailedType: type, shouldSaveBet: false }); } handleBetSaveSuccess(gameId, newBet) { const { onBetEditDone, userBet } = this.props; this.setState({ editingBet: false, editingBetSuccessful: true, shouldSaveBet: false }); const updatedBetId = userBet ? userBet.id : null; onBetEditDone(updatedBetId, newBet); } handleBetSaveErrorInfoDialogClosed() { this.setState((prevState, prevProps) => { let cancelEdit = false; if (prevState.betSaveFailedType !== SavingErrorType.INCOMPLETE) { prevProps.onBetEditCancel(); cancelEdit = true; } return { editingBet: !cancelEdit, betSaveFailed: false, betSaveFailedType: null, shouldSaveBet: false, }; }); } render() { const { betSaveFailed, betSaveFailedType, editingBet, editingBetSuccessful, shouldSaveBet, } = this.state; const { game, theme, userBet } = this.props; const formattedRoundInfo = (_game) => { if (!_game) return '...'; const roundName = _game.round_details.name; const groupName = _game.group ? _game.group.name : null; if (groupName) { return `${roundName} - ${groupName}`; } return roundName; }; return ( <div className="CurrentGameCard"> <RtgSeparator content={game ? ( <div> {CurrentGameCard.getFormattedKickoffDate(parseISO(game.kickoff))} <br /> <span style={{ fontSize: '12px', color: theme.palette.grey['400'], textTransform: 'initial', letterSpacing: 0, }} > {formattedRoundInfo(game)} </span> </div> ) : '...'} contentStyle={{ margin: 0 }} style={{ marginBottom: 10 }} /> {game ? ( <GameCard displayTeamNames="small" hometeam={game.hometeam_name} hometeamAbbrev={game.hometeam_abbreviation} awayteam={game.awayteam_name} awayteamAbbrev={game.awayteam_abbreviation} > {editingBet ? ( <GameCardBet gameId={game.id} hadSaveIssues={editingBet && betSaveFailed} shouldSave={shouldSaveBet} userBet={userBet} onSaveFailure={this.handleBetSaveFailure} onSaveSuccess={this.handleBetSaveSuccess} /> ) : ( <GameCardGameInfo city={game.city} kickoff={toDate(parseISO(game.kickoff))} result={game.homegoals !== -1 && game.awaygoals !== -1 ? `${game.homegoals} : ${game.awaygoals}` : null} resultBetType={userBet ? userBet.result_bet_type : null} points={userBet ? userBet.points : null} userBet={userBet ? userBet.result_bet : null} /> )} </GameCard> ) : <NullGameCard />} {game && game.bets_open && ( <div className="CurrentGameCard__actions"> {editingBet && ( <> <Button color="primary" icon={<SaveIcon style={{ width: 20, height: 20 }} />} disabled={shouldSaveBet} onClick={this.handleBetSave} > Speichern </Button> <br /> <Button onClick={this.handleBetEditCancel}>Abbrechen</Button> </> )} {(!editingBet && !editingBetSuccessful) && ( <Button color="primary" icon={<EditIcon style={{ width: 20, height: 20 }} />} onClick={this.handleBetEdit} > {userBet ? 'Tipp ändern' : 'Tipp abgeben'} </Button> )} {editingBetSuccessful && ( <Notification type={NotificationType.SUCCESS} title="Gespeichert" dismissable disappearAfterMs={2000} containerStyle={{ margin: '3px auto', maxWidth: 215 }} onClose={() => this.setState({ editingBetSuccessful: false })} /> )} </div> )} <Dialog open={betSaveFailed} onClose={this.handleBetSaveErrorInfoDialogClosed}> <DialogTitle>Speichern fehlgeschlagen</DialogTitle> <DialogContent> {betSaveFailedType === SavingErrorType.INCOMPLETE && 'Bitte gib einen vollständigen Tipp ein.'} {betSaveFailedType === SavingErrorType.DEADLINE_PASSED && 'Die Deadline für diesen Tipp ist abgelaufen. Eine Tippabgabe ist daher leider nicht mehr möglich.'} {betSaveFailedType === SavingErrorType.FAILED && 'Das Speichern des Tipps ist leider fehlgeschlagen. Bitte versuche es erneut.'} </DialogContent> <DialogActions> <Button color="primary" onClick={this.handleBetSaveErrorInfoDialogClosed}> Ok </Button> </DialogActions> </Dialog> </div> ); } } CurrentGameCard.defaultProps = { game: null, userBet: null, onBetEditStart: () => {}, onBetEditCancel: () => {}, }; CurrentGameCard.propTypes = { game: PropTypes.shape(), userBet: PropTypes.shape(), onBetEditStart: PropTypes.func, onBetEditCancel: PropTypes.func, onBetEditDone: PropTypes.func.isRequired, theme: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types }; export default withTheme(CurrentGameCard);
import { ref, computed } from 'vue'; import { defineStore, acceptHMRUpdate } from 'pinia'; import useGetJobs from '@/composables/useGetJobs.mjs'; const jobs = Object.freeze(await useGetJobs()); export const useJobsStore = defineStore('jobsStore', () => { /*** State ***/ const activeTags = ref(new Set()); /*** Getters ***/ const tags = computed(() => { const allTags = jobs.flatMap(job => job.tags); const uniqueTags = new Set(allTags); return uniqueTags; }); const filteredJobs = computed(() => { if (!activeTags.value.size) return jobs; const matchingJobs = jobs.filter(job => [...activeTags.value].every(activeTag => job.tags.includes(activeTag))); return matchingJobs; }); /*** Actions ***/ function addTag(newTag) { if (!newTag || activeTags.value.has(newTag)) return false; activeTags.value.add(newTag); tags.value.delete(newTag); return true; } function deleteTag(tag) { activeTags.value.delete(tag); tags.value.add(tag); } function toggleTag(tag) { activeTags.value.has(tag) ? deleteTag(tag) : addTag(tag); } function deleteAllTags() { activeTags.value.clear(); } /*** Store API ***/ return { activeTags, tags, filteredJobs, addTag, toggleTag, deleteTag, deleteAllTags, }; }); if (import.meta.hot) import.meta.hot.accept(acceptHMRUpdate(useJobsStore, import.meta.hot));
# ordermanagement package com.example.demo.model; import javax.persistence.*; import java.util.Collection; @Entity public class Customer { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; private String name; private String email; private Integer bill; @ManyToMany @JoinTable(name="cust_order", joinColumns=@JoinColumn(name="cust_id", referencedColumnName="id"), inverseJoinColumns=@JoinColumn(name="order_id", referencedColumnName="id")) private Collection<Order> orders; public Customer(){ } public Customer(Integer id, String name, String email , Collection<Order> orders) { this.id=id; this.name = name; this.email = email; this.orders=orders; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; }public void setEmail(String email) { this.email = email; } public Integer getBill() { return bill; } public void setBill(Integer bill) { this.bill = bill; } public Collection<Order> getOrders() { return orders; } public void setOrders(Collection<Order> orders) { this.orders = orders; } } // package com.example.demo.model; public class Menu { private Integer m_id; private String dish; private Integer price; public Menu() { } public Menu(Integer m_id, String dish, Integer price) { this.m_id = m_id; this.dish=dish; this.price=price; } public Integer getM_id() { return m_id; } public void setM_id(Integer m_id) { this.m_id = m_id; } public String getDish() { return dish; } public void setDish(String dish) { this.dish = dish; } public Integer getPrice() { return price; } public void setPrice(Integer price) { this.price = price; } } // package com.example.demo.model; public class Order { private Integer id; //ref to customer id i.e foreign key private String dish; private int qunt; private int price; public Order(String dish, int qunt){ this.dish=dish; this.qunt=qunt; } public Order(String dish){ super(); this.dish=dish; } public Order(){ } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getDish() { return dish; } public void setItem(String dish) { this.dish = dish; } public int getQunt() { return qunt; } public void setQunt(int qunt) { this.qunt = qunt; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } } //customerrepo package com.example.demo.repository; import com.example.demo.model.Customer; import java.util.List; public interface CustomerRepo { int save(Customer record); int update(Customer record); Customer findById(Integer id); List<Customer> findAll(); } // package com.example.demo.repository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import com.example.demo.model.Customer; import com.example.demo.model.Order; import java.util.List; public class JdbcCustRepo implements CustomerRepo{ @Autowired private JdbcTemplate jdbcTemplate; @Override public int save(Customer customer){ return jdbcTemplate.update("INSERT INTO customer(id, name, email, orders) VALUES(?, ?, ?, ?)", new Object[] {customer.getId(), customer.getName(), customer.getEmail(), customer.getOrders() }); } @Override public int update(Customer customer){ return jdbcTemplate.update("UPDATE customers SET name=?, email=? WHERE id=?", new Object[] {customer.getName(), customer.getEmail(), customer.getId() }); } @Override public Customer findById(Integer id) { try { Customer customer = jdbcTemplate.queryForObject("SELECT * FROM customer WHERE id=?", BeanPropertyRowMapper.newInstance(Customer.class), id); return customer; } catch (IncorrectResultSizeDataAccessException e) { return null; } } @Override public List<Customer> findAll(){ return jdbcTemplate.query("SELECT * FROM customer", BeanPropertyRowMapper.newInstance(Customer.class)); } } // package com.example.demo.repository; import com.example.demo.model.Order; public interface OrderRepo { int save(Order record); int update(Order order); int deleteById(Long id); int deleteAll(); } //menurepo package com.example.demo.repository; import com.example.demo.model.Menu; import java.util.List; public interface MenuRepo { int save(Menu record); int update(Menu record); Menu findById(Integer id); List<Menu> findAll(); } // package com.example.demo.repository; import com.example.demo.model.Menu; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import java.util.List; @Repository public class JdbcMenuRepo implements MenuRepo { @Autowired JdbcTemplate jdbcTemplate; @Override public int save(Menu menu) { return jdbcTemplate.update("INSERT INTO menu(m_id, dish, price) VALUES(?, ?, ?)", new Object[]{menu.getM_id(), menu.getDish(), menu.getPrice()}); } @Override public int update(Menu menu) { return jdbcTemplate.update("UPDATE menu SET dish=?, price=? WHERE id=?", new Object[]{menu.getDish(), menu.getPrice(), menu.getM_id() }); } @Override public Menu findById(Integer id){ try{ Menu menu= jdbcTemplate.queryForObject("SELECT * FROM meu WHERE id=?", BeanPropertyRowMapper.newInstance(Menu.class), id); return menu; } catch (IncorrectResultSizeDataAccessException e) { return null; } } @Override public List<Menu> findAll() { return jdbcTemplate.query("SELECT * FROM menu", BeanPropertyRowMapper.newInstance(Menu.class)); } } //
from flask import Flask, render_template , request from flask_socketio import SocketIO from dotenv import load_dotenv import logging from threading import Event from banter_assignment.get_transcription import on_disconnect , start_transcription_loop , steve_intro load_dotenv() app = Flask(__name__) socketio = SocketIO(app) # Track transcription state transcribing = False not_started = True transcription_event = Event() @app.route('/talk_to_steve') def index(): start_countdown = request.args.get('start_countdown', 'false') # Change to start_countdown print("start_countdown:", start_countdown) # Check the value in console return render_template('index.html', start_countdown=start_countdown) @app.route('/') def home(): return render_template('home.html') @socketio.on('disconnect') def handle_disconnect(): socketio.start_background_task(target=on_disconnect) @socketio.on('start_steve_intro') def start_steve_intro(): global not_started if not not_started: return # If transcription has started, do nothing socketio.start_background_task(target=steve_intro, socketio=socketio) not_started = False @socketio.on('toggle_transcription') def toggle_transcription(data): global transcribing action = data.get('action') if action == 'start' and not transcribing: # Start transcription transcribing = True socketio.start_background_task(target=start_transcription_loop, transcribing=transcribing, transcription_event=transcription_event , socketio=socketio) elif action == 'stop' and transcribing: # Stop transcription transcribing = False transcription_event.set() if __name__ == '__main__': logging.info("Starting SocketIO server.") socketio.run(app, host='0.0.0.0', debug=True)
package com.example.catass.ui.views import com.example.catass.MainDispatcherRule import com.example.catass.model.CatItem import com.example.catass.model.Cats import com.example.catass.model.ResultWrapper import com.example.catass.repository.CatsRepository import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.whenever import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Rule import org.junit.Test class CatsViewModelTest { @get:Rule val mainDispatcherRule = MainDispatcherRule() private lateinit var catsRepository: CatsRepository private lateinit var catsViewModel: CatsViewModel @Before fun setUp() { catsRepository = mock() catsViewModel = CatsViewModel(catsRepository) } @Test fun `loadCats success`(): Unit = runTest { // Mock data val cats = Cats(listOf(CatItem("1", "Fluffy", 1, emptyList()))) whenever(catsRepository.getCats()).thenReturn(ResultWrapper.Success(cats)) // Call the function under test catsViewModel.loadCats() // Verify loading state assertEquals(false, catsViewModel.loading.first()) // Verify cats data assertEquals(cats, catsViewModel.cats.first()) // Verify error state assertEquals(null, catsViewModel.error.first()) // Verify repository method is called verify(catsRepository).getCats() // Verify loading state after completion assertEquals(false, catsViewModel.loading.first()) } @Test fun `loadCats error`(): Unit = runTest { // Mock error val errorMessage = "Error loading cats" whenever(catsRepository.getCats()).thenReturn(ResultWrapper.Error(Exception(errorMessage))) // Call the function under test catsViewModel.loadCats() // Verify loading state assertEquals(false, catsViewModel.loading.first()) // Verify error message assertEquals(errorMessage, catsViewModel.error.first()) // Verify cats data assertEquals(null, catsViewModel.cats.first()) // Verify repository method is called verify(catsRepository).getCats() // Verify loading state after completion assertEquals(false, catsViewModel.loading.first()) } }
import { useState } from 'react'; import { Modal, Button, Form } from 'react-bootstrap'; import MyAPI, { Item } from '../MyAPI'; import { useAlert } from 'react-alert'; const AdminEditableModel = ({ show, handleClose, leadData, reloadData }) => { let alert = useAlert(); const excludeFields = ['_id', 'account', 'createdAt', '__v','closingAmmount','closingReasone']; // Fields to exclude const editableFields = Object.keys(leadData).filter((key) => !excludeFields.includes(key)); const [formData, setFormData] = useState({ ...leadData }); const handleInputChange = (e) => { const { name, value } = e.target; setFormData({ ...formData, [name]: value }); }; const handleSaveChanges = () => { console.log('Updated Data:', formData); let token = Item.getItem('token'); MyAPI.post(`/lead/edit/${formData._id}`, formData, token) .then((res) => { reloadData(); if (res.data.success) { alert.success('lead updated successfully..!'); } else { alert.error('something wrong'); } }) leadData = null; handleClose(); }; return ( <Modal show={show} onHide={handleClose}> <Modal.Header closeButton> <Modal.Title>Edit Lead Data</Modal.Title> </Modal.Header> <Modal.Body> <Form> <div className="row"> {editableFields.map((key) => ( <div className="col-md-6 col-sm-12" key={key}> <Form.Group controlId={key}> <Form.Label>{key}</Form.Label> {key === 'status' ? ( <Form.Control as="select" name={key} value={formData[key]} onChange={handleInputChange}> <option value="pending">Pending</option> <option value="ongoing">On Going</option> <option value="close">Close</option> <option value="cancel">cancel</option> </Form.Control> ) : ( <Form.Control type="text" name={key} value={formData[key]} onChange={handleInputChange} /> )} </Form.Group> </div> ))} </div> </Form> </Modal.Body> <Modal.Footer> <Button variant="secondary" onClick={handleClose}> Close </Button> <Button variant="primary" onClick={handleSaveChanges}> Save Changes </Button> </Modal.Footer> </Modal> ); }; export default AdminEditableModel;
import VisibilityIcon from '@mui/icons-material/Visibility'; import { IconButton, Stack } from '@mui/material'; import L from 'leaflet'; import PropTypes from 'prop-types'; import { useEffect } from 'react'; import { Marker, Popup, useMap } from 'react-leaflet'; import MarkerClusterGroup from 'react-leaflet-cluster'; HomeMapMarker.propTypes = { plants: PropTypes.array.isRequired, openDetail: PropTypes.func.isRequired }; export default function HomeMapMarker({ plants, openDetail }) { const mapRef = useMap(); useEffect(() => { mapBounds(); }, []); const mapBounds = () => { let markerBounds = mapRef.getBounds(); plants.forEach((marker) => { markerBounds.extend([marker.latitude, marker.longitude]); }); mapRef.fitBounds(markerBounds); }; return ( <MarkerClusterGroup chunkedLoading maxClusterRadius={50}> {plants.map((plant) => ( <Marker position={L.latLng(plant.latitude, plant.longitude)} key={plant.id}> <Popup> <Stack direction="row" justifyContent="space-between" alignItems="center"> {plant.name} <IconButton onClick={() => openDetail(plant)}> <VisibilityIcon /> </IconButton> </Stack> </Popup> </Marker> ))} </MarkerClusterGroup> ); }
/** * @file oaPlatformMath.h * @author Rivaz (idv19c.rrivera@uartesdigitales.edu.mx) * @date 9/07/2021 */ #pragma once #include "oaPlatformDefines.h" #include "oaStdHeaders.h" #include "oaForDecUtilities.h" #include "oaPlatformTypes.h" namespace oaEngineSDK { /** * @brief math from this platform */ class OA_UTILITY_EXPORT PlatformMath { public: /** * @brief wraper of the cmath sqrtf * @param x * @return */ static FORCEINLINE float sqrt(const float x) { return std::sqrtf(x); } /** * @brief the infamous Q_rsqrt by sir John Karmak * @param number * @return 1/sqrt(x)d */ static float invSqrt(float number); /** * @brief cosine function in radians * @param r * @return */ static FORCEINLINE float cos(const float r) { return std::cosf(r); } /** * @brief sine function in radians * @param r * @return */ static FORCEINLINE float sin(const float r) { return std::sinf(r); } /** * @brief tangent function in radians * @param r * @return */ static FORCEINLINE float tan(const float r) { return std::tanf(r); } /** * @brief arc cosine function in radians * @param x * @return */ static FORCEINLINE float acos(const float x) { return std::acosf(x); } /** * @brief arc sine function in radians * @param x * @return */ static FORCEINLINE float asin(const float x) { return std::asinf(x); } /** * @brief arc tangent in radians * @param x * @return */ static FORCEINLINE float atan(const float x) { return std::atanf(x); } /** * @brief arc tangent from y/x * @param x * @param y * @return */ static FORCEINLINE float atan2(const float x,const float y) { return std::atan2f(y, x); } /** * @brief absolute value of a value * @tparam T * @param v * @return */ template<class T> static FORCEINLINE T abs(const T v) { return std::abs(v); } /** * @brief the maximum value between two value * @tparam T * @param v1 * @param v2 * @return */ template<class T> static FORCEINLINE T max(const T v1,const T v2) { return std::max(v1,v2); } /** * @brief the minimum value between two value * @tparam T * @param v1 * @param v2 * @return */ template<class T> static FORCEINLINE T min(const T v1,const T v2) { return std::min(v1, v2); } /** * @brief e to the poewr of v * @tparam T * @param v */ static FORCEINLINE float exp(const float v) { return std::expf(v); } /** * @brief modular function for floats * @tparam T * @param v1 * @param v2 */ static FORCEINLINE float mod(const float v1,const float v2) { return std::fmod(v1, v2); } /** * @brief the first value tho the power of the second one * @tparam T * @param v1 * @param v2 * @return */ static FORCEINLINE float pow(const float v1,const float v2) { return std::pow(v1, v2); } /** * @brief logaritmic function of the value */ static FORCEINLINE float log(const float v) { return std::log(v); } /** * @brief 1 if positive, -1 if negative, 0 if 0 * @tparam T * @param val * @return */ static FORCEINLINE float sign(const float v) { return float((0.f < v) - (v < 0)); } /** * @brief fast aproximation to sin * @param x * @return */ static FORCEINLINE float fastSin(const float x) { float x2 = x * x; return (1.f - .16605f * x2 + .00761f*x2*x2) * x; } /** * @brief fast aproximate to cos * @param x * @return */ static FORCEINLINE float fastCos(const float x) { float x2 = x * x; return 1.f - .4967f * x2 + .03705f * x2 * x2; } /** * @brief fast aproximate to tan * @param x * @return */ static FORCEINLINE float fastTan(const float x) { float x2 = x * x; return (1.f + .31755f * x2 + .20330f * x2 * x2) * x; } /** * @brief fast aproximation to acos * @param x * @return */ static FORCEINLINE float fastAcos(const float x) { float x2 = x * x; return sqrt(1 - x) * (1.5707288f - .2121144f * x + 0.074261f * x2 - .0187293f * x2 * x); } /** * @brief fast aproximation to asin * @param x * @return */ static FORCEINLINE float fastAsin(const float x) { float x2 = x * x; return HALF_PI - sqrt(1 - x) * (1.5707288f - .2121144f * x + 0.074261f * x2 - .0187293f * x2 * x); } /** * @brief fast aproximation to atan * @param x * @return */ static FORCEINLINE float fastAtan(const float x) { float x2 = x * x; float x4 = x2 * x2; float x6 = x4 * x2; return (0.9998660f - .3302995f*x2 + .180141f*x4 - .085133f*x6 + .0208351f*x6*x2) * x; } /** * @brief the module of a number in positives * @param number * @param modul * @return */ static FORCEINLINE uint32 mod(int32 number, uint32 modul) { return ((number % modul) + modul) % modul; } /** * @brief the module of a number in positives * @param number * @param modul * @return */ static FORCEINLINE float umodf(float number, float modul) { return std::fmodf(std::fmodf(number,modul) + modul , modul); } /** * @brief the module of a number * @param number * @param modul * @return */ static FORCEINLINE float modf(float number, float modul) { return std::fmodf(std::fmodf(number,modul) + modul , modul); } /** * @brief rounds f to the min value * @param f * @return */ static FORCEINLINE float floor(float f){ return std::floor(f); } /** * @brief interpolates a value between a and b * @param a if t is o * @param b if b is 1 * @param t a number between 0 and 1 * @return */ static FORCEINLINE float interpolate(float a, float b, float t){ //OA_ASSERT(t>=0 && t<=1); return (b-a)*t+a; } /** * @brief a cubic interpolation between a and b * @param a if t is 0 * @param b if t is 1 * @param t a number between 0 and 1 * @return */ static FORCEINLINE float smoothStep(float t){ OA_ASSERT(t>=0 && t<=1); return (3.0f - t * 2.0f) * t * t; } /** * @brief a cubic interpolation with a second derivative equal to zero on boundaries * @param a if t is 0 * @param b if t is 1 * @param t a number between 0 and 1 * @return */ static FORCEINLINE float smootherStep(float t){ OA_ASSERT(t>=0 && t<=1); return ((t * (t * 6.0f - 15.0f) + 10.0f) * t * t * t); } /** * @brief if a point is inside a sphere * @param _point * @param _sphere * @return */ static bool overlap(const Vector3f& _point,const Sphere& _sphere); /** * @brief if two spheres are intersecting * @param _sphere1 * @param _sphere2 * @return */ static bool overlap(const Sphere& _sphere1,const Sphere& _sphere2); /** * @brief checks if a point is inside a box * @param _point * @param _box * @return */ static bool overlap(const Vector3f& _point,const AABB& _box); /** * @brief checks if a shpere overlaps a box * @param _sphere * @param _box * @return */ static bool overlap(const Sphere& _sphere,const AABB& _box); /** * @brief checks if two boxes overlap * @param _box1 * @param _box2 * @return */ static bool overlap(const AABB& _box1,const AABB& _box2); /** * @brief checks if a point is inside a capsule * @param _point * @param _capsule * @return */ static bool overlap(const Vector3f& _point,const Capsule& _capsule); /** * @brief checks if a capsule and a sphere overlap * @param _sphere * @param _capsule * @return */ static bool overlap(const Sphere& _sphere,const Capsule& _capsule); /** * @brief * @param _box * @param _capsule * @return */ static bool overlap(const AABB& _box, const Capsule& _capsule); /** * @brief checks if two capsules are overlapping * @param _capsule1 * @param _capsule2 * @return */ static bool overlap(const Capsule& _capsule1,const Capsule& _capsule2); /** * @brief calculates the distance between the point p and this line * @param p * @return */ static float distance(const Line& _line, const Vector3f& _point); ///** // * @brief calculates the distance between two lines // * @param _line1 // * @param _line2 // * @return //*/ //static float //distance(const Line& _line1, const Line& _line2); /** * @brief calculates the distance between a point and a plane * @param _plane * @param _point * @return */ static float distance(const Plane& _plane, const Vector3f& _point); /** * @brief checks if a plane and a line intersect * @param _plane * @param _line * @param _point the point where the intersection ocurres * @return */ static bool intersect(const Plane& _plane, const Line& _line, Vector3f& _point); /** * @brief checks if 3 planes intersect * @param _plane1 * @param _plane2 * @param _plane3 * @param _point the point where the intersection occures * @return */ static bool intersect(const Plane& _plane1, const Plane& _plane2,const Plane& _plane3, Vector3f& _point); /** * @brief checks if 2 planes intersect * @param _plane1 * @param _plane2 * @param _line the line where the intersection occures * @return */ //static bool //intersect(const Plane& _plane1, const Plane& _plane2, Line& _line); /** * @brief calculates a gausean value at a certain point in x * @param x * @param mean * @param std_deviation * @return */ static float computeGaussianValue( float x, float mean, float std_deviation ); static const float PI; static const float HALF_PI; static const float TWO_PI; static const float INV_PI; static const float INV_TWO_PI; static const float RAD_TO_DEG; static const float DEG_TO_RAD; static const float MAX_FLOAT; }; }
import React from 'react'; import { connect, Link, withRouter } from 'umi'; import { get } from 'lodash'; import { IUser } from '@/pages/user/userSearch/types'; import { Dropdown, Menu } from 'antd'; interface IProps { User: IUser; } const TopMenu = (props: IProps) => { const location = get(props, 'location.pathname', ''); const acl = get(props, 'User.acl', []); const roles = get(props, 'User.roles', []); const menuItems = [ { path: '/base', name: 'Base', perm: 'base.get.own' }, { path: '/users', name: 'Users', perm: 'user.delete.any' }, { path: '/admin/challenge', name: 'Challenges', perm: 'challenge.update.any' }, { path: '/telephony', name: 'Telephony', perm: 'telephony.call.generate.token' }, { path: '/admin-order', name: 'Orders', perm: 'shop.product.create' }, ].map((el) => ({ ...el, isActive: location.startsWith(el.path), isVisible: acl.includes(el.perm), })); // role shop is supposed to see only "shop" submenu etc., so individual permissions are also implemented inside child components const rolesAllowedToAccessAdmin = ['admin', 'shop', 'challenge', 'telephony']; // check whether current user roles include at least one of roles that are allowed to access admin menu const adminIsPermitted: boolean = roles.some((role: string) => rolesAllowedToAccessAdmin.includes(role)); const menu = ( <Menu> {menuItems.map( (el) => el.isVisible && ( <Menu.Item key={el.path}> <Link to={el.path}>{el.name}</Link> </Menu.Item> ), )} </Menu> ); return ( <div id="top-menu" role="menu" className="d-flex align-items-center"> {adminIsPermitted && ( <Dropdown overlay={menu}> <a className="ant-dropdown-link" onClick={(e) => e.preventDefault()}> Admin </a> </Dropdown> )} </div> ); }; const mapStateToProps = (state: any) => ({ User: state.User, }); export default withRouter(connect(mapStateToProps)(TopMenu));
# Copyright 2008-2009 WebDriver committers # Copyright 2008-2009 Google Inc. # # 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 logging import time from webdriver_common.exceptions import ErrorInResponseException from webdriver_common.exceptions import InvalidSwitchToTargetException from webdriver_firefox.webelement import WebElement from webdriver_firefox.firefoxlauncher import FirefoxLauncher from webdriver_firefox.extensionconnection import ExtensionConnection from webdriver_firefox import utils class WebDriver(object): """The main interface to use for testing, which represents an idealised web browser.""" def __init__(self, profile_name="WebDriver", timeout=30): self.browser = FirefoxLauncher() self.browser.launch_browser(profile_name) self._conn = ExtensionConnection(timeout) self._conn.connect() def execute_script(self, script, *args): """Executes arbitrary javascript. For WebElement argument, the format is: execute_script("argument[0].value='cheese'", elem) """ converted_args = [] for arg in args: if type(arg) == WebElement: converted_args.append({"type": "ELEMENT", "value": arg.id}) else: converted_args.append({"type": "STRING", "value": arg}) resp = self._conn.driver_command("executeScript", script, converted_args) if "NULL" == resp["resultType"]: pass elif "ELEMENT" == resp["resultType"]: return WebElement(self, resp["response"]) else: return resp["response"] def get(self, url): """Loads a web page in the current browser.""" self._command("get", url) def get_current_url(self): """Gets the current url.""" return self._command("getCurrentUrl") def get_title(self): """Gets the title of the current page.""" return self._command("title") def find_element_by_xpath(self, xpath): """Finds an element by xpath.""" try: elem_id = self._command("selectElementUsingXPath", xpath) elem = WebElement(self, elem_id) except ErrorInResponseException, ex: utils.handle_find_element_exception(ex) return elem def find_element_by_link_text(self, link): """Finds an element by its link text. throws NoSuchElementException when no element is found with the link text. """ try: elem_id = self._command("selectElementUsingLink", link) elem = WebElement(self, elem_id) return elem except ErrorInResponseException, ex: utils.handle_find_element_exception(ex) def find_elements_by_link_text(self, link): """Finds all elements with the same link text. throws NoSuchElementException when no element is found with the link text. """ try: elem_id_list = self._command("selectElementsUsingLink", link) elem_list = [] for elem_id in elem_id_list.split(","): elem = WebElement(self, elem_id) elem_list.append(elem) return elem_list except ErrorInResponseException, ex: utils.handle_find_element_exception(ex) def find_element_by_id(self, id_): """Finds an element by its id.""" try: return self.find_element_by_xpath("//*[@id=\"%s\"]" % id_) except ErrorInResponseException, ex: utils.handle_find_element_exception(ex) def find_element_by_name(self, name): """Finds and element by its name.""" try: return self.find_element_by_xpath("//*[@name=\"%s\"]" % name) except ErrorInResponseException, ex: utils.handle_find_element_exception(ex) def find_elements_by_xpath(self, xpath): """Finds all the elements for the given xpath query.""" try: elem_ids = self._command("selectElementsUsingXPath", xpath) elems = [] if len(elem_ids): for elem_id in elem_ids.split(","): elem = WebElement(self, elem_id) elems.append(elem) return elems except ErrorInResponseException, ex: utils.handle_find_element_exception(ex) def get_page_source(self): """Gets the page source.""" return self._command("getPageSource") def close(self): """Closes the current window. Quit the browser if it's the last window open. """ if self._conn.is_connectable(): self._conn.driver_command("close") def quit(self): """Quits the driver and close every associated window.""" self._conn.quit() self.browser.kill() def switch_to_window(self, window_name): """Switches focus to a window.""" resp = self._command("switchToWindow", window_name) if not resp or "No window found" in resp: raise InvalidSwitchToTargetException( "Window %s not found" % window_name) self._conn.context = resp def get_current_window_handle(self): handle = self._command("getCurrentWindowHandle") assert "," not in handle, "there should be only one current handle" return handle def get_window_handles(self): return filter(lambda handle: handle, self._command("getAllWindowHandles").split(",")) def switch_to_frame(self, index_or_name): """Switches focus to a frame by index or name.""" self._command("switchToFrame", str(index_or_name)) def back(self): """Goes back in browser history.""" self._command("goBack") def forward(self): """Goes forward in browser history.""" self._command("goForward") def _command(self, cmd, *args): """Forward command on to the extension connection.""" return self._conn.driver_command(cmd, *args)["response"] @property def conn(self): return self._conn
// NotaItem.js import React from 'react'; import { FormGroup, Input, Label, Col, Button } from 'reactstrap'; import style from '../ListaTareas/Lista.module.css'; function Tarea({ tareas, cambiarEstado, eliminarTarea }) { return ( <li className={style.notaitem}> <FormGroup switch className={style.notalabel}> <Input type="checkbox" checked={tareas.completed} onChange={() => cambiarEstado(tareas.id)} /> <Label check className={style.notalabel}> <span className={tareas.completed ? style.completed : style.notcompleted}> {tareas.text} </span> </Label> </FormGroup> <FormGroup check row className={style.notadelete}> <Col sm={{ offset: 2, size: 10 }}> <Button color="danger" onClick={() => eliminarTarea(tareas.id)}> Eliminar </Button> </Col> </FormGroup> </li> ); } export default Tarea;
library(tidyverse) library(vegan) library(mice) library(SoDA) library(adespatial) library(pracma) # set random seed set.seed(999) #### Define utility functions #### create.dbmem = function (coord = NULL, D.mat = NULL, nsites, randtest=T) { if (is.null(coord) & is.null(D.mat)) stop("Geographic information must be provided in 'coord' or in 'D.mat'") if (is.null(D.mat)) D.mat <- dist(coord) D.mat <- as.matrix(D.mat) if (!is.null(coord)) { n <- nrow(coord) } else { n <- nrow(D.mat) } if (sum(nsites) != n) stop("Vector nsites does not sum to nrow(coord) or nrow(D.mat)") if (min(nsites) == 1) stop("At least one group contains a single site") out <- matrix(0, n, n) end <- 0 end.mem <- 0 for (k in 1:length(nsites)) { start <- end + 1 end <- end + nsites[k] tmp <- as.dist(D.mat[start:end, start:end]) res <- dbmem(tmp, MEM.autocor = "positive") if (randtest) { test.mem = moran.randtest(res, attributes(res)$listw) tb_res = as_tibble(res) sel_res = select(tb_res, test.mem$names[test.mem$pvalue<0.05]) } dbMEM <- as.matrix(sel_res) n.mem <- ncol(dbMEM) out[start:end, (end.mem + 1):(end.mem + n.mem)] <- dbMEM end.mem <- end.mem + n.mem } out <- out[, 1:end.mem] if (is.null(rownames(coord))) { rownames(out) <- rownames(out, do.NULL = FALSE, prefix = "Site.") } else { rownames(out) <- rownames(coord) } colnames(out) <- colnames(out, do.NULL = FALSE, prefix = "dbMEM.") out } calc_trophic_scores = function(x) { patho_score = function (x){ switch(x, "Pathotroph"=1, "Pathotroph-Symbiotroph"=1/2, "Pathotroph-Saprotroph"=1/2, "Pathotroph-Saprotroph-Symbiotroph"=1/3, 0) } sapro_score = function (x){ switch(x, "Saprotroph"=1, "Saprotroph-Symbiotroph"=1/2, "Pathotroph-Saprotroph"=1/2, "Pathotroph-Saprotroph-Symbiotroph"=1/3, 0) } symbio_score = function (x){ switch(x, "Symbiotroph"=1, "Pathotroph-Symbiotroph"=1/2, "Saprotroph-Symbiotroph"=1/2, "Pathotroph-Saprotroph-Symbiotroph"=1/3, 0) } patho_score = Vectorize(patho_score) sapro_score = Vectorize(sapro_score) symbio_score = Vectorize(symbio_score) pa = patho_score(x) sa = sapro_score(x) sy = symbio_score(x) return(tibble(patho=pa, sapro=sa, symbio=sy)) } #### Load raw data #### plant_traits = read_csv("data/plant_traits.csv") asv_table = read_csv("data/asv_table_renamed.csv") asv_annotations = read_csv("data/asv_annotations.csv") compartment_mapping = read_csv("data/compartment_mapping.csv") compartment_mapping = distinct(compartment_mapping, site, compartment) #### Alpha diversity #### asv_table_t = t(select(asv_table,-ASV_ID)) fungal_diversity = tibble( sample_id = rownames(asv_table_t), richness = specnumber(asv_table_t), shannon = diversity(asv_table_t, "shannon"), evenness = shannon / log(richness) ) total_traits = left_join(fungal_diversity, plant_traits, by="sample_id") #### Clustering #### run_optimize_clusters = FALSE if (run_optimize_clusters) { cluster_func = function(x, k) { d = vegdist(x, method="jaccard", binary="T") return(hcut(d, k)) } require(factoextra) fviz_nbclust(asv_table_t, cluster_func, method="gap_stat") ggsave("output/optimal_cluster_gap_stat.pdf", width=4.9, height=3.45, units="in") fviz_nbclust(asv_table_t, cluster_func, method="wss") ggsave("output/optimal_cluster_wss.pdf", width=4.9, height=3.45, units="in") } optimal_num_clusters = 7 clusters = asv_table_t %>% vegdist(method = "jaccard", binary = T) %>% hclust(method = "ward.D2") %>% cutree(k = optimal_num_clusters) total_traits$cluster = clusters #### Trophic composition #### tm = left_join(asv_table, distinct(asv_annotations, ASV_ID, trophic_mode), by="ASV_ID") ts = calc_trophic_scores(tm$trophic_mode) tms = tm %>% mutate(across(2:(ncol(tm)-1), ~ifelse(.x>0, 1, 0))) %>%group_by(trophic_mode) %>% summarise(across(2:(ncol(tm)-1), sum)) ttm = tms$trophic_mode ttm[which(is.na(ttm))] = "Unknowntroph" tdf = t(tms[,2:ncol(tms)]) sid = rownames(tdf) tdf = as_tibble(tdf) colnames(tdf) = ttm tdf$sample_id = sid total_traits = left_join(total_traits, tdf) asv_table_pa = select(asv_table, -ASV_ID) %>% decostand(method="pa", MARGIN=2) pa = (asv_table_pa * ts$patho) %>% as_tibble() %>% colSums() sa = (asv_table_pa * ts$sapro) %>% as_tibble() %>% colSums() sy = (asv_table_pa * ts$symbio) %>% as_tibble() %>% colSums() trophic_table = tibble( sample_id = colnames(asv_table_pa), patho = pa, sapro = sa, symbio = sy ) x = trophic_table[,2:4] %>% scale() center = sweep(x, 2, apply(x, 2, min),'-') R = apply(x, 2, max) - apply(x, 2, min) x_star = sweep(center, 2, R, "/") %>% as.data.frame() theta = (c(1,2,3)-1) * 2*pi/3 xm = sweep(x_star, 2, cos(theta), "*") ym = sweep(x_star, 2, sin(theta), "*") centroids = t(apply(cbind(xm, ym), 1, function(x) poly_center(x[1:3], x[4:6]))) area = apply(cbind(xm, ym), 1, function(x) polyarea(x[1:3], x[4:6])) trophic_table = trophic_table %>% mutate(patho_s = x_star[["patho"]], sapro_s = x_star[["sapro"]], symbio_s = x_star[["symbio"]], centroid_x = centroids[,1], centroid_y = centroids[,2], area = area) write_csv(trophic_table, "data/trophic_table.csv") #### Assign compartment #### total_traits = total_traits %>% left_join(compartment_mapping, by="site") %>% left_join(trophic_table, by="sample_id") #### Calculate climate PCs #### bioclim_vars = select(total_traits, V1:V19) clim_pc = prcomp(scale(bioclim_vars)) total_traits$cpc1 = clim_pc$x[,1] total_traits$cpc2 = clim_pc$x[,2] total_traits$cpc3 = clim_pc$x[,3] #### Generate dbMEM #### ordered = arrange(total_traits, origin) cartesian_coord = geoXY(ordered$lat, ordered$lon, unit=1000) # unit=km num_nat = sum(total_traits$origin == "AR") num_int = sum(total_traits$origin == "CN") dbMEMs = create.dbmem(coord=cartesian_coord, nsites=c(num_nat, num_int), randtest=T) dbMEMs.nat = colnames(dbMEMs[,which(dbMEMs[1,]!=0)]) dbMEMs.int = colnames(dbMEMs[,which(dbMEMs[nrow(dbMEMs),]!=0)]) total_traits = as_tibble(cbind(ordered, dbMEMs)) #### Data imputation #### total_traits = arrange(total_traits, sample_id) asv_table_t = t(select(asv_table, -ASV_ID)) %>% as.data.frame() %>% mutate(sample_id = rownames(.)) %>% arrange(sample_id) %>% select(-sample_id) host_predictor = c( "leafherb", "leafbio", "SSL", "SLA", "BI", "trichome", "saponins", "lignin") clim_predictor = c("cpc1", "cpc2", "cpc3") soil_predictor = c( "soil_water", "soil_PH", "soil_SOM", "soil_CN", "soil_NH", "soil_NO", "soil_AP") spatial_predictor = c(dbMEMs.nat, dbMEMs.int) all_predictor = c(clim_predictor, host_predictor, soil_predictor) d = select(total_traits, all_of(all_predictor)) temp_data = mice(d, m=5, maxit=50, meth='pmm', seed=999, printFlag=F) completed_data = complete(temp_data, 1) total_traits[,all_predictor] = completed_data #### Gamma richness of each cluster #### gamma_richness = NULL for (i in 1:7) { rowidx = which(total_traits$cluster == i) gamma_richness[i] = sum(colSums(asv_table_t[rowidx,]) > 0) } nsamples = count(total_traits, cluster, name="cluster_n") total_traits = total_traits %>% left_join(tibble(cluster=1:7, gamma_richness=gamma_richness), by="cluster") %>% left_join(nsamples, by="cluster") write_csv(total_traits, "data/total_traits_final.csv") write_csv(asv_table_t, "data/asv_table_final.csv")
#ifndef FILL_H #define FILL_H #include <iostream> #include <QPainter> #include <QPoint> #include <QStack> #include <QColor> #include <QImage> #include <ctime> #include <QDebug> #include "Brush.h" using namespace std; class Fill: public Brush{ private: QStack<QPoint> stack; QPixmap &_pixmap; QPen &_pen; QColor tempColor; public: Fill(QPixmap &map,QPainter &p, QPen &pen): Brush(1,p, pen), _pixmap(map),_pen(pen){ } void fillColor(QColor color){ tempColor = _pen.color(); _pen.setColor(color); } void restoreColor(){ _pen.setColor(tempColor); } void timeGetColor(){ clock_t start,end; start = clock(); qDebug()<<"start QT timing!"; for(int i=0;i<600;i++){ for(int j=0;j<400;j++){ getPixelColor(i,j); } } end = clock(); double endtime=(double)(end-start)/CLOCKS_PER_SEC; qDebug()<<"QT Total time:"<<endtime<<" s"; //s为单位 start = clock(); qDebug()<<"start MAP timing!"; for(int i=0;i<600;i++){ for(int j=0;j<400;j++){ MAP[i][j].getColor(); } } end = clock(); endtime=(double)(end-start)/CLOCKS_PER_SEC; qDebug()<<"MAP Total time:"<<endtime<<" s"; //s为单位 } /* * point:填充起始点 * * function: 填充任意封闭图形 * */ void fillShape(QPoint point, QColor newColor){ //将点击位置的颜色设置为需要替换的颜色 QColor oldColor = MAP[point.x()][point.y()].getColor(); if(oldColor==newColor) return; //笔刷设置为需要的新颜色 _pen.setColor(newColor); int xl,xr,i,x,y; x = point.x(); y = point.y(); bool spanNeedFill; QPoint pt(point); push(pt); while(!isEmpty()){ pt = pop(); y = pt.y(); x = pt.x(); while(MAP[x][y].getColor()==oldColor && x<599){ drawPixel(x,y); x++; } xr = x -1; x = pt.x() - 1; while(MAP[x][y].getColor()==oldColor && x>0){ drawPixel(x,y); x--; } xl = x + 1; x = xl; y = y + 1; while(x<xr){ spanNeedFill = false; while(MAP[x][y].getColor()==oldColor && x<599){ spanNeedFill = true; x++; } if(spanNeedFill){ pt.setX(x - 1); pt.setY(y); push(pt); spanNeedFill= false; } while(MAP[x][y].getColor()!=oldColor&&x<xr)x++; } x = xl; y = y-2; while(x<xr){ spanNeedFill = false; while(MAP[x][y].getColor()==oldColor && x<599){ spanNeedFill = true; x++; } if(spanNeedFill){ pt.setX(x - 1); pt.setY(y); push(pt); spanNeedFill= false; } while(MAP[x][y].getColor()!=oldColor&&x<xr)x++; } } } void push(QPoint p){ stack.push(p); } QPoint pop(){ return stack.pop(); } bool isEmpty(){ return stack.empty(); } QColor getPixelColor(int x,int y){ QImage image = _pixmap.toImage(); return image.pixelColor(x,y); } void getColorMap() { QImage image = _pixmap.toImage(); for(int i = 0;i < 600;i++){ for(int j = 0;j < 400;j++){ MAP[i][j].setColor(image.pixelColor(i,j)); } } } }; #endif // FILL_H
import React from 'react' export default function Navbar(props) { const onClick = (e) => { e.preventDefault(); const q = document.getElementById('searchBox2').value; props.handleSearch(q); } const handleModeClick = (e) => { e.preventDefault(); console.log("button clicked") props.toggleMode(); } return ( <nav className={`navbar navbar-expand-lg ${props.mode === 'dark' ? 'navbar-dark bg-dark' : 'navbar-light'}`} id='navbar'> <div className="container-fluid" style={{"fontFamily": "Pacifico, cursive"}}> <a className="navbar-brand" href="#">Image Gallery</a> <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span className="navbar-toggler-icon"></span> </button> <div className="collapse navbar-collapse" id="navbarSupportedContent"> <ul className="navbar-nav me-auto mb-2 mb-lg-0"> <li className="nav-item"> <a className="nav-link active" aria-current="page" href="#">Home</a> </li> </ul> <div className="form-check form-switch"> <input className="form-check-input box3" type="checkbox" role="switch" onInput={handleModeClick} id="flexSwitchCheckDefault"/> </div> {/* <button >mode change</button> */} <form className="d-flex" role="search"> <input className="form-control me-2" id='searchBox2' type="search" placeholder="Search" aria-label="Search" /> <button className="btn btn-outline-success" type="submit" onClick={onClick}>Search</button> </form> </div> </div> </nav> ) }
import React, { useContext } from "react"; import { Box, Button, FormControl, Grid, TextField, Typography, } from "@mui/material"; import { Link } from "react-router-dom"; import * as yup from "yup"; import { FaEnvelope, FaLock } from "react-icons/fa"; import Logo from "../../../assets/images/logo.png"; import { useFormik } from "formik"; import strings from "../../../assets/locals/locals"; import LanguageContext from "../../../context/langContext"; import { UserContext } from "../../../context/userContext"; const LogInPage = () => { const { login } = useContext(UserContext); const { lang } = useContext(LanguageContext); strings.setLanguage(lang); const formik = useFormik({ initialValues: { userName: "", password: "", }, validationSchema: yup.object({ userName: yup .string(strings.userNameEmptyError) .required(strings.userNameEmptyError), password: yup .string(strings.passwordNotString) .min(4, strings.passwordLessThanMin) .required(strings.passwordEmptyError), }), onSubmit: (data) => login(data), }); const inputs = [ { name: "userName", label: strings.userName, type: "text", id: "userName", icon: <FaEnvelope />, }, { name: "password", label: strings.password, type: "password", id: "password", icon: <FaLock />, }, ]; return ( <Grid container className={"mainContainer"}> <Grid item xs={11} lg={8} xl={8} justifyContent={"space-around"} bgcolor={"#fff"} borderRadius={"50px"} padding={{ xs: 1, sm: 1, md: 2, lg: 3 }} > <Grid container margin={2} justifyContent={"space-between"} alignItems={"center"} > <Grid item xs={12} sm={12} lg={6} xl={4}> <form onSubmit={formik.handleSubmit}> <Typography variant="h4" gutterBottom> {strings.login} </Typography> <Grid container alignItems="center" margin={1}> <FormControl fullWidth> {inputs.map(({ name, label, id, type, icon }) => ( <Grid container key={name} gap={{ xs: 0, sm: 0, md: 1, lg: 1 }} > <Grid item xs={2} sm={2} md={2} lg={1} display={"flex"} justifyContent={"center"} alignItems={"center"} > <Typography variant="h6" color={ formik.touched[name] && Boolean(formik.errors[name]) ? "#d32f2f" : "#FFB600" } > {icon} </Typography> </Grid> <Grid item xs={9} sm={9} lg={10} textAlign={lang === "ar" ? "right" : "left"} > <TextField style={{ direction: lang === "ar" ? "right" : "left", }} key={name} placeholder={label} fullWidth id={id} label={label} type={type} select={type === "select" ? true : false} name={name} margin="normal" value={formik.values[name]} onChange={formik.handleChange} onBlur={formik.handleBlur} error={ formik.touched[name] && Boolean(formik.errors[name]) } /> <Typography variant="p" fontSize={"15px"} textAlign={lang === "ar" ? "right" : "left"} color={"#D32F2F"} > {formik.touched[name] && formik.errors[name]} </Typography> </Grid> </Grid> ))} </FormControl> </Grid> </form> <Grid container> <Grid item xs={12} md={12} xl={12} lg={12}> <Button variant="contained" onClick={formik.handleSubmit} style={{ backgroundColor: "#FFB600" }} padding={2} > {strings.login} </Button> </Grid> </Grid> </Grid> <Grid item xs={12} sm={12} lg={6}> <Box component="img" src={Logo} sx={{ height: "450px", width: "100%" }} alt="sign up" /> </Grid> </Grid> </Grid> </Grid> ); }; export default LogInPage;
package com.sms.schoolmanagementsystem.model; import java.math.BigDecimal; import java.sql.Timestamp; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.UpdateTimestamp; import jakarta.persistence.*; @Entity @Table(name = "grades_assignment") public class Grades { private @Id @GeneratedValue Long id; @Column(name = "grade_calculation", precision = 10, scale = 2) private BigDecimal gradeCalculation; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "student_id") private Student student; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "course_id") private Course course; @Column(name = "created_at", nullable = false, updatable = false) @CreationTimestamp private Timestamp createdAt; @Column(name = "updated_at") @UpdateTimestamp private Timestamp updatedAt; Grades() { } Grades(BigDecimal gradeCalculation, Student student, Course course) { this.gradeCalculation = gradeCalculation; this.student = student; this.course = course; } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public BigDecimal getGradeCalculation() { return this.gradeCalculation; } public void setGradeCalculation(BigDecimal gradeCalculation) { this.gradeCalculation = gradeCalculation; } public Student getStudent() { return this.student; } public Course getCourse() { return this.course; } }
<script lang="ts"> import { page } from '$app/stores'; var mobileMenuOpen: Boolean = false; function toggleMobileMenu() { mobileMenuOpen = !mobileMenuOpen; } </script> <div class="flex items-center justify-between"> <!-- Logo --> <div class="pt-2"> <img src="/img/logo.jpg" alt="" /> </div> <!-- Menu items--> <div class="hidden md:flex space-x-6"> <a href="/" class="hover:text-darkGrayishBlue" class:nav-active-route={$page.url.pathname === '/'}>Home</a > <a href="/about" class="hover:text-darkGrayishBlue" class:nav-active-route={$page.url.pathname === '/about'}>About</a > <a href="/sign-up" class="hover:text-darkGrayishBlue" class:nav-active-route={$page.url.pathname === '/sign-up'}>Sign up</a > </div> <!-- Free button --> <a href="/sign-up" class="hidden md:block p-3 px-6 pt-2 text-white bg-brightRed rounded-full baseline hover:bg-brightRedLight" >Free Forever</a > <!-- Hamburger Icon --> <button on:click={toggleMobileMenu} id="menu-btn" class:open={mobileMenuOpen} class="block hamburger md:hidden focus:outline-none" > <span class="hamburger-top" /> <span class="hamburger-middle" /> <span class="hamburger-bottom" /> </button> </div> {#if mobileMenuOpen} <!-- Mobile Menu --> <div class="md:hidden"> <div id="menu" class="absolute flex flex-col items-center self-end py-8 mt-10 space-y-6 font-bold bg-white sm:w-auto sm:self-center left-6 right-6 drop-shadow-md" > <a href="/">Home</a> <a href="/about">About</a> <a href="/sign-up">Sign-up FREE</a> </div> </div> {/if}
import { useState } from "react"; import styled from "styled-components"; import Card from "@/Cabinet/components/Card/Card"; import { CardContentWrapper } from "@/Cabinet/components/Card/CardStyles"; import ClubMemoModalContainer from "@/Cabinet/components/Modals/ClubModal/ClubMemoModal.container"; import { ReactComponent as EditIcon } from "@/Cabinet/assets/images/edit.svg"; const ClubNoticeCard = ({ notice, isMaster, }: { notice: string; isMaster: boolean; }) => { const [showMemoModal, setShowMemoModal] = useState<boolean>(false); const [text, setText] = useState<string>(notice); const openModal = () => { setShowMemoModal(true); }; return ( <> <Card title={"동아리 메모"} gridArea={"clubNotice"} width={"350px"} height={"240px"} buttons={ isMaster ? [ { onClick: openModal, icon: EditIcon, isClickable: true, }, ] : [ // NOTE: 이 부분은 레이아웃을 유지하기 위한 placeholder 버튼입니다. { backgroundColor: "var(--card-bg-color)", onClick: () => {}, icon: null, isClickable: false, }, ] } > <> <CardContentWrapper> <ClubNoticeTextStyled>{notice}</ClubNoticeTextStyled> </CardContentWrapper> </> </Card> {showMemoModal && ( <ClubMemoModalContainer text={text} setText={setText} clubNotice={notice} setShowMemoModal={setShowMemoModal} /> )} </> ); }; const ClubNoticeTextStyled = styled.div` width: 100%; height: 150px; font-size: 1rem; padding: 0.5rem 1rem; word-break: break-all; white-space: pre-wrap; line-height: 1.2rem; overflow-y: auto; /* letter-spacing: 0.8px; */ ::-webkit-scrollbar { width: 20px; background-color: transparent; } ::-webkit-scrollbar-thumb { background: var(--line-color); border-radius: 50px; border: 6px solid transparent; background-clip: padding-box; display: inline-block; } `; export default ClubNoticeCard;
import Module.PTATM as PTATM from functools import reduce def genprobes(binary: str, functions: list, max_seg: int, verbose: bool): import angr from CFG2Segment import CFGBase, CFGRefactor, SFGBase, SFGBuilder # Parse binary with angr. if verbose: PTATM.info('Build angr cfg for binary[%s].' % binary) angr_project = angr.Project(binary, load_options={'auto_load_libs': False}) angr_cfg = angr_project.analyses.CFGFast() # Refactor CFG. if verbose: PTATM.info('Refactor angr cfg.') cfg = CFGBase.CFG(angr_cfg) cfg_refactor = CFGRefactor.FunctionalCFGRefactor() refactor_result = cfg_refactor.refactor(cfg) # Build SFG. if verbose: PTATM.info('Segment cfg with max_seg[%d] for function%s.' % (max_seg, functions)) sfg = SFGBase.SFG(cfg) sfg_builder = SFGBuilder.FunctionalSFGBuilder(max_seg, functions) build_result = sfg_builder.build(sfg) # Dump uprobes. if verbose: PTATM.info('Dump uprobes.') probes = [] for name in functions: segfunc = sfg.getSegmentFunc(name) if segfunc is None: continue for segment in segfunc.segments: offset = hex(segment.startpoint.addr - segfunc.addr) probe_prefix = segment.name + "=" probe_suffix = segfunc.name + ("+" + offset if offset != "0x0" else '') probes.append(probe_prefix + probe_suffix) probes.append(segfunc.name + "=" + segfunc.name + r"%return") return probes def service(args): if not hasattr(args, 'function'): args.function = ['main'] probes = genprobes(args.binary, args.function, args.max_seg, args.verbose) if len(probes) != 0: if args.verbose: PTATM.info(f'Save result into ➜ {args.output}') with open(args.output, 'a') as output: output.write('\n' + reduce(lambda x, y: x + ',' + y, probes)) if args.verbose: PTATM.info('Done.') elif args.verbose: PTATM.warn('Nothing to segment, check func arguments.')
/* * Licensed to The OpenNMS Group, Inc (TOG) under one or more * contributor license agreements. See the LICENSE.md file * distributed with this work for additional information * regarding copyright ownership. * * TOG licenses this file to You under the GNU Affero General * Public License Version 3 (the "License") or (at your option) * any later version. You may not use this file except in * compliance with the License. You may obtain a copy of the * License at: * * https://www.gnu.org/licenses/agpl-3.0.txt * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the * License. */ package org.opennms.web.event.filter; import org.opennms.web.filter.SubstringFilter; /** * Encapsulates all node filtering functionality. * * @author ranger * @version $Id: $ * @since 1.8.1 */ public class NodeNameLikeFilter extends SubstringFilter { /** Constant <code>TYPE="nodenamelike"</code> */ public static final String TYPE = "nodenamelike"; /** * <p>Constructor for NodeNameLikeFilter.</p> * * @param substring a {@link java.lang.String} object. */ public NodeNameLikeFilter(String substring) { super(TYPE, "NODE.NODELABEL", "node.label", substring); } /** {@inheritDoc} */ @Override public String getSQLTemplate() { return (" EVENTID IN (SELECT EVENTID FROM EVENTS JOIN NODE ON EVENTS.NODEID=NODE.NODEID WHERE NODE.NODELABEL ILIKE %s) "); } /** * <p>getTextDescription</p> * * @return a {@link java.lang.String} object. */ @Override public String getTextDescription() { return ("Node name containing \"" + getSubstring() + "\""); } /** * <p>toString</p> * * @return a {@link java.lang.String} object. */ @Override public String toString() { return ("<WebEventRepository.NodeNameContainingFilter: " + getDescription() + ">"); } /** * <p>getSubstring</p> * * @return a {@link java.lang.String} object. */ public String getSubstring() { return getValue(); } /** {@inheritDoc} */ @Override public boolean equals(Object obj) { if (obj == null) return false; if (!(obj instanceof NodeNameLikeFilter)) return false; return (this.toString().equals(obj.toString())); } }
package com.example.ejerciciobrubank.data.room import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.example.ejerciciobrubank.data.model.Movie /** * @author Axel Sanchez */ @Dao interface MovieDao { @Query("SELECT * FROM Movie WHERE `query` is null order by title") suspend fun getAllMovies(): List<Movie?> @Query("SELECT * FROM Movie where id = :idMovie") suspend fun getMovie(idMovie: Long): Movie? @Query("SELECT * FROM Movie WHERE `query` = :query") suspend fun getMoviesBySearch(query: String): List<Movie?> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertMovie(movie: Movie?): Long }
import { DetailedHTMLProps, InputHTMLAttributes } from "react" import cn from "../../utils/cn" interface TextInputProps { hint?: string label?: string id?: string required?: boolean readonly?: boolean type?: "text" | "password" | "email" tooltip?: { className?: string id?: string show?: boolean text: string } inputProps?: DetailedHTMLProps< InputHTMLAttributes<HTMLInputElement>, HTMLInputElement > dataTestId?: string onEnter?: () => void showInvalid?: boolean className?: string onChange?: (text: string) => void value?: string | undefined } /** * Component for TextInput fields */ const TextInput = ({ hint, label, id, required = false, readonly = false, type = "text", inputProps, dataTestId = "text-input", tooltip, onEnter, className, onChange, showInvalid = true, value, }: TextInputProps) => { return ( <div className="relative typo-text flex w-full flex-col gap-1"> <input required={required} readOnly={readonly} aria-label={"input"} data-testid={dataTestId} id={id} {...inputProps} className={cn( "h-10 w-full order-2 peer rounded border bg-white/5 text-white border-white p-2", showInvalid && "invalid:border-2 invalid:bg-red-200/20 invalid:text-white", className, )} type={type} value={value} onKeyDown={(event) => { if (event.key === "Enter") { onEnter?.() } }} placeholder={hint} onChange={(e) => onChange?.call(this, e.target.value)} /> {tooltip?.show && ( <p id={tooltip?.id} className={cn( "order-3 absolute ml-4 mr-[-2rem] -translate-y-2 rounded-md bg-gray-800 px-2 py-1 text-sm text-white transition-opacity duration-500 xs:ml-20 md:mr-[-4rem]", tooltip?.className, )} > {tooltip?.text} </p> )} {label && ( <label htmlFor={id} className="peer-group inline-flex order-1 text-white" > {label} <span className=" ml-1 block peer-group-valid:hidden text-red-400"> {required && "*"} </span> </label> )} </div> ) } export default TextInput
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HomeComponent } from './components/home.component'; import { ReadingComponent } from './components/reading.component'; import { ReadingThreeComponent } from './components/reading-three.component'; import { SearchResultComponent } from './components/search-result.component'; import { SavedReadingsComponent } from './components/saved-readings.component'; const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'daily', component: ReadingComponent }, { path: 'ppf', component: ReadingThreeComponent }, { path: 'search', component: SearchResultComponent }, { path: 'saved', component: SavedReadingsComponent }, { path: '**', redirectTo: 'landing', pathMatch: 'full' } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
import React from "react"; import {useState, useEffect} from "react" import Navbar from "./components/Navbar" import Main from "./components/Main" export default function App() { const [mode, setMode] = useState(true); const changeMode = () => { setMode(!mode); } useEffect(() => { localStorage.setItem("mode", JSON.stringify(mode)) }, [mode]) return ( <div className = {mode ? "dark bg-darkbg" : "bg-lightbg"}> <Navbar darkMode={mode} changeTheme={changeMode} /> <Main mode={mode}/> </div> ); }
# Module: tree_search # # This module provides a set o classes for automated # problem solving through tree search: # SearchNode - search tree nodes # SearchTree - search tree with the necessary methods for searhing # # (c) Luis Seabra Lopes # Introducao a Inteligencia Artificial, 2012-2019, # Inteligência Artificial, 2014-2019 from common import Map,Coordinates # Nos de uma arvore de pesquisa class SearchNode: def __init__(self,state: Map,parent: Map, change , heuristic = None): self.state = state self.parent = parent self.change = change self.heuristic = heuristic def __str__(self): return "no(" + str(self.state) + "," + str(self.parent) + ")" def __repr__(self): return str(self) # Arvores de pesquisa class SearchTree: def heuristic(self, map:Map, d_cars): if map.piece_coordinates(Map.player_car)[0].x == map.grid_size -2: return 0 blockcars = 0 blockingcars = [] player_car_size = len(map.piece_coordinates(Map.player_car)) for car in d_cars: if car[2] == "V" and map.piece_coordinates(car[0])[0].x >= (map.piece_coordinates(Map.player_car)[0].x + player_car_size) and (map.piece_coordinates(car[0])[0].y <= map.piece_coordinates(Map.player_car)[0].y and map.piece_coordinates(car[0])[0].y + car[1] > map.piece_coordinates(Map.player_car)[0].y ): blockcars += 1 blockingcars.append(car) blocking2 = {} for v in blockingcars: d = self.getBestDirection(map,v,d_cars) if d == "Up": for vv in d_cars: if vv != v and map.piece_coordinates(vv[0])[0].y < 2 and map.piece_coordinates(vv[0])[0].y <= map.piece_coordinates(v[0])[0].x - v[1] and map.piece_coordinates(vv[0])[0].x <= map.piece_coordinates(v[0])[0].x and map.piece_coordinates(vv[0])[0].x + vv[1] > map.piece_coordinates(v[0])[0].x and vv[2] == "H": blocking2[vv] = 1 else: for vv in d_cars: if vv != v and map.piece_coordinates(vv[0])[0].y > 2 and map.piece_coordinates(vv[0])[0].y >= map.piece_coordinates(v[0])[0].y + v[1] and ((map.piece_coordinates(vv[0])[0].x <= map.piece_coordinates(v[0])[0].x and map.piece_coordinates(vv[0])[0].x + vv[1] > map.piece_coordinates(v[0])[0].x and vv[2] == "H") or (vv[2] == "V" and map.piece_coordinates(vv[0])[0].x) == map.piece_coordinates(v[0])[0].x): blocking2[vv] = 1 blockcars += len(blocking2) return blockcars def getBestDirection(self, map,vehicle,cars): if vehicle[1] == 3: return "Down" carUp = 0 carDown = 0 for car in cars: if car != vehicle: if map.piece_coordinates(car[0])[0].y > 2 and map.piece_coordinates(car[0])[0].y >= 2 + vehicle[1] and ((map.piece_coordinates(car[0])[0].x < map.piece_coordinates(vehicle[0])[0].x and map.piece_coordinates(car[0])[0].x + car[1] > map.piece_coordinates(vehicle[0])[0].x and car[2] == "H") or (car[2] == "V" and map.piece_coordinates(car[0])[0].x == map.piece_coordinates(vehicle[0])[0].x)): carDown += 1 if map.piece_coordinates(car[0])[0].y < 2 and map.piece_coordinates(car[0])[0].y <= 2 - vehicle[1] and map.piece_coordinates(car[0])[0].x <= map.piece_coordinates(vehicle[0])[0].x and map.piece_coordinates(car[0])[0].x + car[1] > map.piece_coordinates(vehicle[0])[0].x and car[2] == "H": carUp += 1 if carUp >= carDown: return "Down" return "Up" # construtor def __init__(self,problem: Map, strategy, goal = None): self.strategy = strategy root = SearchNode(problem,None,(),0) self.open_nodes = [root] self.solution = None self.goal = goal def get_path(self,node): if node.parent == None: return [node.state] path = self.get_path(node.parent) path += [node.state] return(path) def get_actions(self,node): if node.parent == None: return [node.change] path = self.get_actions(node.parent) path += [node.change] return(path) # procurar a solucao def search(self): states_visited = set() level = 0 while self.open_nodes != []: node = self.open_nodes.pop(0) if self.goal == None: if node.state.test_win(): print("\n\n\n\n\n\nWiiiin\n\n\n\n\n\n") self.solution = node return (self.get_path(node),self.get_actions(node)) else: if str(node.state) == str(self.goal): self.solution = node return (self.get_path(node),self.get_actions(node)) lnewnodes = set() if node.state.pieces != level: d_cars = self.Direction_cars(node.state) level = node.state.pieces teste = str(node.state) for car,move in self.moves(d_cars, node.state): copy = Map(teste) copy.move(car,move) strcopy = str(copy) if strcopy not in states_visited: if self.strategy == 'a*': newnode = SearchNode(copy,node,(car,move),self.heuristic(copy,d_cars)) else: newnode = SearchNode(copy,node,(car,move)) states_visited.add(strcopy) lnewnodes.add(newnode) self.add_to_open(lnewnodes) return None def moves(self, cars, map): # function return possivel moves all_moves =[] linha_Pcar,coluna_Pcar = map.piece_coordinates(Map.player_car) if map.grid[linha_Pcar.y][coluna_Pcar.x:].count('o') == map.grid_size - coluna_Pcar.x -1 and self.goal == None: return [(Map.player_car,Coordinates(1,0))] else: for car in cars: carx = map.piece_coordinates(car[0])[0].x cary = map.piece_coordinates(car[0])[0].y if car[2] == "H": if carx - 1 >= 0 and map.grid[cary][carx -1] == 'o': all_moves.append((car[0],Coordinates(-1,0))) if carx + car[1] <= ((map.grid_size) -1) and map.grid[cary][carx + car[1]] == 'o': all_moves.append((car[0],Coordinates(1,0))) else: if cary - 1 >= 0 and map.grid[cary -1][carx] == 'o': all_moves.append((car[0],Coordinates(0,-1))) if cary + car[1] <= ((map.grid_size) -1) and map.grid[cary + car[1]][carx] == 'o': all_moves.append((car[0],Coordinates(0,1))) return all_moves def Direction_cars(self, mapa: Map): cars = set() #lista de tuplos que contem os carros horizontais e o seu tamanho line = str(mapa).split()[1] for i in line: if i.isupper(): car = i cor = mapa.piece_coordinates(car) if cor[0].y == cor[(len(cor)) -1].y: cars.add((car,len(cor),"H")) else: cars.add((car,len(cor),"V")) return list(cars) # juntar novos nos a lista de nos abertos de acordo com a estrategia def add_to_open(self,lnewnodes): if self.strategy == 'breadth': self.open_nodes.extend(lnewnodes) elif self.strategy == 'a*': self.open_nodes.extend(lnewnodes) self.open_nodes.sort(key = lambda node: node.heuristic)
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:mobx/mobx.dart'; import 'package:blocks_game/enums.dart'; part 'controller.g.dart'; class Controller = ControllerBase with _$Controller; abstract class ControllerBase with Store { Color fallingColor = Colors.grey.shade400; int gridSize = 5; // @observables are state variables that should only be modified by @actions // Once their value changes, the Observer widget is notified and rebuilds whatever is necessary @observable GameState gameState = GameState.notStarted; @observable List<ObservableList<Color>> blockColors = []; @observable bool isFalling = false; @observable int fallingRowIndex = 0; @observable int fallingColIndex = 0; @observable int score = 0; // An @action is simply a method that modifies @observables // This method/action essentially populates the blockColors observable @action void initializeBlockColors() { blockColors = List.generate( gridSize, (index) => ObservableList<Color>.of(List.filled(gridSize, Colors.white)), ); } @action void startGame() { gameState = GameState.playing; initializeBlockColors(); score = 0; } @action void fallingAnimation(int rowIndex, int colIndex, BuildContext context) { fallingRowIndex = rowIndex; fallingColIndex = colIndex; blockColors[fallingRowIndex][fallingColIndex] = fallingColor; isFalling = true; const duration = Duration(milliseconds: 250); Timer.periodic(duration, (timer) { if (isFalling) { _handleCollisionCases(context); } else { resetPreviousBlock(); timer.cancel(); } }); } @action void resetPreviousBlock() { if (fallingRowIndex > 0) { blockColors[fallingRowIndex - 1][fallingColIndex] = Colors.white; } } @action void _handleCollision(BuildContext context) { isFalling = false; resetPreviousBlock(); blockColors[fallingRowIndex][fallingColIndex] = fallingColor; _calculateColoredBlocksScore(); _autoEndGame(context); } @action void handleNoCollision() { fallingRowIndex++; resetPreviousBlock(); } @action void _handleCollisionCases(BuildContext context) { // The colored block has collided with the bottom of the screen if (fallingRowIndex == gridSize - 1) { _handleCollision(context); // The colored block has collided with a colored block below it } else if (fallingRowIndex < gridSize - 1 && blockColors[fallingRowIndex + 1][fallingColIndex] != Colors.white) { _handleCollision(context); // The colored block has formed a bridge with one colored block at each side } else if (fallingRowIndex < gridSize - 1 && fallingColIndex > 0 && fallingColIndex < 4 && blockColors[fallingRowIndex][fallingColIndex - 1] != Colors.white && blockColors[fallingRowIndex][fallingColIndex + 1] != Colors.white) { _handleCollision(context); // The colored block has not yet collided with anything } else { handleNoCollision(); } } // This method is called after every collision, as opposed to the white blocks which are only calculated at the end of the game @action void _calculateColoredBlocksScore() { Color currentColor = blockColors[fallingRowIndex][fallingColIndex]; if (fallingRowIndex == gridSize - 1 && currentColor != Colors.white) { score += 5; } else if (fallingRowIndex < gridSize - 1 && blockColors[fallingRowIndex + 1][fallingColIndex] != Colors.white) { int coloredBlocksBelow = 0; for (int i = fallingRowIndex + 1; i < gridSize; i++) { if (blockColors[i][fallingColIndex] != Colors.white) { coloredBlocksBelow++; } else { break; } } if (coloredBlocksBelow > 0) { score += 5 + (5 * coloredBlocksBelow); } } else if (fallingRowIndex < gridSize - 1 && fallingColIndex > 0 && blockColors[fallingRowIndex][fallingColIndex - 1] != Colors.white && blockColors[fallingRowIndex][fallingColIndex + 1] != Colors.white) { score += 5; } } // Calculates the score for the white blocks at the end of the game @action void _calculateWhiteBlocksScore() { for (int colIndex = 0; colIndex < gridSize; colIndex++) { for (int rowIndex = 1; rowIndex < gridSize; rowIndex++) { if (blockColors[rowIndex][colIndex] == Colors.white) { // Check if there's a colored block above the white block for (int i = rowIndex - 1; i >= 0; i--) { if (blockColors[i][colIndex] != Colors.white) { // Found a colored block above the white block score += 10; break; } } } } } } @action Future<void> showEndGameConfirmationDialog(BuildContext context) async { return showDialog<void>( context: context, builder: (BuildContext context) { return AlertDialog( title: const Text('Are you sure?'), actions: <Widget>[ TextButton( onPressed: () { Navigator.of(context).pop(); }, child: const Text('No'), ), TextButton( onPressed: () { Navigator.of(context).pop(); _calculateWhiteBlocksScore(); gameState = GameState.finished; _showFinalScoreDialog(context); }, child: const Text('Yes'), ), ], ); }, ); } @action void _showFinalScoreDialog(BuildContext context) { showDialog<void>( context: context, builder: (BuildContext context) { return AlertDialog( title: const Text('Thanks for playing!'), content: Text( 'Your Score: $score', style: Theme.of(context).textTheme.headlineSmall!.copyWith(color: Colors.pink.shade300), ), actions: <Widget>[ TextButton( onPressed: () { Navigator.of(context).pop(); initializeBlockColors(); startGame(); }, child: const Text('Play Again'), ), ], ); }, ); } // If there are 10 blocks with "fallingColor", the game ends automatically void _autoEndGame(BuildContext context) { int count = 0; for (int i = 0; i < gridSize; i++) { for (int j = 0; j < gridSize; j++) { if (blockColors[i][j] == fallingColor) { count++; } } } if (count >= 10) { _calculateWhiteBlocksScore(); gameState = GameState.finished; _showFinalScoreDialog(context); } } }
import { useContext } from "react"; import AppContext from "../contexts/AppContext"; import { productos } from "../productos" export function Carousel() { let { setCount } = useContext(AppContext) return ( <div id="carouselExampleDark" className="carousel slide" data-bs-ride="carousel"> <div className="carousel-inner"> {productos.map(function (prod, indice) { if (indice < 4) { return ( <div className="carousel-item" key={indice}> <div className=" d-flex flex-wrap justify-content-center"> <img src={prod.linkImg} className="rounded d-block w-50" alt={prod.nombre} /> <div className="carousel-text d-flex flex-column w-25 mx-1 align-self-center"> <h3>${prod.precio}</h3> <p>{prod.descrip}</p> { prod.cant === 0 ? <button type="button" className='compar' onClick={() => { prod.cant += 1; setCount((c) => c + 1) }}>Comprar</button> : <div className="d-flex flex-row count"> <button onClick={() => { prod.cant -= 1; setCount((c) => c - 1) }}><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" className="bi bi-arrow-left-circle-fill" viewBox="0 0 16 16"> <path d="M8 0a8 8 0 1 0 0 16A8 8 0 0 0 8 0zm3.5 7.5a.5.5 0 0 1 0 1H5.707l2.147 2.146a.5.5 0 0 1-.708.708l-3-3a.5.5 0 0 1 0-.708l3-3a.5.5 0 1 1 .708.708L5.707 7.5H11.5z" /> </svg></button> <span className='align-self-center h-100'>{prod.cant}</span> <button onClick={() => { prod.cant += 1; setCount((c) => c + 1) }}><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" className="bi bi-arrow-right-circle-fill" viewBox="0 0 16 16"> <path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0zM4.5 7.5a.5.5 0 0 0 0 1h5.793l-2.147 2.146a.5.5 0 0 0 .708.708l3-3a.5.5 0 0 0 0-.708l-3-3a.5.5 0 1 0-.708.708L10.293 7.5H4.5z" /> </svg></button> </div> } </div> </div> </div> ) } }) } <div className="carousel-item active "> <div className=" d-flex flex-wrap justify-content-center"> <img src={productos[4].linkImg} className="rounded d-block w-50" alt={productos[4].nombre} /> <div className="carousel-text d-flex flex-column w-25 mx-1 align-self-center"> <h3>${productos[4].precio}</h3> <p>{productos[4].descrip}</p> { productos[4].cant === 0 ? <button type="button" className='compar' onClick={() => { productos[4].cant += 1; setCount((c) => c + 1) }}>Comprar</button> : <div className="d-flex flex-row count"> <button onClick={() => { productos[4].cant -= 1; setCount((c) => c - 1) }}><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" className="bi bi-arrow-left-circle-fill" viewBox="0 0 16 16"> <path d="M8 0a8 8 0 1 0 0 16A8 8 0 0 0 8 0zm3.5 7.5a.5.5 0 0 1 0 1H5.707l2.147 2.146a.5.5 0 0 1-.708.708l-3-3a.5.5 0 0 1 0-.708l3-3a.5.5 0 1 1 .708.708L5.707 7.5H11.5z" /> </svg></button> <span className='align-self-center h-100'>{productos[4].cant}</span> <button onClick={() => { productos[4].cant += 1; setCount((c) => c + 1) }}><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" className="bi bi-arrow-right-circle-fill" viewBox="0 0 16 16"> <path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0zM4.5 7.5a.5.5 0 0 0 0 1h5.793l-2.147 2.146a.5.5 0 0 0 .708.708l3-3a.5.5 0 0 0 0-.708l-3-3a.5.5 0 1 0-.708.708L10.293 7.5H4.5z" /> </svg></button> </div> } </div> </div> </div> <button className="carousel-control-prev" type="button" data-bs-target="#carouselExampleDark" data-bs-slide="prev"> <span className="carousel-control-prev-icon" aria-hidden="true"></span> <span className="visually-hidden">Previous</span> </button> <button className="carousel-control-next" type="button" data-bs-target="#carouselExampleDark" data-bs-slide="next"> <span className="carousel-control-next-icon" aria-hidden="true"></span> <span className="visually-hidden">Next</span> </button> </div> </div> ) }
import { BadRequestException, Body, Controller, Delete, Get, Param, Patch, Post, Query, Req, UseGuards, } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; import { ApiBearerAuth, ApiOperation, ApiParam, ApiQuery, ApiResponse, ApiTags, } from '@nestjs/swagger'; import { Request } from 'express'; import { CreateUserDto } from './dto/create-user.dto'; import { UpdateUserDto } from './dto/update-user.dto'; import { UserService } from './user.service'; @ApiBearerAuth() @UseGuards(AuthGuard('jwt')) @ApiTags('User') @Controller('user') export class UserController { constructor(private readonly userService: UserService) {} @ApiOperation({ summary: 'Create User', description: '- Allows you to create complete user', }) @ApiResponse({ status: 201, description: 'Success in creation', schema: { default: { id: 1, user_name: 'johnD@e10', password: '12@#!10Aa', user_is_active: 1, createdAt: '2023-08-31T12:00:58.723Z', updatedAt: null, canceledAt: null, }, }, }) @ApiResponse({ status: 400, description: 'Incorrect request, incorrect or missing information', schema: { default: { statusCode: 400, message: 'User already registered', error: 'Bad Request', }, }, }) @ApiResponse({ status: 401, description: 'Not authorized access', schema: { default: [ { statusCode: 401, message: 'Unauthorized', }, ], }, }) @Post() async create( @Body() createUserDto: CreateUserDto, @Req() request: Request, ): Promise<any> { const authenticatedUser = request.user; if (!authenticatedUser) { throw new BadRequestException('Unauthenticated user'); } return await this.userService.create(createUserDto, authenticatedUser); } @ApiOperation({ summary: 'List all Users', description: '- It has the function of listing all registered users, displaying all the details', }) @ApiResponse({ status: 200, description: 'Success in the request', schema: { default: [ { id: 1, user_name: 'johnD@e10', password: '12@#!10Aa', user_is_active: 1, createdAt: '2023-08-31T12:00:58.723Z', updatedAt: null, canceledAt: null, }, { id: 2, user_name: 'johnD@e20', user_is_active: 1, createdAt: '2023-09-01T12:00:58.723Z', updatedAt: null, canceledAt: null, }, ], }, }) @ApiResponse({ status: 400, description: 'Incorrect request, incorrect or missing information', schema: { default: { statusCode: 400, message: 'Users not found', error: 'Bad Request', }, }, }) @ApiResponse({ status: 401, description: 'Not authorized access', schema: { default: { statusCode: 401, message: 'Unauthorized', }, }, }) @ApiQuery({ name: 'skip', type: String, required: true, description: 'Start listing users from the first registered (e.g., 0)', example: '0', }) @ApiQuery({ name: 'take', type: String, required: true, description: 'How many users will be listed per page (e.g., 10)', example: '10', }) @Get() async findAll( @Query('skip') skip: string, @Query('take') take: string, ): Promise<any> { return await this.userService.findAll(parseInt(take), parseInt(skip)); } @ApiOperation({ summary: 'Find unique User', description: '- Function that queries a registered user based on their identifier', }) @ApiResponse({ status: 200, description: 'Success in the request', schema: { default: { id: 1, user_name: 'johnD@e10', password: '12@#!10Aa', user_is_active: 1, createdAt: '2023-08-31T12:00:58.723Z', updatedAt: null, canceledAt: null, }, }, }) @ApiResponse({ status: 400, description: 'Incorrect request, incorrect or missing information', schema: { default: { statusCode: 400, message: 'User #id not found', error: 'Bad Request', }, }, }) @ApiResponse({ status: 401, description: 'Not authorized access', schema: { default: { statusCode: 401, message: 'Unauthorized', }, }, }) @ApiParam({ name: 'id', type: String, required: true, description: 'User ID (e.g., 1, 2, 3)', example: '1', }) @Get(':id') async findOne(@Param('id') id: string): Promise<any> { return await this.userService.findOne(+id); } @ApiOperation({ summary: "Update information's of one unique User", description: "- Function that is responsible for updating some data in the user's registration", }) @ApiResponse({ status: 200, description: 'OK', schema: { default: { id: 1, user_name: 'D@e100', user_is_active: 1, createdAt: '2023-08-31T12:00:58.723Z', updatedAt: '2023-09-08T12:00:58.723Z', canceledAt: null, }, }, }) @ApiResponse({ status: 400, description: 'Incorrect request, incorrect or missing information', schema: { default: { statusCode: 400, message: 'User #id not found', error: 'Bad Request', }, }, }) @ApiResponse({ status: 401, description: 'Not authorized access', schema: { default: { statusCode: 401, message: 'Unauthorized', }, }, }) @ApiParam({ name: 'id', type: String, required: true, description: 'User ID (e.g., 1, 2, 3)', example: '1', }) @Patch(':id') async update( @Param('id') id: string, @Body() updateUserDto: UpdateUserDto, @Req() request: Request, ): Promise<any> { const authenticatedUser = request.user; if (!authenticatedUser) { throw new BadRequestException('Unauthenticated user'); } return await this.userService.update(+id, updateUserDto, authenticatedUser); } @ApiOperation({ summary: 'Disable a User', description: "- Function responsible for deactivating a user's registration", }) @ApiResponse({ status: 200, description: 'Success in the request', schema: { default: { id: 1, user_name: 'D@e100', user_is_active: 0, createdAt: '2023-08-31T12:00:58.723Z', updatedAt: '2023-09-08T12:00:58.723Z', canceledAt: '2023-09-15T12:00:58.723Z', }, }, }) @ApiResponse({ status: 400, description: 'Incorrect request, incorrect or missing information', schema: { default: { statusCode: 400, message: 'User #id not found', error: 'Bad Request', }, }, }) @ApiResponse({ status: 401, description: 'Not authorized access', schema: { default: { statusCode: 401, message: 'Unauthorized', }, }, }) @ApiParam({ name: 'id', type: String, required: true, description: 'User ID (e.g., 1, 2, 3)', example: '1', }) @Delete(':id') async remove(@Param('id') id: string, @Req() request: Request): Promise<any> { const authenticatedUser = request.user; if (!authenticatedUser) { throw new BadRequestException('Unauthenticated user'); } return await this.userService.remove(+id, authenticatedUser); } }
--- title: "First Game Developed!" publishedAt: "2023-08-20" summary: "Documenting the development of my first game." --- While working at Unity I attended several of their game dev nights, where I worked on a game called Lightspeed. You can play it for free on [itch.io](https://itch.io). This post is dedicated to my process while making the game. Screenshots included. I first had the idea for my game in March of this year, waking up in the middle of the night to take my phone and jot down what I thought was possible with the game. - The game involves you, a spaceship, trying to maneuver around planets come at you from the center. I wanted to focus on a camera that would pan in and out based on your position away from the center, creating a cool speed effect. I planned on making it story based, like [Exo One](https://store.steampowered.com/app/773370/Exo_One/), but decided to go with a high score game. My first game dev night was somewhere back in May; the second week after I joined. I had no experience with Unity whatsoever; in my day job as an intern I touched on C#, which may have helped. I used ChatGPT for a lot of my first scripts. However, I was able to get a working prototype that looked like the phone-recorded image you see below: <!-- <p align="center"> <img src="" width="50%"> </p> --> Adding the projectile spitter (that's what I named it for a long time: `ProjectileSpitter`) was simple, and I got used to a lot of Unity's built-in functionalities like Colliders and RigidBodies. I found myself digging for a long time in scripts, while I in fact had to toggle a button on a Collider and what I wanted would work. Here's the second prototype, and a video of it on [YouTube](). <!-- <p align="center"> <img src="" width="50%"> </p> --> I added color effects to the game, and decided on how I should make the player obtain a Score. I decided on creating 'levels', where the only way you could advance to the next level is by coming in close contact with outcoming planets. The closer you are, the more you progress to the next level. This was it. Other than that, I added a logarithmic curve that increased the difficulty as the player progressed, and got sound effects made for my game. I added in some non-copyright music, spent a long time figuring out scenes, persisting music and a game over, pause and main menu. Here's a screen cap of some gameplay: <!-- <p align="center"> <img src="" width="50%"> </p> --> You can play the final product [itch.io](https://itch.io). Hope it's worth your time!
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Mirror.Examples.NetworkRoom { [AddComponentMenu("")] public class MyNetworkRoomManager : NetworkRoomManager { public static new MyNetworkRoomManager singleton { get; private set; } public bool showButton = false; /// <summary> /// Runs on both Server and Client /// Networking is NOT initialized when this fires /// </summary> public override void Awake() { base.Awake(); singleton = this; } /// <summary> /// This is called on the server when a networked scene finishes loading. /// </summary> /// <param name="sceneName">Name of the new scene.</param> public override void OnRoomServerSceneChanged(string sceneName) { // spawn the initial batch of Rewards } /// <summary> /// Called just after GamePlayer object is instantiated and just before it replaces RoomPlayer object. /// This is the ideal point to pass any data like player name, credentials, tokens, colors, etc. /// into the GamePlayer object as it is about to enter the Online scene. /// </summary> /// <param name="roomPlayer"></param> /// <param name="gamePlayer"></param> /// <returns>true unless some code in here decides it needs to abort the replacement</returns> public override bool OnRoomServerSceneLoadedForPlayer(NetworkConnectionToClient conn, GameObject roomPlayer, GameObject gamePlayer) { return true; } public override void OnRoomStopClient() { base.OnRoomStopClient(); } public override void OnRoomStopServer() { base.OnRoomStopServer(); } /* This code below is to demonstrate how to do a Start button that only appears for the Host player showStartButton is a local bool that's needed because OnRoomServerPlayersReady is only fired when all players are ready, but if a player cancels their ready state there's no callback to set it back to false Therefore, allPlayersReady is used in combination with showStartButton to show/hide the Start button correctly. Setting showStartButton false when the button is pressed hides it in the game scene since NetworkRoomManager is set as DontDestroyOnLoad = true. */ public bool showStartButton; public override void OnRoomServerPlayersReady() { // calling the base method calls ServerChangeScene as soon as all players are in Ready state. #if UNITY_SERVER base.OnRoomServerPlayersReady(); #else showStartButton = true; GameObject.Find("Canvas").GetComponent<RoomCanvasManager>().SetButtonStart(true); #endif } public override void ServerChangeScene(string newSceneName) { if (newSceneName == RoomScene) { foreach (NetworkRoomPlayer roomPlayer in roomSlots) { if (roomPlayer == null) continue; // find the game-player object for this connection, and destroy it NetworkIdentity identity = roomPlayer.GetComponent<NetworkIdentity>(); if (NetworkServer.active) { // re-add the room object roomPlayer.GetComponent<NetworkRoomPlayer>().readyToBegin = false; //roomPlayer.GetComponent<MyNetworkRoomPlayer>().playerName = test; NetworkServer.ReplacePlayerForConnection(identity.connectionToClient, roomPlayer.gameObject); } } allPlayersReady = false; } base.ServerChangeScene(newSceneName); } public override void OnGUI() { base.OnGUI(); if (allPlayersReady && showStartButton && GUI.Button(new Rect(150, 300, 120, 20), "START GAME")) { // set to false to hide it in the game scene showStartButton = false; ServerChangeScene(GameplayScene); } } } }
# PostgreSQL Proxy Utilities This package provides a number of different utilities for developing and testing with `PGProxy`. * [Test Databases](#test-databases) * [Database Migrations](#database-migrations) * [Persister Schema Generation](#persister-schema-generation) * [PGProxy](https://github.com/juitnow/juit-pgproxy/blob/main/README.md) * [Copyright Notice](https://github.com/juitnow/juit-pgproxy/blob/main/NOTICE.md) * [License](https://github.com/juitnow/juit-pgproxy/blob/main/NOTICE.md) ### Test Databases Few helpers are available to create and drop test databases while developing: * `testdb(...)`: return a test database _name_. An optional parameter can be used to specify the database name _prefix_ (defaults to `test`). * `createdb(name, url)`: actually _create_ a new database, and return its name. * `name`: the name of the database to create, defaults to the value returned by calling `testdb()`. * `url`: the URL to connect to for creating the database, defaults to `psql:///postgres` (the local PostgreSQL instance via `libpq`) * `dropdb(name, url)`: drop the specified database. * `name`: the name of the database to drop, _required_. * `url`: the URL to connect to for dropping the database, defaults to `psql:///postgres` (the local PostgreSQL instance via `libpq`) Normally, those methods are used when running tests, in a pattern similar to the following: ```ts let databaseName: string beforeAll(async () => { databaseName = await createdb() }) afterAll(async () => { await dropdb(databasename) }) it('should run a test', async () => { const client = new PGClient(databaseName) /// ... use the client to test }) ``` ### Database Migrations The `migrate(...)` function provides an extremely simplistic way to migrate databases. Migration files should have names like `001-initial.sql`, `002-second.sql`, basically stating the migration _order_ followed by a simple name describing it. All migrations will be recorded in the database using the `$migrations` table. The `migrate(...)` function requires two arguments: * `url`: the URL of the database to migrate, _required_. * `options`: an optional set of options including: * `migrations`: the _directory_ where migration files reside, relative to the current working directory, defaults to `./sql`. * `additional`: an additional set of migrations to be run (for example) migrations required to run unit tests, defaults to _undefined_. * `group`: a logical name grouping migrations together, when multiple sources of database migrations exist in the same database, defaults to `default`. In unit tests, for example, migrations can be applied in the following way: ```ts let databaseName: string beforeAll(async () => { databaseName = await createdb() await migrate(databaseName, { migrations: './migrations', additional: './test/migrations', }) }) // run your tests, all migrations will be applied beforehand ``` ### Persister Schema Genration Schema definitions for our `Persister` models (see `@juit/pgproxy-persister`) can be generated using a couple of functions: * `extractSchema(...)`: extract the `Schema` definition from a database. * `serializeSchema(...)`: serialize the extracted `Schema` as a Typescript DTS. The `extractSchema(...)` function takes a couple of arguments: * `url`: the URL of the database whose schemas are to be extracted, _required_. * `schemas`: an array of _database schema names_ to extract, defaulting to the single `['public']` schema. The `serializeSchema(...)` takes the following arguments: * `schema`: the `Schema` for which the DTS should be generated, _required_. * `id`: the exported identifier of the schema, optional, defaults to `Schema`. * `overrides`: A `Record` mapping OID numbers to TypeScript types, in case the registry used by the client is capable of handling them. All known OIDs from the `@juit/pgproxy-types` library are already covered. An extra couple of utilities are available for the schema extractor: * `types`: a collection of TypeScript types representing the common, well known types converted by `PGProxy` (e.g. _strings_, _numbers_, _arrays_, ...). * `helpers`: helper functions to generate extra types for `serializeSchema`: * `makePostgresArrayType(...)`: given a type `T`, it'll return a type representing a postgres array, that is `(T | null)[]`. * `makeImportType(module, name, args)`: generate a type imported from the specified module, using the specified type arguments, for example: `import('myModule').MyType<MyArg1, MyArg2>`
// Converting time to stopwatch function timeToString(time) { let diffInHrs = time / 3600000; let hh = Math.floor(diffInHrs); let diffInMin = (diffInHrs - hh) * 60; let mm = Math.floor(diffInMin); let diffInSec = (diffInMin - mm) * 60; let ss = Math.floor(diffInSec); let diffInMs = (diffInSec - ss) * 100; let ms = Math.floor(diffInMs); let formattedMM = mm.toString().padStart(2, "0"); let formattedSS = ss.toString().padStart(2, "0"); let formattedMS = ms.toString().padStart(2, "0"); return `${formattedMM}:${formattedSS}:${formattedMS}`; } // Variables let startTime; let elapsedTime = 0; let timerInterval; let running = false; // Func to modify innerHTML function print(txt) { document.getElementById("display").innerHTML = txt; } function toogleRunning() { running = !running; } // Action functions function start() { toogleRunning(); startTime = Date.now() - elapsedTime; timerInterval = setInterval(function printTime() { elapsedTime = Date.now() - startTime; print(timeToString(elapsedTime)); }, 10); showButton("PAUSE"); } function pause() { clearInterval(timerInterval); showButton("PLAY"); } function reset() { toogleRunning(); clearInterval(timerInterval); print("00:00:00"); elapsedTime = 0; showButton("PLAY"); } // Displaying buttons function showButton(buttonKey) { const buttonToShow = buttonKey === "PLAY" ? playButton : pauseButton; const buttonToHide = buttonKey === "PLAY" ? pauseButton : playButton; buttonToShow.style.display = "block"; buttonToHide.style.display = "none"; } // Event listeners let playButton = document.getElementById("playButton"); let pauseButton = document.getElementById("pauseButton"); let resetButton = document.getElementById("resetButton"); playButton.addEventListener("click", start); pauseButton.addEventListener("click", pause); resetButton.addEventListener("click", reset); // Keyboard action!!! document.addEventListener('keydown', function(event){ if(event.key === "Escape" && running === true){ reset(); console.log(event.key === "Escape"); } }); document.addEventListener('keydown', function(event){ if(event.key === " " && running !== true){ start(); console.log(event.key === " " ); } });
import React from "react"; import { renderCheckedOrUnCheckedStar, renderHalfOrFullStar } from "../utils"; type Props = { rating: number; handleRatingChange: (value: number) => void; }; export default function StarRatingInput({ rating, handleRatingChange }: Props) { return ( <div> {Array.from(Array(5)).map((_, index) => { return ( <button className="b--none bg-white pa0 pointer" onClick={() => handleRatingChange(index + 1)} key={index} > <i className={`w2 fas fa-lg ${renderHalfOrFullStar( index, rating )} ${renderCheckedOrUnCheckedStar(index, rating)}`} /> </button> ); })} </div> ); }
import { prismaMock } from '../../src/database/singleton' import TransactionService from '../../src/services/TransactionService' describe('TransactionService', () => { const creditedUser = { id: 2, username: 'ada', accountId: 2, account: { balance: 100 } } const debitedUser = { id: 1, username: 'john', accountId: 1, account: { balance: 100 } } const mockTransaction = [ { id: 1, debitedAccountId: 1, creditedAccountId: 2, value: 25, createdAt: '2022-11-19T15:23:34.348Z' }, { id: 1, balance: 75 }, { id: 2, balance: 125 } ] it('should be able to make a transaction', async () => { prismaMock.$transaction.mockResolvedValue(mockTransaction) const [transaction, debitedAccount, creditedAccount] = await TransactionService.makeTransaction(creditedUser, debitedUser, 25) expect(transaction).toHaveProperty('id') expect(transaction.value).toBe(25) expect(debitedAccount.id).toBe(1) expect(creditedAccount.id).toBe(2) }) it('should not make a transaction that exceeds the user balance', async () => { prismaMock.user.findUnique.mockResolvedValue(null) await expect( TransactionService.makeTransaction(creditedUser, debitedUser, 200) ).rejects.toThrow() }) })
// @ts-ignore import React, { useCallback, useEffect } from "react"; // Хук выполняющий onEnter(), когда нажали на Enter const useOnEnter = (onEnter: () => void) => { const _onEnter = useCallback(e => { if (e.key === "Enter" || e.which === 13 || e.keyCode === 13) { onEnter(); } }, [onEnter]); useEffect(() => { window.addEventListener("keypress", _onEnter); return () => { window.removeEventListener("keypress", _onEnter); }; }, []); return null; }; export default useOnEnter;
<header class="sticky-top"> <nav class="navbar navbar-light bg-light"> <a routerLink="/products" class="navbar-brand"> <img src="/assets/images/nav/logo.png" width="30" height="30" class="d-inline-block align-top" alt="logo" /> MyShop </a> <div class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" #Input placeholder="Search" aria-label="Search" (keyup.enter)="onSubmit(Input.value)" /> <button class="btn btn-outline-primary my-2 my-sm-0" (click)="onSubmit(Input.value)" > Search </button> </div> <div class="d-flex align-items-center"> <div *ngIf="isAuth || username" class="mr-2"> <p> Welcome:<strong>{{ username }}</strong> </p> </div> <button type="button" class="btn btn-sm btn-outline-primary mr-2" (click)="onLogin()" *ngIf="!isAuth" > Login </button> <button type="button" class="btn btn-sm btn-outline-danger mr-2" (click)="onLogout()" *ngIf="isAuth" > Logout </button> <div class="border border-info rounded-circle" *ngIf="isAuth"> <div class="p-2">{{ totalPrice | currency : "INR" }}</div> </div> <button type="button" class="btn btn-sm ml-1" (click)="onCartDetails()" *ngIf="isAuth" > <img src="/assets/images/nav/local_grocery_store.svg" width="30" height="30" class="d-inline-block" alt="cart" /> <span class="badge badge-info align-top">{{ totalQuantity }}</span> </button> </div> </nav> </header>
<?php namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use App\Mail\WelcomeEmail; use App\Models\Currency; use App\Models\DictationTopic; use App\Models\LanguageVariant; use App\Models\ListeningTopic; use App\Models\Payment; use App\Models\SpellingTopic; use App\Models\NumberTopic; use Carbon\Carbon; use GuzzleHttp\Client; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use App\Mail\TestEmail; use Illuminate\Mail\Markdown; use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\View; use Mailgun\Mailgun; use App\Http\Repositories\MainInfoRepository; use Tymon\JWTAuth\Facades\JWTAuth; class MainInfoController extends Controller { public function getLanguageVariant(): JsonResponse { $languageVariants = LanguageVariant:: where('enabled', 1) ->orderBy('sort_order') ->get(); return response()->json($languageVariants); } public function getTopics(): JsonResponse { $dictationTopics = DictationTopic:: where('enabled', 1) ->where('learning_language_id',1) ->orderBy('sort_order') ->get(); $listeningTopics = ListeningTopic:: where('enabled', 1) ->where('learning_language_id',1) ->orderBy('sort_order') ->get(); $spellingTopics = SpellingTopic:: where('enabled', 1) ->where('learning_language_id',1) ->orderBy('sort_order') ->get(); $numberTopics = NumberTopic:: where('enabled', 1) ->where('learning_language_id',1) ->orderBy('sort_order') ->get(); return response()->json([ 'dictation' => $dictationTopics, 'listening' => $listeningTopics, 'spelling' => $spellingTopics, 'number' => $numberTopics, ]); } public function getCurrencies(): JsonResponse { $currencies = Currency::all(); $defaultCurrencyId = null; foreach ($currencies as $currency){ $currency->description = $currency->code . ' - ' . $currency->name; if($currency->code === env('CURRENCY_DEFAULT','USD')){ $defaultCurrencyId = (int) $currency->id; } } return response()->json([ 'currencies' => $currencies, 'defaultCurrencyId' => $defaultCurrencyId ]); } public function getCurrencyInfoById(Request $request) { $validated = $request->validate([ 'currencyId' => 'required|integer|exists:currencies,id' ]); $currencyId = $validated['currencyId']; $currency = Currency::find($currencyId); return response()->json($currency); } public function getUserCurrency(Request $request) { $mainInfoRepository = new MainInfoRepository(); $clientIpAddress = $mainInfoRepository->getUserIp(); $currencyUser = $mainInfoRepository->getCurrencyByIP($clientIpAddress); return response()->json(['currency' => $currencyUser]); } public function getUserOverview() { $user = JWTAuth::parseToken()->authenticate(); $listeningAverageScore = $user->listening()->avg('score'); $dictationAverageScore = $user->dictations()->avg('score'); $spellingAverageScore = $user->spelling()->avg('score'); $numberAverageScore = $user->number()->avg('score'); $listeningQtyLessonsCompleted = $user->listening()->count(); $dictationQtyLessonsCompleted = $user->dictations()->count(); $spellingQtyLessonsCompleted = $user->spelling()->count(); $numberQtyLessonsCompleted = $user->number()->count(); if($listeningAverageScore) $listeningAverageScore = (float) round($listeningAverageScore,1); if($dictationAverageScore) $dictationAverageScore = (float) round($dictationAverageScore,1); if($spellingAverageScore) $spellingAverageScore = (float) round($spellingAverageScore,1); if($numberAverageScore) $numberAverageScore = (float) round($numberAverageScore,1); $data = []; $data[] = (object) [ 'name' => 'Listening', 'score' => $listeningAverageScore, 'lessonsCompleted' => $listeningQtyLessonsCompleted ]; $data[] = (object) [ 'name' => 'Dictation', 'score' => $dictationAverageScore, 'lessonsCompleted' => $dictationQtyLessonsCompleted ]; $data[] = (object) [ 'name' => 'Spelling', 'score' => $spellingAverageScore, 'lessonsCompleted' => $spellingQtyLessonsCompleted ]; $data[] = (object) [ 'name' => 'Numbers', 'score' => $numberAverageScore, 'lessonsCompleted' => $numberQtyLessonsCompleted ]; return response()->json($data); } public function getUserMembershipStatus() { $user = JWTAuth::parseToken()->authenticate(); $userId = $user ? $user->id : null; $mainInfoRepository = new MainInfoRepository(); $isPremium = $mainInfoRepository->isPremium(); $membershipStatus = "Basic (free)"; if ($isPremium) { $paymentInfo = Payment::where('user_id', $userId) ->orderBy('id', 'desc') ->first(['payment_date', 'subscription_end_date']); if($paymentInfo->payment_date && $paymentInfo->subscription_end_date){ $paymentDate = Carbon::createFromFormat('Y-m-d H:i:s',$paymentInfo->payment_date)->format('Y.m.d'); $subscriptionEndDate = Carbon::createFromFormat('Y-m-d H:i:s',$paymentInfo->subscription_end_date)->format('Y.m.d'); $membershipStatus = "Premium ($paymentDate - $subscriptionEndDate)"; }else{ $membershipStatus = "Lifelong access to Premium features"; } } return response()->json($membershipStatus); } }
package com.app.catcare.ayaz.activities; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.text.method.HideReturnsTransformationMethod; import android.text.method.PasswordTransformationMethod; import android.util.Patterns; import android.widget.Toast; import com.app.catcare.ayaz.R; import com.app.catcare.ayaz.databinding.ActivitySignInBinding; import com.app.catcare.ayaz.utils.Constants; import com.app.catcare.ayaz.utils.PreferenceManager; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import java.util.Objects; public class SignInActivity extends AppCompatActivity { private ActivitySignInBinding binding; private PreferenceManager preferenceManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding=ActivitySignInBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); preferenceManager=new PreferenceManager(getApplicationContext()); binding.btnSignIn.setOnClickListener(view -> { if (isValidSignInDetails()) { SigIn(); } }); binding.SignUpForNew.setOnClickListener(view -> { Intent intent = new Intent(SignInActivity.this, SignUpActivity.class); SignInActivity.this.startActivity(intent); }); binding.ForgotPassword.setOnClickListener(view -> { Intent intent = new Intent(SignInActivity.this, RecoverPasswordActivity.class); SignInActivity.this.startActivity(intent); }); binding.checkboxPassword.setOnClickListener(v -> { if (binding.checkboxPassword.isChecked()) { binding.enterPasswordEt.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); binding.checkboxPassword.setText(getString(R.string.hide_password)); } else { binding.enterPasswordEt.setTransformationMethod(PasswordTransformationMethod.getInstance()); binding.checkboxPassword.setText(getString(R.string.show_password)); } }); } private void SigIn() { FirebaseFirestore database=FirebaseFirestore.getInstance(); database.collection(Constants.KEY_COLLECTION_USERS) .whereEqualTo(Constants.KEY_EMAIL,binding.getEmailEt.getText().toString()) .whereEqualTo(Constants.KEY_PASSWORD,binding.enterPasswordEt.getText().toString()) .get() .addOnCompleteListener(task->{ if (task.isSuccessful()&&task.getResult()!=null &&task.getResult().getDocuments().size()>0) { DocumentSnapshot documentSnapshot=task.getResult().getDocuments().get(0); preferenceManager.putBoolean(Constants.KEY_IS_SIGNED_IN,true); preferenceManager.putString(Constants.KEY_USER_ID,documentSnapshot.getId()); preferenceManager.putString(Constants.KEY_NAME, documentSnapshot.getString(Constants.KEY_NAME)); preferenceManager.putString(Constants.KEY_DOB,documentSnapshot.getString(Constants.KEY_DOB)); preferenceManager.putString(Constants.KEY_TOTAL_AGE,documentSnapshot.getString(Constants.KEY_TOTAL_AGE)); preferenceManager.putString(Constants.KEY_IMAGE,documentSnapshot.getString(Constants.KEY_IMAGE)); Intent intent=new Intent(getApplicationContext(),MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } else { showToast("Unable to Sign In"); } }); } private Boolean isValidSignInDetails() { if (Objects.requireNonNull(binding.enterPasswordEt.getText()).toString().trim().isEmpty()) { showToast("Enter Email"); return false; } else if (!(Patterns.EMAIL_ADDRESS.matcher(binding.getEmailEt.getText().toString()).matches())) { showToast("Enter Valid Email"); return false; } else if (binding.enterPasswordEt.getText().toString().trim().isEmpty()) { showToast("Enter Password"); return false; } else if (binding.enterPasswordEt.getText().toString().length() < 6) { showToast("Password length is shorter than 6 characters!"); return false; } else { return true; } } private void showToast(String message) { Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show(); } }
package baekjoon; import java.io.*; import java.util.ArrayList; import java.util.List; public class B6996 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); List<String> output = new ArrayList<>(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int input = Integer.parseInt(br.readLine()); for (int i = 0; i < input; i++){ String[] s = br.readLine().split(" "); if(s[0].length() != s[1].length()){ output.add(String.format("%s & %s are NOT anagrams.", s[0], s[1])); continue; } String x = s[0].chars() // IntStream .sorted() .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); String y = s[1].chars() // IntStream .sorted() .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); if (x.equals(y)){ output.add(String.format("%s & %s are anagrams.", s[0], s[1])); }else{ output.add(String.format("%s & %s are NOT anagrams.", s[0], s[1])); } } for (String s : output){ bw.write(s); bw.newLine(); } bw.flush(); bw.close(); } }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Instruction; use App\Models\Workplace; use Illuminate\Support\Facades\Log; class InstructionsController extends Controller { /** * 指示内容の追加フォームを表示 */ public function create($workplace_id) { $workplace = Workplace::findOrFail($workplace_id); return view('instructions.create', compact('workplace')); } /** * 指示内容を保存 */ public function store(Request $request, $workplace_id) { // バリデーション $validated = $request->validate([ 'instructions.*.construction_location' => 'required|string|max:255', 'instructions.*.construction_location_detail' => 'nullable|string|max:255', 'instructions.*.product_name' => 'required|string|max:255', 'instructions.*.product_number' => 'nullable|string|max:255', 'instructions.*.amount' => 'nullable|integer', 'instructions.*.unit_id' => 'required|exists:units,id', ]); // 各指示内容を保存 foreach ($validated['instructions'] as $instructionData) { Instruction::create([ 'workplace_id' => $workplace_id, 'construction_location' => $instructionData['construction_location'], 'construction_location_detail' => $instructionData['construction_location_detail'], 'product_name' => $instructionData['product_name'], 'product_number' => $instructionData['product_number'], 'amount' => $instructionData['amount'], 'unit_id' => $instructionData['unit_id'], 'show_flg' => 1 ]); } Log::info('指示内容が登録されました。', ['workplace_id' => $workplace_id]); return redirect()->route('workplaces.index')->with('success', '指示内容が登録されました。'); } }
import { Role } from "@prisma/client"; import { Transform } from "class-transformer"; import { IsBoolean, IsEnum, IsNotEmpty, IsOptional, IsString, Length } from "class-validator" import { RequestDTO } from "./index" export class Register extends RequestDTO{ constructor() { super(); } @IsNotEmpty() @IsString() email: string @IsNotEmpty() @IsString() @Length(8) password: string @IsNotEmpty() @IsString() name: string @Transform(param => param.value?.toUpperCase() || Role.USER) @IsEnum(Role) role: Role = Role.USER; }
import 'dart:async'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../../Utils/dimensions.dart'; import '../../controllers/popular_product_controller.dart'; import '../../controllers/recommended_product_controller.dart'; import '../../routes/route_helper.dart'; class SplashScreen extends StatefulWidget { const SplashScreen({Key? key}) : super(key: key); @override State<SplashScreen> createState() => _SplashScreenState(); } class _SplashScreenState extends State<SplashScreen> with TickerProviderStateMixin{ late Animation<double> animation; late AnimationController controller; Future<void> _loadResources() async { await Get.find<PopularProductController>().getPopularProductList(); await Get.find<RecommendedProductController>().getRecommendedProductList(); } @override void initState() { super.initState(); _loadResources(); controller = AnimationController(vsync: this, duration: const Duration(seconds: 2))..forward(); animation = CurvedAnimation(parent: controller, curve: Curves.linear); Timer( const Duration(seconds: 3), () => Get.offNamed(RouteHelper.getInitial()) ); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, body: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ ScaleTransition( scale: animation, child: Center( child: Image.asset("assets/images/logo part 1.png", width: Dimensions.splashImg,) ), ), Center( child: Image.asset("assets/images/logo part 2.png", width: Dimensions.splashImg,) ) ], ), ); } }
package com.example.qrscan.data.repository import androidx.annotation.WorkerThread import com.example.qrscan.data.dao.MultipleScanDao import com.example.qrscan.data.model.MultipleScanModel import kotlinx.coroutines.flow.Flow class MultipleScanRepository(private val multipleScanDao: MultipleScanDao) { val listMultipleScan: Flow<List<MultipleScanModel>> = multipleScanDao.getAllResult() @WorkerThread suspend fun insertItem(multipleScanModel: MultipleScanModel) { multipleScanDao.insertMultipleScan(multipleScanModel) } @WorkerThread suspend fun deleteItem(isDelete: Boolean) { multipleScanDao.delete(isDelete) } @WorkerThread suspend fun updateIsDeleteItem(isDelete: Boolean) { multipleScanDao.updateIsDeleteItem(isDelete) } @WorkerThread suspend fun updateCheckItem(id:Int,isCheck: Boolean) { multipleScanDao.updateCheckItem(id,isCheck) } @WorkerThread suspend fun updateIsCheckItem(isCheck: Boolean) { multipleScanDao.updateIsCheckItem(isCheck) } @WorkerThread suspend fun deleteAllItem() { multipleScanDao.deleteAll() } }
import { GRAPHQL_API_URL } from './shared' import { SETTINGS_QUERY, HEADER_QUERY, FOOTER_QUERY } from '../_graphql/globals' export async function fetchSettings(): Promise<Settings> { if (!GRAPHQL_API_URL) throw new Error('NEXT_PUBLIC_SERVER_URL not found') const response = await fetch(`${GRAPHQL_API_URL}/api/graphql`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, cache: 'no-store', body: JSON.stringify({ query: SETTINGS_QUERY, }), }) if (!response.ok) { throw new Error('Error fetching doc') } const result = await response.json() if (result.errors) { throw new Error(result.errors[0]?.message || 'Error fetching settings') } return result.data?.Settings } // Similar changes for fetchHeader and fetchFooter export async function fetchHeader(): Promise<Header> { if (!GRAPHQL_API_URL) throw new Error('NEXT_PUBLIC_SERVER_URL not found') const response = await fetch(`${GRAPHQL_API_URL}/api/graphql`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, cache: 'no-store', body: JSON.stringify({ query: HEADER_QUERY, }), }) if (!response.ok) { throw new Error('Error fetching doc') } const result = await response.json() if (result.errors) { throw new Error(result.errors[0]?.message || 'Error fetching header') } return result.data?.Header } export async function fetchFooter(): Promise<Footer> { if (!GRAPHQL_API_URL) throw new Error('NEXT_PUBLIC_SERVER_URL not found') const response = await fetch(`${GRAPHQL_API_URL}/api/graphql`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query: FOOTER_QUERY, }), }) if (!response.ok) { throw new Error('Error fetching doc') } const result = await response.json() if (result.errors) { throw new Error(result.errors[0]?.message || 'Error fetching footer') } return result.data?.Footer }
import { MigrationInterface, QueryRunner } from 'typeorm'; export class CreateInitialTables1685896868634 implements MigrationInterface { name = 'CreateInitialTables1685896868634'; public async up(queryRunner: QueryRunner): Promise<void> { await queryRunner.query( `CREATE TABLE "countries" ("id" character varying NOT NULL, "name" character varying NOT NULL, "iso" character varying NOT NULL, "languages" json NOT NULL DEFAULT '{"languages":[]}', CONSTRAINT "PK_b2d7006793e8697ab3ae2deff18" PRIMARY KEY ("id"))` ); await queryRunner.query( `CREATE TABLE "expressions" ("id" character varying NOT NULL, "languageId" character varying NOT NULL, "countryId" character varying NOT NULL, "terms" json NOT NULL DEFAULT '{"terms":[]}', "userId" character varying NOT NULL, CONSTRAINT "PK_e75aa87c24b37cd86f6c8a668c9" PRIMARY KEY ("id"))` ); await queryRunner.query( `CREATE TABLE "users" ("id" character varying NOT NULL, "name" character varying NOT NULL, "provider" character varying NOT NULL, "email" character varying NOT NULL, "photo" character varying NOT NULL, CONSTRAINT "PK_a3ffb1c0c8416b9fc6f907b7433" PRIMARY KEY ("id"))` ); await queryRunner.query( `CREATE TABLE "words" ("id" character varying NOT NULL, "languageId" character varying NOT NULL, "countryId" character varying NOT NULL, "terms" json NOT NULL DEFAULT '{"terms":[]}', "userId" character varying NOT NULL, CONSTRAINT "PK_feaf97accb69a7f355fa6f58a3d" PRIMARY KEY ("id"))` ); } public async down(queryRunner: QueryRunner): Promise<void> { await queryRunner.query(`DROP TABLE "words"`); await queryRunner.query(`DROP TABLE "users"`); await queryRunner.query(`DROP TABLE "expressions"`); await queryRunner.query(`DROP TABLE "countries"`); } }
import React from 'react' import Label from '../label'; import ErrorLabel from '../error-label'; import { ISelectCountry } from './select-country-types'; import "./select-country.css" import { Select } from 'antd'; import { countries } from 'src/lib/country'; const { Option } = Select; const SelectCountryComponent = ({ id, name, label, value = "", required = false, errorMessage = "", showError, onSelect, containerClassName = "" }: ISelectCountry) => { const countriesList = Object.keys(countries).map((country_code) => ({ country_code, name: countries[country_code].name, image: countries[country_code].image, })) const filterOption = (input: string, option?: { label: string; value: string }) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase()); return <> <div className={`${containerClassName} ${showError && errorMessage ? "select-country-error" : ""}`}> {label && <Label id={id || name} name={label} required={required} className="" />} <Select showSearch style={{ width: '100%' }} value={value} filterOption={filterOption} className='select-country' onSelect={(e) => onSelect(e)} > {countriesList.map((value, i) => { return ( <Option value={value?.country_code} key={i} label={value?.name}> <div className='flex flex-row'><img height={25} width={25} src={value?.image} /> <span>{value.name}</span> </div> </Option> ) })} </Select> {showError && <ErrorLabel message={errorMessage} />} </div> </> } export default SelectCountryComponent
{% extends 'shop/base.html' %} {% load staticfiles %} {% block metadescription %} {% if category %} {{ category.description|truncatewords:155 }} {% else %} Welcome to the cushion store where you can buy comfy and awesome cushions. {% endif %} {% endblock %} {% block title %} {% if category %} {{ category.name }} - Perfect Cushion Store {% else %} See Our Cushion collection - Perfect Cushion Store {% endif %} {% endblock %} {% block content %} {% if category %} <div class="row my_row_class"> <div class="mx-auto"> <p><a href="{% url 'shop:allProdCat' %}">Our Product Collection</a> | {{ category.name }}</p> </div> </div> {% endif %} <div class="mx-auto"> {% if category %} <img class="my_image" src="{{ category.image.url }}" alt="{{ category.name }}"> </div> <br> <div> <h1 class="text-center my_title">{{ category.name }}</h1> <p class="text-justify">{{ category.description }}</p> </div> {% else %} <img class="my_image my_image_padding" src="{% static 'img/banner.jpg' %}" alt="Our Products Collection"> </div> <br> <div> <h1 class="text-center my_title">Our Products Collection</h1> <p class="text-justify">Finding perfect cushion for your room can instantly add to the levels of comfort and sense of style throughout your home. They can transform the blandest of decors instantly by adding colour, softness and an air of cosiness.</p> </div> {% endif %} <div class="container"> <div class="row mx-auto"> {% for product in products.object_list %} <div class="my_bottom_margin col-9 col-sm-12 col-md-4 col-md-12 col-lg-4"> <div class="card text-center" style="width: 18rem;"> <a href="{{ product.get_url }}"> <img class="card-img-top my_image" src="{{ product.image.url }}" alt="{{product.name}}"> <div class="card-body"> <h4>{{ product.name }}</h4> <p>${{ product.price }}</p> </div> </a> </div> </div> {% endfor %} </div> <div class="mx-auto"> {% if products.paginator.num_pages > 1 %} <hr> <div class="text-center"> {% for pg in products.paginator.page_range %} <a href="?page={{pg}}" class="btn btn-light btn-sm {% if products.number == pg%}active{%endif%}">{{pg}}</a> {% endfor %} </div> {% endif %} </div> <br> </div> {% endblock %}
import { Container, interfaces } from "inversify"; import React, { useContext, useMemo } from "react"; const InversifyContext = React.createContext<{ container: Container | null}>({container: null}); type Props = { container: Container, children?: JSX.Element } export const IoCProvider: React.FunctionComponent<Props> = (props: Props) => { return ( <InversifyContext.Provider value={{container: props.container}}> {props?.children } </InversifyContext.Provider> ); }; export function useInjection<T>(identifier: interfaces.ServiceIdentifier<T>): T { const { container } = useContext(InversifyContext); if (!container) { throw new Error(); } return useMemo(() => container.get<T>(identifier), [container, identifier]); };
#pragma once #include <SDL.h> // #include <SDL_ttf.h> #include "/usr/local/Cellar/sdl2_ttf/2.22.0/include/SDL2/SDL_ttf.h" #include <string> #include <map> #include <iostream> #include <filesystem> #include <cstdlib> // for getenv() #include <fstream> #include "Font_TTCParsing.h" enum class FontStyle { BLACK, BLACK_ITALIC, BOLD, BOLD_ITALIC, ITALIC, LIGHT, LIGHT_ITALIC, MEDIUM, MEDIUM_ITALIC, REGULAR, THIN, THIN_ITALIC }; class FontManager { public: // Delete copy constructor FontManager(const FontManager&) = delete; TTF_Font* getFont(const std::string& fontName, int size, FontStyle style = FontStyle::REGULAR); static FontManager& getInstance(); ~FontManager(); private: std::vector<std::string> fontPaths; std::map<std::tuple<std::string, FontStyle, int>, TTF_Font*> fontCache; FontManager(); TTF_Font* loadFont(const std::string& fontPath, int size, int index = 0); std::string getStyleString(FontStyle style); };
import axios from 'axios' import React, { useState, useContext, useEffect } from 'react' import './CreateTask.css' import { SelectUser } from './Select/SelectUser/SelectUser' import { SelectProject } from './Select/SelectProject/SelectProject' import { SelectTaskType } from './Select/SelectTaskType/SelectTaskType' import { AuthContext } from '../../../../context' export const CreateTask = ({ visible, setVisible, ...props }) => { const { token } = useContext(AuthContext) const [newTask, setNewTask] = useState({}) const [user, setUser] = useState() const [project, setProject] = useState() const [taskType, setTaskType] = useState() const cl = ['createTaskModal'] if (visible) { cl.push('createTaskActive') } function createTask() { axios({ method: 'post', url: 'http://localhost:88/api/task/', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token }, data: { ...newTask, user: user, project: project, taskType: taskType } }).then(() => setVisible(false)) } useEffect(() => {props.getTasks()}, [visible]) return ( <div className={cl.join(' ')} onClick={() => setVisible(false)}> <div className="createTaskContent" onClick={(e) => e.stopPropagation()}> <input type="text" placeholder="Имя задачи" defaultValue='' onChange={(e) => setNewTask({ ...newTask, name: e.target.value })} /> <input type="text" placeholder="Описание задачи" defaultValue='' onChange={(e) => setNewTask({ ...newTask, description: e.target.value })} /> <input type="date" placeholder="Дата начала выполнения" defaultValue='' onChange={(e) => setNewTask({ ...newTask, startDate: e.target.value })} /> <input type="date" placeholder="Дата завершения выполнения" defaultValue='' onChange={(e) => setNewTask({ ...newTask, finishDate: e.target.value })} /> <SelectUser state={user} setState={setUser} /> <SelectProject state={project} setState={setProject} /> <SelectTaskType state={taskType} setState={setTaskType} /> <button type="button" onClick={() => createTask()}>Создать</button> </div> </div> ) }
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.mideaac.internal.handler; import static org.openhab.binding.mideaac.internal.MideaACBindingConstants.*; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.Map; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import javax.measure.Unit; import javax.measure.quantity.Temperature; import javax.measure.spi.SystemOfUnits; import org.apache.commons.lang3.StringUtils; import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jetty.client.HttpClient; import org.openhab.binding.mideaac.internal.MideaACConfiguration; import org.openhab.binding.mideaac.internal.Utils; import org.openhab.binding.mideaac.internal.discovery.DiscoveryHandler; import org.openhab.binding.mideaac.internal.discovery.MideaACDiscoveryService; import org.openhab.binding.mideaac.internal.handler.CommandBase.FanSpeed; import org.openhab.binding.mideaac.internal.handler.CommandBase.OperationalMode; import org.openhab.binding.mideaac.internal.handler.CommandBase.SwingMode; import org.openhab.binding.mideaac.internal.security.Cloud; import org.openhab.binding.mideaac.internal.security.CloudProvider; import org.openhab.binding.mideaac.internal.security.Clouds; import org.openhab.binding.mideaac.internal.security.Decryption8370Result; import org.openhab.binding.mideaac.internal.security.Security; import org.openhab.binding.mideaac.internal.security.Security.MsgType; import org.openhab.binding.mideaac.internal.security.TokenKey; import org.openhab.core.config.core.Configuration; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.i18n.UnitProvider; import org.openhab.core.library.types.DecimalType; import org.openhab.core.library.types.OnOffType; import org.openhab.core.library.types.QuantityType; import org.openhab.core.library.types.StringType; import org.openhab.core.library.unit.ImperialUnits; import org.openhab.core.library.unit.SIUnits; import org.openhab.core.thing.Channel; import org.openhab.core.thing.ChannelUID; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingStatusDetail; import org.openhab.core.thing.binding.BaseThingHandler; import org.openhab.core.types.Command; import org.openhab.core.types.RefreshType; import org.openhab.core.types.State; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The {@link MideaACHandler} is responsible for handling commands, which are * sent to one of the channels. * * @author Jacek Dobrowolski */ // @NonNullByDefault public class MideaACHandler extends BaseThingHandler implements DiscoveryHandler { private final Logger logger = LoggerFactory.getLogger(MideaACHandler.class); private MideaACConfiguration configuration; // private MideaACConfiguration configuration; public MideaACConfiguration getConfiguration() { return configuration; } public void setConfiguration(MideaACConfiguration configuration) { this.configuration = configuration; } private Map<String, String> properties = null; public Map<String, String> getProperties() { return properties; } public void setProperties(Map<String, String> properties) { this.properties = properties; } private String ipAddress = null; public String getIpAddress() { return ipAddress; } public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } public String getIpPort() { return ipPort; } public void setIpPort(String ipPort) { this.ipPort = ipPort; } public String getDeviceId() { return deviceId; } public void setDeviceId(String deviceId) { this.deviceId = deviceId; } private String ipPort = null; private String deviceId = null; private int version = 0; private final DataSmoother dataHistory = new DataSmoother(); private @Nullable CloudProvider cloudProvider = null; private @Nullable Security security; public @Nullable CloudProvider getCloudProvider() { return cloudProvider; } public @Nullable Security getSecurity() { return security; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } private static final StringType OPERATIONAL_MODE_OFF = new StringType("OFF"); private static final StringType OPERATIONAL_MODE_AUTO = new StringType("AUTO"); private static final StringType OPERATIONAL_MODE_COOL = new StringType("COOL"); private static final StringType OPERATIONAL_MODE_DRY = new StringType("DRY"); private static final StringType OPERATIONAL_MODE_HEAT = new StringType("HEAT"); private static final StringType OPERATIONAL_MODE_FAN_ONLY = new StringType("FAN_ONLY"); private static final StringType FAN_SPEED_OFF = new StringType("OFF"); private static final StringType FAN_SPEED_SILENT = new StringType("SILENT"); private static final StringType FAN_SPEED_LOW = new StringType("LOW"); private static final StringType FAN_SPEED_MEDIUM = new StringType("MEDIUM"); private static final StringType FAN_SPEED_HIGH = new StringType("HIGH"); private static final StringType FAN_SPEED_AUTO = new StringType("AUTO"); private static final StringType SWING_MODE_OFF = new StringType("OFF"); private static final StringType SWING_MODE_VERTICAL = new StringType("VERTICAL"); private static final StringType SWING_MODE_HORIZONTAL = new StringType("HORIZONTAL"); private static final StringType SWING_MODE_BOTH = new StringType("BOTH"); private final Clouds clouds; private final ConnectionManager connectionManager; private final SystemOfUnits systemOfUnits; private final HttpClient httpClient; private ConnectionManager getConnectionManager() { return connectionManager; } private @Nullable Response getLastResponse() { return getConnectionManager().getLastResponse(); } public MideaACHandler(Thing thing, String ipv4Address, UnitProvider unitProvider, HttpClient httpClient, Clouds clouds) { super(thing); this.thing = thing; this.systemOfUnits = unitProvider.getMeasurementSystem(); this.httpClient = httpClient; this.clouds = clouds; dataHistory.setManaged(CHANNEL_OUTDOOR_TEMPERATURE); dataHistory.setManaged(CHANNEL_INDOOR_TEMPERATURE); connectionManager = new ConnectionManager(ipv4Address, this); } public Clouds getClouds() { return clouds; } protected boolean isImperial() { return systemOfUnits instanceof ImperialUnits; } @Override public void dispose() { super.dispose(); getConnectionManager().dispose(); } @Override public void handleCommand(ChannelUID channelUID, Command command) { logger.debug("Handling channelUID {} with command {}", channelUID.getId(), command.toString()); if (command instanceof RefreshType) { connectionManager.requestStatus(true); return; } if (getLastResponse() == null) { markOfflineWithMessage(ThingStatusDetail.COMMUNICATION_ERROR, "Device not responding with its status. Last response was null"); return; } switch (channelUID.getId()) { case CHANNEL_POWER -> handlePower(command); case CHANNEL_OPERATIONAL_MODE -> handleOperationalMode(command); case CHANNEL_TARGET_TEMPERATURE -> handleTargetTemperature(command); case CHANNEL_FAN_SPEED -> handleFanSpeed(command); case CHANNEL_ECO_MODE -> handleEcoMode(command); case CHANNEL_TURBO_MODE -> handleTurboMode(command); case CHANNEL_SWING_MODE -> handleSwingMode(command); case CHANNEL_SCREEN_DISPLAY -> handleScreenDisplay(command); case CHANNEL_TEMP_UNIT -> handleTempUnit(command); default -> logger.debug("Unexpected channelUID '{}' has received with command '{}'", channelUID.getId(), command.toString()); } } public void handlePower(Command command) { CommandSet commandSet = CommandSet.fromResponse(getLastResponse()); if (command.equals(OnOffType.OFF)) { commandSet.setPowerState(false); } else if (command.equals(OnOffType.ON)) { commandSet.setPowerState(true); } else { logger.debug("Unknown power state command: {}", command); return; } getConnectionManager().sendCommandAndMonitor(commandSet); } public void handleOperationalMode(Command command) { CommandSet commandSet = CommandSet.fromResponse(getLastResponse()); commandSet.setPowerState(true); if (command instanceof StringType) { if (command.equals(OPERATIONAL_MODE_OFF)) { commandSet.setPowerState(false); return; } else if (command.equals(OPERATIONAL_MODE_AUTO)) { commandSet.setOperationalMode(OperationalMode.AUTO); } else if (command.equals(OPERATIONAL_MODE_COOL)) { commandSet.setOperationalMode(OperationalMode.COOL); } else if (command.equals(OPERATIONAL_MODE_DRY)) { commandSet.setOperationalMode(OperationalMode.DRY); } else if (command.equals(OPERATIONAL_MODE_HEAT)) { commandSet.setOperationalMode(OperationalMode.HEAT); } else if (command.equals(OPERATIONAL_MODE_FAN_ONLY)) { commandSet.setOperationalMode(OperationalMode.FAN_ONLY); } else { logger.debug("Unknown operational mode command: {}", command); return; } } getConnectionManager().sendCommandAndMonitor(commandSet); } private static float convertTargetCelsiusTemperatureToInRange(float temperature) { if (temperature < 17.0f) { return 17.0f; } if (temperature > 30.0f) { return 30.0f; } return temperature; } private static float convertTargetFahrenheitTemperatureToInRange(float temperature) { if (temperature < 62.0f) { return 62.0f; } if (temperature > 86.0f) { return 86.0f; } return temperature; } public void handleTargetTemperature(Command command) { if (command == null) { logger.debug("handleTargetTemperature command was null"); return; } Response lastResponse = getLastResponse(); if (lastResponse == null) { logger.debug("handleTargetTemperature lastResponse was null"); return; } CommandSet commandSet = CommandSet.fromResponse(lastResponse); if (command instanceof DecimalType) { QuantityType<Temperature> quantity = new QuantityType<>(((DecimalType) command).doubleValue(), lastResponse.getTempUnit() == true ? ImperialUnits.FAHRENHEIT : SIUnits.CELSIUS); commandSet.setPowerState(true); if (lastResponse.getTempUnit() == true) { // F if (isImperial()) { logger.debug("handleTargetTemperature: Set field of type Integer F > F"); commandSet.setTargetTemperature(convertTargetFahrenheitTemperatureToInRange(quantity.floatValue())); } else { logger.debug("handleTargetTemperature: Set field of type Integer C > F"); commandSet.setTargetTemperature(convertTargetCelsiusTemperatureToInRange( quantity.toUnit(ImperialUnits.FAHRENHEIT).floatValue())); } } else { if (isImperial()) { logger.debug("handleTargetTemperature: Set field of type Integer F > C"); commandSet.setTargetTemperature( convertTargetFahrenheitTemperatureToInRange(quantity.toUnit(SIUnits.CELSIUS).floatValue())); } else { logger.debug("handleTargetTemperature: Set field of type Integer C > C"); commandSet.setTargetTemperature(convertTargetCelsiusTemperatureToInRange(quantity.floatValue())); } } getConnectionManager().sendCommandAndMonitor(commandSet); } else if (command instanceof QuantityType) { commandSet.setPowerState(true); QuantityType<?> quantity = (QuantityType<?>) command; Unit<?> unit = quantity.getUnit(); logger.debug( "handleTargetTemperature: Set field of type Integer to value of item QuantityType with unit {}", unit); if (unit.equals(ImperialUnits.FAHRENHEIT) || unit.equals(SIUnits.CELSIUS)) { if (lastResponse.getTempUnit() == true && unit.equals(ImperialUnits.FAHRENHEIT)) { commandSet.setTargetTemperature(convertTargetFahrenheitTemperatureToInRange(quantity.floatValue())); } else if (lastResponse.getTempUnit() == true && unit.equals(SIUnits.CELSIUS)) { commandSet.setTargetTemperature(convertTargetFahrenheitTemperatureToInRange( quantity.toUnit(ImperialUnits.FAHRENHEIT).floatValue())); } else if (lastResponse.getTempUnit() == false && unit.equals(SIUnits.CELSIUS)) { commandSet.setTargetTemperature(convertTargetCelsiusTemperatureToInRange(quantity.floatValue())); } else if (lastResponse.getTempUnit() == false && unit.equals(ImperialUnits.FAHRENHEIT)) { commandSet.setTargetTemperature( convertTargetCelsiusTemperatureToInRange(quantity.toUnit(SIUnits.CELSIUS).floatValue())); } getConnectionManager().sendCommandAndMonitor(commandSet); } } else { logger.debug("handleTargetTemperature unsupported commandType:{}", command.getClass().getTypeName()); } } public void handleFanSpeed(Command command) { CommandSet commandSet = CommandSet.fromResponse(getLastResponse()); if (command instanceof StringType) { commandSet.setPowerState(true); if (command.equals(FAN_SPEED_OFF)) { commandSet.setPowerState(false); } else if (command.equals(FAN_SPEED_SILENT)) { if (getVersion() == 2) { commandSet.setFanSpeed(FanSpeed.SILENT2); } else if (getVersion() == 3) { commandSet.setFanSpeed(FanSpeed.SILENT3); } } else if (command.equals(FAN_SPEED_LOW)) { if (getVersion() == 2) { commandSet.setFanSpeed(FanSpeed.LOW2); } else if (getVersion() == 3) { commandSet.setFanSpeed(FanSpeed.LOW3); } } else if (command.equals(FAN_SPEED_MEDIUM)) { if (getVersion() == 2) { commandSet.setFanSpeed(FanSpeed.MEDIUM2); } else if (getVersion() == 3) { commandSet.setFanSpeed(FanSpeed.MEDIUM3); } } else if (command.equals(FAN_SPEED_HIGH)) { if (getVersion() == 2) { commandSet.setFanSpeed(FanSpeed.HIGH2); } else if (getVersion() == 3) { commandSet.setFanSpeed(FanSpeed.HIGH3); } } else if (command.equals(FAN_SPEED_AUTO)) { if (getVersion() == 2) { commandSet.setFanSpeed(FanSpeed.AUTO2); } else if (getVersion() == 3) { commandSet.setFanSpeed(FanSpeed.AUTO3); } } else { logger.debug("Unknown fan speed command: {}", command); return; } } getConnectionManager().sendCommandAndMonitor(commandSet); } public void handleEcoMode(Command command) { CommandSet commandSet = CommandSet.fromResponse(getLastResponse()); if (command.equals(OnOffType.OFF)) { commandSet.setEcoMode(false); } else if (command.equals(OnOffType.ON)) { commandSet.setEcoMode(true); } else { logger.debug("Unknown eco mode command: {}", command); return; } getConnectionManager().sendCommandAndMonitor(commandSet); } public void handleSwingMode(Command command) { if (getVersion() == 3) { logger.debug("Setting Swing Mode for version 3 is not supported by protocol (LAN and Cloud)"); return; } CommandSet commandSet = CommandSet.fromResponse(getLastResponse()); commandSet.setPowerState(true); if (command instanceof StringType) { if (command.equals(SWING_MODE_OFF)) { commandSet.setSwingMode(SwingMode.OFF); } else if (command.equals(SWING_MODE_VERTICAL)) { commandSet.setSwingMode(SwingMode.VERTICAL); } else if (command.equals(SWING_MODE_HORIZONTAL)) { commandSet.setSwingMode(SwingMode.HORIZONTAL); } else if (command.equals(SWING_MODE_BOTH)) { commandSet.setSwingMode(SwingMode.BOTH); } else { logger.debug("Unknown swing mode command: {}", command); return; } } getConnectionManager().sendCommandAndMonitor(commandSet); } public void handleTurboMode(Command command) { CommandSet commandSet = CommandSet.fromResponse(getLastResponse()); commandSet.setPowerState(true); if (command.equals(OnOffType.OFF)) { commandSet.setTurboMode(false); } else if (command.equals(OnOffType.ON)) { commandSet.setTurboMode(true); } else { logger.debug("Unknown turbo mode command: {}", command); return; } getConnectionManager().sendCommandAndMonitor(commandSet); } public void handleScreenDisplay(Command command) { CommandSet commandSet = CommandSet.fromResponse(getLastResponse()); if (command.equals(OnOffType.OFF)) { commandSet.setScreenDisplay(false); } else if (command.equals(OnOffType.ON)) { commandSet.setScreenDisplay(true); } else { logger.debug("Unknown screen display command: {}", command); return; } getConnectionManager().sendCommandAndMonitor(commandSet); } public void handleTempUnit(Command command) { CommandSet commandSet = CommandSet.fromResponse(getLastResponse()); if (command.equals(OnOffType.OFF)) { commandSet.setFahrenheit(false); } else if (command.equals(OnOffType.ON)) { commandSet.setFahrenheit(true); } else { logger.debug("Unknown temperature unit/farenheit command: {}", command); return; } getConnectionManager().sendCommandAndMonitor(commandSet); } @Override public void initialize() { // connectionManager.disconnect(); getConnectionManager().disconnect(); setCloudProvider(CloudProvider.getCloudProvider("MSmartHome")); setSecurity(new Security(cloudProvider)); setConfiguration(getConfigAs(MideaACConfiguration.class)); // properties = editProperties(); setProperties(editProperties()); logger.debug("MideaACHandler config for {} is {}", thing.getUID(), getConfiguration()); if (!getConfiguration().isValid()) { logger.warn("Configuration invalid for {}", thing.getUID()); if (getConfiguration().isDiscoveryNeeded()) { logger.warn("Discovery needed, thing '{}' is discovering....", thing.getUID()); updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING, "Configuration missing, discovery needed. Discovering..."); MideaACDiscoveryService discoveryService = new MideaACDiscoveryService(); // discoveryService.setSecurity(this.getSecurity()); try { discoveryService.discoverThing(getConfiguration().getIpAddress(), this); } catch (Exception e) { logger.error("Discovery failure for {}: {}", thing.getUID(), e.getMessage()); } return; } else { logger.debug("MideaACHandler config of {} is invalid. Check configuration", thing.getUID()); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Invalid MideaAC config. Check configuration."); return; } } else { logger.debug("Configuration valid for {}", thing.getUID()); } setIpAddress(getConfiguration().getIpAddress()); setIpPort(getConfiguration().getIpPort()); setDeviceId(getConfiguration().getDeviceId()); version = Integer.parseInt(getProperties().get(PROPERTY_VERSION).toString()); logger.debug("IPAddress: {}", getIpAddress()); logger.debug("IPPort: {}", getIpPort()); logger.debug("ID: {}", getDeviceId()); logger.debug("Version: {}", version); updateStatus(ThingStatus.UNKNOWN); // connectionManager.connect(); getConnectionManager().connect(); } @Override public void discovered(DiscoveryResult discoveryResult) { logger.debug("Discovered {}", thing.getUID()); Configuration updatedConfiguration = editConfiguration(); updatedConfiguration.put(CONFIG_DEVICEID, discoveryResult.getProperties().get(CONFIG_DEVICEID).toString()); updatedConfiguration.put(CONFIG_IP_PORT, discoveryResult.getProperties().get(CONFIG_IP_PORT).toString()); updateConfiguration(updatedConfiguration); setProperties(editProperties()); getProperties().put(PROPERTY_VERSION, discoveryResult.getProperties().get(PROPERTY_VERSION).toString()); getProperties().put(PROPERTY_SN, discoveryResult.getProperties().get(PROPERTY_SN).toString()); getProperties().put(PROPERTY_SSID, discoveryResult.getProperties().get(PROPERTY_SSID).toString()); getProperties().put(PROPERTY_TYPE, discoveryResult.getProperties().get(PROPERTY_TYPE).toString()); updateProperties(getProperties()); initialize(); } /* * Manage the ONLINE/OFFLINE status of the thing */ private void markOnline() { if (!isOnline()) { logger.debug("Changing status of {} from {}({}) to ONLINE", thing.getUID(), getStatus(), getDetail()); updateStatus(ThingStatus.ONLINE); // logger.debug(Arrays.toString(Thread.currentThread().getStackTrace()).replace(',', '\n')); } } private void markOffline() { if (isOnline()) { logger.debug("Changing status of {} from {}({}) to OFFLINE", thing.getUID(), getStatus(), getDetail()); updateStatus(ThingStatus.OFFLINE); // logger.debug(Arrays.toString(Thread.currentThread().getStackTrace()).replace(',', '\n')); // wait 3 seconds then reconnects } getConnectionManager().connect(); } private void markOfflineWithMessage(ThingStatusDetail statusDetail, String statusMessage) { // If it's offline with no detail or if it's not offline, mark it offline with detailed status if ((isOffline() && getDetail() == ThingStatusDetail.NONE) || (isOffline() && !statusMessage.equals(getDescription())) || !isOffline()) { logger.debug("Changing status of {} from {}({}) to OFFLINE({})", thing.getUID(), getStatus(), getDetail(), statusDetail); logger.info("Changing status of {} from {}({}) to OFFLINE({})", thing.getUID(), getStatus(), getDetail(), statusDetail); if (isOffline()) { updateStatus(ThingStatus.UNKNOWN); } try { Thread.sleep(250); } catch (InterruptedException e) { } updateStatus(ThingStatus.OFFLINE, statusDetail, statusMessage); } getConnectionManager().connect(); } private boolean isOnline() { return thing.getStatus().equals(ThingStatus.ONLINE); } private boolean isOffline() { return thing.getStatus().equals(ThingStatus.OFFLINE); } private ThingStatus getStatus() { return thing.getStatus(); } private ThingStatusDetail getDetail() { return thing.getStatusInfo().getStatusDetail(); } private @Nullable String getDescription() { return thing.getStatusInfo().getDescription(); } public void setCloudProvider(CloudProvider cloudProvider) { this.cloudProvider = cloudProvider; } public void setSecurity(Security security) { this.security = security; } /* * The {@link ConnectionManager} class is responsible for managing the state of the TCP connection to the * fan. * * @author Jacek Dobrowolski */ private class ConnectionManager { private Logger logger = LoggerFactory.getLogger(ConnectionManager.class); private boolean deviceIsConnected; private boolean connectionIsAuthenticated; // private @Nullable InetAddress ifAddress; private @Nullable Socket socket; public Socket getSocket() { return socket; } public void setSocket(Socket socket) { this.socket = socket; } public DataOutputStream getWriter() { return writer; } public void setWriter(DataOutputStream writer) { this.writer = writer; } private @Nullable InputStream inputStream; private @Nullable DataOutputStream writer; // private final int SOCKET_CONNECT_TIMEOUT = 4000; private @Nullable ScheduledFuture<?> connectionMonitorJob; private final long CONNECTION_MONITOR_FREQ = 10L; private final long CONNECTION_MONITOR_DELAY = 10L; private @Nullable Response lastResponse; private final MideaACHandler mideaACHandler; @Nullable public Response getLastResponse() { return lastResponse; } Runnable connectionMonitorRunnable = () -> { logger.trace("Performing connection check for {} at IP {}", thing.getUID(), getIpAddress()); checkConnection(); }; public ConnectionManager(String ipv4Address, MideaACHandler mideaACHandler) { deviceIsConnected = false; this.mideaACHandler = mideaACHandler; } /* * Connect to the command and serial port(s) on the device. The serial connections are established only for * devices that support serial. */ private Date getTokenReqested() { Cloud cloud = mideaACHandler.getClouds().get(getConfiguration().getEmail(), getConfiguration().getPassword(), cloudProvider); return cloud.getTokenRequested(); } private boolean reAuthenticationNeeded() { int reuth = getConfiguration().getReauth(); if (reuth == 0) { return false; } Calendar now = Calendar.getInstance(); Calendar tokenReqeustedAt = Calendar.getInstance(); tokenReqeustedAt.setTime(getTokenReqested()); tokenReqeustedAt.add(Calendar.HOUR, reuth); if (now.compareTo(tokenReqeustedAt) > 0) { return true; } return false; } protected synchronized void connect() { if (reAuthenticationNeeded()) { logger.info("Force re-authentication has initiated"); authenticate(); } if (isConnected()) { return; } logger.trace("Connecting to {} at {}:{}", thing.getUID(), getIpAddress(), getIpPort()); // Open socket try { setSocket(new Socket()); getSocket().setSoTimeout(getConfiguration().getTimeout() * 1000); int connectionRetry = getConfiguration().getConnectionRetry(); int numberOfRetries = 0; boolean connected = false; // socket.setReuseAddress(true); // socket.bind(new InetSocketAddress(0)); // TODO: allow choosing adapter? // new InetSocketAddress(0) // socket.setReuseAddress(true); if (getIpPort() != null) { while (!connected || numberOfRetries <= connectionRetry) { try { getSocket().connect(new InetSocketAddress(getIpAddress(), Integer.valueOf(getIpPort())), getConfiguration().getTimeout() * 1000); connected = true; } catch (IOException | NumberFormatException te) { numberOfRetries++; logger.info("Socket connection exception {}. Try reconnection {} time(s)", te.getMessage(), numberOfRetries); } } } } catch (IOException e) { logger.debug("IOException connecting to {} at {}: {}", thing.getUID(), getIpAddress(), e.getMessage()); String message = ">>>" + e.getMessage(); if (message != null) { markOfflineWithMessage(ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, message + " [connect IOException] "); } else { markOfflineWithMessage(ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, " [connect IOException] "); } disconnect(); scheduleConnectionMonitorJob(); return; } // Create streams try { setWriter(new DataOutputStream(getSocket().getOutputStream())); setInputStream(getSocket().getInputStream()); } catch (IOException e) { logger.warn("IOException getting streams for {} at {}: {}", thing.getUID(), getIpAddress(), e.getMessage(), e); String message = "!!!" + e.getMessage(); if (message != null) { markOfflineWithMessage(ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, message + " [connect create streams IOException]"); } else { markOfflineWithMessage(ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, " [connect create streams IOException]"); } disconnect(); return; } logger.info("Connected to {} at {}", thing.getUID(), getIpAddress()); deviceIsConnected = true; markOnline(); if (getVersion() != 3) { logger.debug("Device {}@{} not require authentication, getting status", thing.getUID(), getIpAddress()); requestStatus(true); } else { logger.debug("Device {}@{} require authentication, going to authenticate", thing.getUID(), getIpAddress()); authenticate(); } } public InputStream getInputStream() { return inputStream; } public void setInputStream(InputStream inputStream) { this.inputStream = inputStream; } public void authenticate() { logger.trace("Version: {}", getVersion()); logger.trace("Key: {}", getConfiguration().getKey()); logger.trace("Token: {}", getConfiguration().getToken()); if (getVersion() == 3) { if (StringUtils.isBlank(getConfiguration().getToken()) == false && StringUtils.isBlank(getConfiguration().getKey()) == false) { logger.debug("Device {}@{} authenticating", thing.getUID(), getIpAddress()); doAuthentication(); } else { if (StringUtils.isBlank(getConfiguration().getToken()) && StringUtils.isBlank(getConfiguration().getKey())) { if (StringUtils.isBlank(getConfiguration().getEmail()) || StringUtils.isBlank(getConfiguration().getPassword())) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Token and Key missing in configuration."); logger.warn("Device {}@{} cannot authenticate, token and key missing", thing.getUID(), getIpAddress()); } else { if (StringUtils.isBlank(getConfiguration().getCloud())) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Cloud Provider missing in configuration."); logger.warn("Device {}@{} cannot authenticate, Cloud Provider missing", thing.getUID(), getIpAddress()); } else { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_PENDING, "Retrieving Token and Key from cloud."); logger.info("Retrieving Token and Key from cloud"); CloudProvider cloudProvider = CloudProvider .getCloudProvider(getConfiguration().getCloud()); getTokenKeyCloud(cloudProvider); } } } else if (StringUtils.isBlank(getConfiguration().getToken())) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Token missing in configuration."); logger.warn("Device {}@{} cannot authenticate, token missing", thing.getUID(), getIpAddress()); } else if (StringUtils.isBlank(getConfiguration().getKey())) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Key missing in configuration."); logger.warn("Device {}@{} cannot authenticate, key missing", thing.getUID(), getIpAddress()); } } } else { logger.warn("Device {}@{} with version {} does not require authentication, not going to authenticate", thing.getUID(), getIpAddress(), getVersion()); } } private void getTokenKeyCloud(CloudProvider cloudProvider) { Cloud cloud = mideaACHandler.getClouds().get(getConfiguration().getEmail(), getConfiguration().getPassword(), cloudProvider); // Cloud cloud = new Cloud(config.getEmail(), config.getPassword(), cloudProvider); cloud.setHttpClient(httpClient); if (cloud.login()) { TokenKey tk = cloud.getToken(getConfiguration().getDeviceId()); Configuration configuration = editConfiguration(); configuration.put(CONFIG_TOKEN, tk.getToken()); configuration.put(CONFIG_KEY, tk.getKey()); updateConfiguration(configuration); logger.trace("Token: {}", tk.getToken()); logger.trace("Key: {}", tk.getKey()); logger.warn("Token and Key obtained from cloud, saving, initializing"); initialize(); } else { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, String.format("Can't retrieve Token and Key from Cloud (%s).", cloud.getErrMsg())); logger.warn("Can't retrieve Token and Key from Cloud ({})", cloud.getErrMsg()); } } private void doAuthentication() { // byte[] request = Security.encode_8370(Utils.hexStringToByteArray(config.getToken()), // MsgType.MSGTYPE_HANDSHAKE_REQUEST); byte[] request = mideaACHandler.getSecurity().encode_8370( Utils.hexStringToByteArray(getConfiguration().getToken()), MsgType.MSGTYPE_HANDSHAKE_REQUEST); try { logger.trace("Device {}@{} writing handshake_request: {}", thing.getUID(), getIpAddress(), Utils.bytesToHex(request)); write(request); byte[] response = read(); logger.trace("Device {}@{} response for handshake_request length: {}", thing.getUID(), getIpAddress(), response.length); if (response != null && response.length > 0) { logger.trace("Device {}@{} response for handshake_request: {}", thing.getUID(), getIpAddress(), Utils.bytesToHex(response)); if (response.length == 72) { // boolean success = Security.tcp_key(Arrays.copyOfRange(response, 8, 72), // Utils.hexStringToByteArray(config.getKey())); boolean success = mideaACHandler.getSecurity().tcp_key(Arrays.copyOfRange(response, 8, 72), Utils.hexStringToByteArray(getConfiguration().getKey())); if (success) { logger.debug("Authentication successufull"); connectionIsAuthenticated = true; try { Thread.sleep(1000); } catch (InterruptedException e) { logger.error("doAuthentication has thrown InterruptedException exception {}", e.getMessage()); } requestStatus(true); } else { logger.debug("Invalid Key. Correct Key in configuration"); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Invalid Key. Correct Key in configuration."); } } else if ("ERROR".getBytes().equals(response)) { logger.warn("Authentication failed!"); } else { logger.warn("Authentication reponse unexpected data length ({} instead of 72)!", response.length); logger.debug("Invalid Token. Correct Token in configuration"); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Invalid Token. Correct Token in configuration."); } } } catch (IOException e) { logger.error("doAuthentication has thrown IOException exception {}", e.getMessage()); } } public void requestStatus(boolean restartMonitor) { CommandBase requestStatusCommand = new CommandBase(); if (restartMonitor) { sendCommandAndMonitor(requestStatusCommand); } else { sendCommand(requestStatusCommand); } } public void sendCommandAndMonitor(CommandBase command) { cancelConnectionMonitorJob(); sendCommand(command); scheduleConnectionMonitorJob(); } public void sendCommand(CommandBase command) { if (command instanceof CommandSet) { ((CommandSet) command).setPromptTone(getConfiguration().getPromptTone()); } Packet packet = new Packet(command, getDeviceId(), mideaACHandler); packet.finalize(); if (!isConnected()) { logger.debug("Unable to send message; no connection to {}. Trying to reconnect: {}", thing.getUID(), command); // connect(); getConnectionManager().connect(); if (isConnected()) { sendCommand(command); return; } } try { byte[] bytes = packet.getBytes(); logger.debug("Writing to {} at {} bytes.length: {}, bytes: {}", thing.getUID(), getIpAddress(), bytes.length, Utils.bytesToHex(bytes)); if (getVersion() == 3) { bytes = mideaACHandler.getSecurity().encode_8370(bytes, MsgType.MSGTYPE_ENCRYPTED_REQUEST); } write(bytes); byte[] responseBytes = read(); if (responseBytes != null) { markOnline(); if (getVersion() == 3) { Decryption8370Result result = mideaACHandler.getSecurity().decode_8370(responseBytes); for (byte[] response : result.getResponses()) { logger.debug("Response length: {}", response.length); logger.trace("Packet: {}", Utils.bytesToHex(responseBytes)); if (response.length > 40 + 16) { byte[] data = mideaACHandler.getSecurity() .aes_decrypt(Arrays.copyOfRange(response, 40, response.length - 16)); // The response data from the appliance includes a packet header which we don't want data = Arrays.copyOfRange(data, 10, data.length); logger.trace("Bytes decoded and stripped without header: length: {}, data: {}", data.length, Utils.bytesToHex(data)); if (data.length > 0) { if (data.length != 25) { logger.error("Response data is not 25 long!"); return; } lastResponse = new Response(data, getVersion()); try { processMessage(lastResponse); } catch (Exception ex) { logger.warn("Error processing response: {}", ex.getMessage()); } } } } } else { byte[] data = security .aes_decrypt(Arrays.copyOfRange(responseBytes, 40, responseBytes.length - 16)); // The response data from the appliance includes a packet header which we don't want data = Arrays.copyOfRange(data, 10, data.length); logger.trace("Bytes decoded and stripped without header: length: {}, data: {}", data.length, Utils.bytesToHex(data)); lastResponse = new Response(data, getVersion()); processMessage(lastResponse); } return; } else { markOfflineWithMessage(ThingStatusDetail.COMMUNICATION_ERROR, "Device not responding with its status.Response bytes is null."); } } catch (SocketException e) { logger.debug("SocketException writing to {} at {}: {}", thing.getUID(), getIpAddress(), e.getMessage()); String message = e.getMessage(); if (message != null) { markOfflineWithMessage(ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, message + " [sendCommand SocketException]"); } else { markOfflineWithMessage(ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, " [sendCommand SocketException]"); } disconnect(); } catch (IOException e) { logger.debug("IOException writing to {} at {}: {}", thing.getUID(), getIpAddress(), e.getMessage()); String message = e.getMessage(); if (message != null) { markOfflineWithMessage(ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, message + " [sendCommand IOException]"); } else { markOfflineWithMessage(ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, " [sendCommand IOException]"); } disconnect(); } scheduleConnectionMonitorJob(); // ZZZ } protected synchronized void disconnect() { if (!isConnected()) { return; } logger.debug("Disconnecting from {} at {}", thing.getUID(), getIpAddress()); try { if (getWriter() != null) { getWriter().close(); } if (getInputStream() != null) { getInputStream().close(); } if (getSocket() != null) { getSocket().close(); } } catch (IOException e) { logger.warn("IOException closing connection to {} at {}: {}", thing.getUID(), getIpAddress(), e.getMessage(), e); } deviceIsConnected = false; setSocket(null); setInputStream(null); setWriter(null); markOffline(); } private void updateChannel(String channelName, State state) { if (isOffline()) { return; } Channel channel = thing.getChannel(channelName); if (channel != null) { updateState(channel.getUID(), state); } } private void processMessage(Response response) { if (response == null) { return; } updateChannel(CHANNEL_POWER, response.getPowerState() == true ? OnOffType.ON : OnOffType.OFF); updateChannel(CHANNEL_IMODE_RESUME, response.getImmodeResume() == true ? OnOffType.ON : OnOffType.OFF); updateChannel(CHANNEL_TIMER_MODE, response.getTimerMode() == true ? OnOffType.ON : OnOffType.OFF); updateChannel(CHANNEL_APPLIANCE_ERROR, response.getApplianceError() == true ? OnOffType.ON : OnOffType.OFF); updateChannel(CHANNEL_TARGET_TEMPERATURE, new QuantityType<>(response.getTargetTemperature(), response.getTempUnit() == true ? ImperialUnits.FAHRENHEIT : SIUnits.CELSIUS)); // new // DecimalType(response.getTargetTemperature())); updateChannel(CHANNEL_OPERATIONAL_MODE, new StringType(response.getOperationalMode().toString())); updateChannel(CHANNEL_FAN_SPEED, new StringType(response.getFanSpeed().toString())); updateChannel(CHANNEL_ON_TIMER, new StringType(response.getOnTimer().toChannel())); updateChannel(CHANNEL_OFF_TIMER, new StringType(response.getOffTimer().toChannel())); updateChannel(CHANNEL_SWING_MODE, new StringType(response.getSwingMode().toString())); updateChannel(CHANNEL_COZY_SLEEP, new DecimalType(response.getCozySleep())); updateChannel(CHANNEL_SAVE, response.getSave() == true ? OnOffType.ON : OnOffType.OFF); updateChannel(CHANNEL_LOW_FREQUENCY_FAN, response.getLowFrequencyFan() == true ? OnOffType.ON : OnOffType.OFF); updateChannel(CHANNEL_SUPER_FAN, response.getSuperFan() == true ? OnOffType.ON : OnOffType.OFF); updateChannel(CHANNEL_FEEL_OWN, response.getFeelOwn() == true ? OnOffType.ON : OnOffType.OFF); updateChannel(CHANNEL_CHILD_SLEEP_MODE, response.getChildSleepMode() == true ? OnOffType.ON : OnOffType.OFF); updateChannel(CHANNEL_EXCHANGE_AIR, response.getExchangeAir() == true ? OnOffType.ON : OnOffType.OFF); updateChannel(CHANNEL_DRY_CLEAN, response.getDryClean() == true ? OnOffType.ON : OnOffType.OFF); updateChannel(CHANNEL_AUX_HEAT, response.getAuxHeat() == true ? OnOffType.ON : OnOffType.OFF); updateChannel(CHANNEL_ECO_MODE, response.getEcoMode() == true ? OnOffType.ON : OnOffType.OFF); updateChannel(CHANNEL_CLEAN_UP, response.getCleanUp() == true ? OnOffType.ON : OnOffType.OFF); updateChannel(CHANNEL_TEMP_UNIT, response.getTempUnit() == true ? OnOffType.ON : OnOffType.OFF); updateChannel(CHANNEL_SLEEP_FUNCTION, response.getSleepFunction() == true ? OnOffType.ON : OnOffType.OFF); updateChannel(CHANNEL_TURBO_MODE, response.getTurboMode() == true ? OnOffType.ON : OnOffType.OFF); updateChannel(CHANNEL_CATCH_COLD, response.getCatchCold() == true ? OnOffType.ON : OnOffType.OFF); updateChannel(CHANNEL_NIGHT_LIGHT, response.getNightLight() == true ? OnOffType.ON : OnOffType.OFF); updateChannel(CHANNEL_PEAK_ELEC, response.getPeakElec() == true ? OnOffType.ON : OnOffType.OFF); updateChannel(CHANNEL_NATURAL_FAN, response.getNaturalFan() == true ? OnOffType.ON : OnOffType.OFF); float cit = dataHistory.get(CHANNEL_INDOOR_TEMPERATURE, response.getIndoorTemperature()); updateChannel(CHANNEL_INDOOR_TEMPERATURE, new QuantityType<Temperature>(response.getIndoorTemperature(), response.getTempUnit() == true ? ImperialUnits.FAHRENHEIT : SIUnits.CELSIUS)); // new // updateChannel(CHANNEL_INDOOR_TEMPERATURE, new // QuantityType<Temperature>(response.getIndoorTemperature(),response.getTempUnit() == true ? // ImperialUnits.FAHRENHEIT : SIUnits.CELSIUS)); // new // DecimalType(response.getIndoorTemperature())); updateChannel(CHANNEL_INDOOR_TEMPERATURE, new QuantityType<Temperature>(cit, response.getTempUnit() == true ? ImperialUnits.FAHRENHEIT : SIUnits.CELSIUS)); float cot = dataHistory.get(CHANNEL_OUTDOOR_TEMPERATURE, response.getOutdoorTemperature()); // updateChannel(CHANNEL_OUTDOOR_TEMPERATURE, new // QuantityType<Temperature>(response.getOutdoorTemperature(), response.getTempUnit() == true ? // ImperialUnits.FAHRENHEIT : SIUnits.CELSIUS)); // new // DecimalType(response.getOutdoorTemperature())); updateChannel(CHANNEL_OUTDOOR_TEMPERATURE, new QuantityType<>(cot, response.getTempUnit() == true ? ImperialUnits.FAHRENHEIT : SIUnits.CELSIUS)); updateChannel(CHANNEL_HUMIDITY, new DecimalType(response.getHumidity())); } public byte @Nullable [] read() { byte[] bytes = new byte[512]; try { if (getInputStream() != null) { // int len = getInputStream().read(bytes); int len = readInputStreamWithTimeout(getInputStream(), bytes, getConfiguration().getReadSocketTimeout()); if (len > 0) { logger.debug("Response received length: {}", len); bytes = Arrays.copyOfRange(bytes, 0, len); logger.debug("Response bytes: {}", Utils.bytesToHex(bytes)); return bytes; } } } catch (IOException e) { disconnect(); String message = e.getMessage(); if (message != null) { markOfflineWithMessage(ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, message + " [read IOException]"); } else { markOfflineWithMessage(ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, " [read IOException]"); } } return null; } public int readInputStreamWithTimeout(InputStream is, byte[] b, int timeoutMillis) throws IOException { int bufferOffset = 0; long maxTimeMillis = System.currentTimeMillis() + timeoutMillis; while (System.currentTimeMillis() < maxTimeMillis && bufferOffset < b.length) { int readLength = java.lang.Math.min(is.available(), b.length - bufferOffset); // can alternatively use bufferedReader, guarded by isReady(): int readResult = is.read(b, bufferOffset, readLength); if (readResult == -1) { break; } bufferOffset += readResult; } return bufferOffset; } public void write(byte[] buffer) throws IOException { if (getWriter() == null) { logger.warn("fanWriter for {} is null when trying to write to {}!!!", thing.getUID(), getIpAddress()); return; } getWriter().write(buffer, 0, buffer.length); } private boolean isConnected() { return deviceIsConnected && !getSocket().isClosed() && getSocket().isConnected(); } /* * Periodically validate the command connection to the device by executing a getversion command. */ private void scheduleConnectionMonitorJob() { if (connectionMonitorJob == null) { logger.debug("Starting connection monitor job in {} seconds for {} at {}", getConfiguration().getPollingTime(), thing.getUID(), getIpAddress()); connectionMonitorJob = scheduler.scheduleWithFixedDelay(connectionMonitorRunnable, CONNECTION_MONITOR_DELAY, CONNECTION_MONITOR_FREQ, TimeUnit.SECONDS); } } private void cancelConnectionMonitorJob() { if (connectionMonitorJob != null) { logger.debug("Cancelling connection monitor job for {} at {}", thing.getUID(), getIpAddress()); connectionMonitorJob.cancel(true); connectionMonitorJob = null; } } private void checkConnection() { logger.trace("Checking status of connection for {} at {}", thing.getUID(), getIpAddress()); if (!isConnected()) { logger.debug("Connection check FAILED for {} at {}", thing.getUID(), getIpAddress()); if (getVersion() == 2 || getVersion() == 3 && connectionIsAuthenticated == true) { // connect(); getConnectionManager().connect(); } } else { logger.debug("Connection check OK for {} at {}", thing.getUID(), getIpAddress()); logger.debug("Requesting status update from {} at {}", thing.getUID(), getIpAddress()); requestStatus(false); } } public void dispose() { cancelConnectionMonitorJob(); } } }
// // IconListView.swift // AdmiralSwiftUI // // Created on 21.06.2021. // import SwiftUI import AdmiralTheme /** IconListViewStyle - Public enum for CardListView IconListViewStyle can be one of the following values: - paragraph - paragraphSecondary */ public enum IconListViewStyle: String { case paragraph case paragraphSecondary } /** IconListView - A view object with icon view. You can create a IconListView with the zero frame rectangle by specifying the following parameters in init: - image: Image - The image displayed in the image view. - renderingMode: Image.TemplateRenderingMode - The Image template rendering mod. Default state is .original - iconListViewStyle: IconListViewStyle? - The style of IconListView ## Example to create IconListView # Code ``` IconListView(image: Image("Your icon list image")) ``` */ /// A view object with icon view. @available(iOS 14.0, *) public struct IconListView: View, TralingListViewComponent { // MARK: - Public Properties /// The image displayed in the image view. @Binding public var image: Image @State public var isHighlighted: Bool = false @State public var isHighlightedEnabled: Bool = true // MARK: Internal Properties @Environment(\.isEnabled) var isEnabled var iconListViewStyle: IconListViewStyle? var renderingMode: Image.TemplateRenderingMode @ObservedObject private var schemeProvider: SchemeProvider<IconListViewScheme> // MARK: - Initializer /// Initializes and returns a newly allocated view object with the zero frame rectangle. public init( image: Image, renderingMode: Image.TemplateRenderingMode = .original, iconListViewStyle: IconListViewStyle? = nil, schemeProvider: SchemeProvider<IconListViewScheme> = AppThemeSchemeProvider<IconListViewScheme>() ) { self._image = Binding(get: { return image }, set: { _ in }) self.renderingMode = renderingMode self.iconListViewStyle = iconListViewStyle self.schemeProvider = schemeProvider } // MARK: - Body public var body: some View { let scheme = schemeProvider.scheme switch renderingMode { case .original: image .opacity(scheme.imageViewAlpha.parameter(for: isEnabled ? .normal : .disabled) ?? 1.0) case .template: image .foregroundColor(scheme.imageTintColor.parameter(for: isEnabled ? .normal : .disabled, style: iconListViewStyle)?.swiftUIColor) @unknown default: Spacer() } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Video Player</title> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f4f4f4; } #video-container { position: relative; } video { width: 100%; height: auto; } #playlist { list-style: none; padding: 0; margin: 10px; max-height: 200px; overflow-y: auto; } #playlist li { cursor: pointer; padding: 8px; border-bottom: 1px solid #ccc; background-color: #fff; } #playlist li:hover { background-color: #e0e0e0; } #controls { display: flex; justify-content: space-between; margin: 10px; } </style> </head> <body> <div id="video-container"> <video id="video" controls> Your browser does not support the video tag. </video> </div> <div> <ul id="playlist"></ul> </div> <div id="controls"> <input type="file" id="fileInput" accept="video/*" multiple /> <!-- <button id="folderInput">Add Folder</button> --> </div> <script> const video = document.getElementById('video'); const playlist = document.getElementById('playlist'); const fileInput = document.getElementById('fileInput'); const folderInput = document.getElementById('folderInput'); fileInput.addEventListener('change', handleFileSelect); folderInput.addEventListener('click', openFolderDialog); function handleFileSelect(event) { const files = event.target.files; if (files.length > 0) { clearPlaylist(); for (const file of files) { addVideoToPlaylist(file); } playVideo(files[0]); } } function openFolderDialog() { alert("Folder selection is not supported in browsers due to security restrictions. Please select video files individually."); } function addVideoToPlaylist(file) { const listItem = document.createElement('li'); listItem.textContent = file.name; listItem.addEventListener('click', () => playVideo(file)); playlist.appendChild(listItem); } function playVideo(file) { const videoURL = URL.createObjectURL(file); video.src = videoURL; } function clearPlaylist() { playlist.innerHTML = ''; } </script> </body> </html>
# File: tokio/tokio-stream/src/stream_ext/take.rs 在tokio-stream crate的stream_ext/take.rs文件中,定义了一个take() trait扩展,用于从流中获取指定数量的元素。 具体来说,该文件中的Take<St>结构体和它的属性和方法提供了以下功能: 1. Take<St>结构体描述了一个具体的take扩展。它是具体类型的泛型,这里命名为St。 2. Take<St>结构体实现了Stream trait,因此可以被Tokio框架处理和操作。 3. Take<St>结构体具有以下属性: - stream:一个类型为St的属性,表示要从中获取元素的流。 - remaining:一个usize属性,表示还需要获取的剩余元素的数量。 4. Take<St>中定义了一个new()方法,用于创建一个Take实例。该方法接收一个类型为St的参数和一个usize类型的参数,分别表示要获取元素的流和需要获取的元素的数量。 5. Take<St>结构体实现了Stream的poll_next()方法。该方法具有以下行为: - 首先检查剩余元素的数量(remaining属性),如果数量为0,则表示已经获取到指定数量的元素,返回Poll::Ready(None)。 - 如果剩余元素数量不为0,则调用stream属性的poll_next()方法,返回它的结果。 - 如果stream的poll_next()方法返回Poll::Ready(Some(item)),则将remaining减一,并返回相同的结果。 - 如果stream的poll_next()方法返回Poll::Ready(None),则表示流中已经没有更多的元素了,返回Poll::Ready(None)。 - 如果stream的poll_next()方法返回Poll::Pending,则表示流中暂时没有更多的元素可用,返回Poll::Pending。 Take<St>结构体的作用是在流中只获取指定数量的元素,保证不会获取超过指定数量的元素,并且可以与其他tokio框架的stream和task配合使用。
/* eslint-disable @typescript-eslint/no-unsafe-member-access */ import axios from "axios"; import type { Locale } from "~/lang/index"; import type { FavoriteProducts, Product, ProductByCategory, ProductGetResponse, SingleProduct, SingleProductDetails, } from "~/types/product"; import type { GoogleUser, LoginPayload } from "~/types/user"; export const baseApiClient = axios.create({ baseURL: "https://api.kh.smart-market.uz", }); export const publicApiClientV3 = axios.create({ baseURL: "https://api.kh.smart-market.uz/api/v3", }); export const publicApiClientV2 = axios.create({ baseURL: "https://api.kh.smart-market.uz/api/v2", }); export const publicApiClientV1 = axios.create({ baseURL: "https://api.kh.smart-market.uz/api/v1", }); export const uploadsApiClient = axios.create({ baseURL: "https://api.cabinet.smart-market.uz/uploads", }); export async function loginHandler({ password, username }: LoginPayload) { return await baseApiClient.post("/auth/login", { password, username, }); } export async function getUserInfo(token: string) { if (!token) return; try { const response = await axios.get( "https://www.googleapis.com/userinfo/v2/me", { headers: { Authorization: `Bearer ${token}`, }, }, ); const user = (await response.data) as GoogleUser; return { user, }; } catch (error) { return { error, }; } } export async function getPopularProducts( max: number, code = 0, ): Promise<ProductGetResponse> { return ( await publicApiClientV3.get("/mobile/products/popular", { params: { page_size: max, unit_id: code, }, }) ).data.data as ProductGetResponse; } export async function getLatestProducts( size = 5, code = 4, ): Promise<ProductGetResponse> { return ( await publicApiClientV2.get("/home/product/new", { params: { page_size: size, code, }, }) ).data.data as ProductGetResponse; } interface GetSingleProductProps { product_id: Product["id"]; lang?: Locale; region_id?: number; district_id?: number; } export async function getSingleProduct({ region_id = 26, district_id = 2601, lang = "en", product_id, }: GetSingleProductProps) { return ( await publicApiClientV2.get("/sync/frontend/catalog/product/detail", { params: { region_id, district_id, lang, product_id, }, }) ).data as unknown as SingleProduct; } export async function getCheapestProducts( size = 5, code = 4, ): Promise<ProductGetResponse> { return ( await publicApiClientV3.get("/home/product/cheap", { params: { page_size: size, code, }, }) ).data.data as ProductGetResponse; } interface GetProductsByCategoryProps { category_id: number; lang?: Locale; page?: number; page_size?: number; sorting?: string; order?: "asc" | "desc"; all_regions?: number; } export async function getProductsByCategory({ category_id, page = 1, page_size = 5, sorting = "popular", order = "asc", all_regions = 1, lang, }: GetProductsByCategoryProps) { return ( await publicApiClientV2.get("/sync/frontend/catalog/products", { params: { category_id, lang, page, page_size, sorting, order, all_regions, }, }) ).data as ProductByCategory; } interface SearchProductsProps extends GetProductsByCategoryProps { query: string; } // eslint-disable-next-line @typescript-eslint/ban-types export function debounce(cb: Function, delay = 1000) { let timer: NodeJS.Timeout; return (...args: never[]) => { clearTimeout(timer); timer = setTimeout(() => { cb(...args); }, delay); }; } export const debounceSearch = debounce(searchProducts); export async function searchProducts({ query = "", ...params }: SearchProductsProps) { if (!params.category_id) return []; const products = await getProductsByCategory({ ...params, }); const filteredProducts = products.data.products.filter((p) => { const regex = new RegExp(query, "i"); return regex.test((p as unknown as SingleProductDetails).name); }); return filteredProducts; } export async function deepSearchProducts({ query }: { query: string }) { const products = await getCheapestProducts(50); const regexPattern = new RegExp(query, "i"); const filteredProducts = products.products.filter((p) => regexPattern.test((p as unknown as SingleProduct["data"]).name), ); return filteredProducts; } export async function getCategories(lang: Locale) { return ( await publicApiClientV2.get("/home/main/categories", { params: { lang, }, }) ).data.data as Category[]; } interface GetCatalogProps { code?: number; lang: Locale; } interface GetSingleCatalogProps extends GetCatalogProps { id: Category["id"]; } export async function getCatalogs({ lang, code }: GetCatalogProps) { return ( await publicApiClientV1.get("/sync/frontend/catalogs", { params: { lang, code, }, }) ).data as Catalogs; } export async function getSingleCatalog({ lang, id }: GetSingleCatalogProps) { const catalogs = await getCatalogs({ lang, }); const catalog = catalogs.data.categories.find((c) => c.id === id); const subCatalogs = catalogs.data.categories.filter( (c) => c.parent_id === catalog?.parent_id, ); return { catalog, subCatalogs, }; } interface SearchCatalogProps { lang: Locale; query: string; } export async function searchCatalogs({ lang, query }: SearchCatalogProps) { const categories = await getCatalogs({ lang, }); const queryRegex = new RegExp(query, "i"); const filteredCategories = categories.data.categories.filter((c) => queryRegex.test(c.name), ); return filteredCategories; } // regions export async function getRegions(lang: Locale) { return ( await publicApiClientV1.get("/sync/frontend/region", { params: { lang, }, }) ).data as Region; } // sellers interface GetSellerProps { lang: Locale; category_id: number; page: number; page_size: number; search: string; all_regions: number; } export async function getSellers({ category_id = 0, page = 1, page_size = 20, search = "", all_regions = 1, ...params }: Partial<GetSellerProps>) { return ( await publicApiClientV2.get("/filters", { params: { category_id, page, page_size, search, all_regions, ...params, }, }) ).data as Seller; } // cart interface GetProductsByMultipleIdsProps { ids: string; } export async function getProductsByMultipleIds({ ids, }: GetProductsByMultipleIdsProps) { const data = ( await publicApiClientV2.get("/products_by_ids", { params: { ids, }, }) ).data as FavoriteProducts; return data; }
import React, { useState } from "react"; import axios from "axios"; import Button from "@mui/material/Button"; import Input from "@mui/material/Input"; const Search = (props) => { const [state, setState] = useState({ value: '', data: [] }); const fetchMovieData = async (query) => { return await axios.get('/api/search', { params: { s: query }, headers: { Authorization: `Bearer ${props.state.token}` } }); }; const change = value => { setState({ ...state, value }); }; const search = async () => { const response = await fetchMovieData(state.value); console.log(response); setState({ ...state, data: response.data.results ?? [] }); }; return <div> <Input value={state.value} onChange={ev => change(ev.target.value)} /> <Button onClick={() => search()}>Search</Button> <ul> {state.data.map(m => <li key={m.Title}>{m.Title}</li>)} </ul> </div>; }; export default Search; // class Search extends Component { // constructor(props) { // super(props); // this.state = { // Posts: [], // }; // this.cancelToken = ""; // this.onIptClick = this.onIptClick.bind(this); // this.node = React.createRef(); // } // componentDidMount() { // document.addEventListener("mousedown", this.onIptClick); // } // componentWillUnmount() { // document.removeEventListener("mousedown", this.onIptClick); // } // onIptClick = (e) => { // if (this.node.current.contains(e.target)) { // return; // } // this.setState({ // Posts: [], // }); // }; // onLsChange = async (e) => { // if (this.isReqToken) { // this.isReqToken.cancel(); // } // this.isReqToken = axios.CancelToken.source(); // await axios // .get("https://jsonplaceholder.typicode.com/albums", { // isReqToken: this.isReqToken.token, // }) // .then((res) => { // this.setState({ // Posts: res.data, // }); // }) // .catch((error) => { // if (axios.isCancel(error) || error) { // console.log("Could not get"); // } // }); // let filterSearch = e.target.value.toLowerCase(); // let searchRes = this.state.Posts.filter((e) => { // let finalRes = e.title.toLowerCase(); // return finalRes.indexOf(filterSearch) !== -1; // }); // this.setState({ // Posts: searchRes, // }); // }; // render() { // return ( // <div className="searchModule"> // <h2> React Live Search Example - positronX</h2> // <input // onClick={this.onIptClick} // onChange={this.onLsChange} // type="text" // placeholder="Search ..." // ref={this.node} // /> // <ul> // {this.state.Posts.map((res) => { // return <li key={res.id}>{res.title}</li>; // })} // </ul> // </div> // ); // } // } // export default Search;
/* Template Name: Metronic - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.1.0 Version: 2.0 Author: KeenThemes Website: http://www.keenthemes.com/ Purchase: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keentheme */ /********************* GENERAL UI COLORS *********************/ /*** Colors blue: #4b8df8 light blue: #bfd5fa red: #e02222 yellow: #ffb848 green: #35aa47 purple: #852b99 dark: #555555; light grey: #fafafa; ***/ /********************* GENERAL RESET & SETUP *********************/ /*** Reset and overrides ***/ /* general body settings */ body { color: #000; font-family: 'Open Sans', sans-serif; padding: 0px !important; margin: 0px !important; font-size: 13px; direction: ltr; } /* Internet Explorer 10 doesn't differentiate device width from viewport width, and thus doesn't properly apply the media queries in Bootstrap's CSS. To address this, you can optionally include the following CSS and JavaScript to work around this problem until Microsoft issues a fix. */ @-webkit-viewport { width: device-width; } @-moz-viewport { width: device-width; } @-ms-viewport { width: device-width; } @-o-viewport { width: device-width; } @viewport { width: device-width; } /* Internet Explorer 10 doesn't differentiate device width from viewport width, and thus doesn't properly apply the media queries in Bootstrap's CSS. To address this, following CSS code applied */ @-ms-viewport { width: auto !important; } /*** Custom Scrollbars ***/ ::-webkit-scrollbar { width: 12px; } ::-webkit-scrollbar-track { background-color: #eaeaea; border-left: 1px solid #cecece; } ::-webkit-scrollbar-thumb { background-color: #cecece; &:hover { background-color: #aaa; } } ::-webkit-scrollbar-track, ::-webkit-scrollbar-thumb { border-radius: 0; box-shadow: none; border: 0; } /*** General typography ***/ h1 small, h2 small, h3 small, h4 small, h5 small, h6 small { color: #444; } h1, h2, h3, h4, h5, h6 { font-family: 'Open Sans', sans-serif; font-weight: 300 !important; } h1.block, h2.block, h3.block, h4.block, h5.block, h6.block { padding-top: 10px; padding-bottom: 10px; } a { text-shadow: none !important; color: #0d638f; outline: 0; &:focus, &:hover, &:active { outline: 0; } } /*** Fix link outlines after click ***/ /*** General backgrounds. Can be applied to any block or panel ***/ .bg-blue { background-image: none !important; background-color: #4b8df8 !important; border-color: #4b8df8 !important; color: #fff !important; } .bg-red { background-image: none !important; background-color: #e02222 !important; border-color: #e02222 !important; color: #fff !important; } .bg-yellow { background-image: none !important; background-color: #ffb848 !important; border-color: #ffb848 !important; color: #fff !important; } .bg-green { background-image: none !important; background-color: #35aa47 !important; border-color: #35aa47 !important; color: #fff !important; } .bg-purple { background-image: none !important; background-color: #852b99 !important; border-color: #852b99 !important; color: #fff !important; } .bg-dark { background-image: none !important; background-color: #555555 !important; border-color: #555555 !important; color: #fff !important; } .bg-grey { background-image: none !important; background-color: #fafafa !important; border-color: #fafafa !important; } /*** Font Awesome Icons ***/ [class^="fa-"], [class*=" fa-"] { display: inline-block; margin-top: 1px; font-size: 14px; *margin-right: .3em; line-height: 14px; } /*** Make font awesome icons fixed width(latest version issue) ***/ li { [class^="fa-"], [class*=" fa-"] { display: inline-block; width: 1.25em; text-align: center; } [class^="fa-"].icon-large, [class*=" fa-"].icon-large { /* increased font size for icon-large */ width: 1.5625em; } } .fa-lg, .icon-lg { font-size: 16px; } .fa-2x { font-size: 2em; } .fa-3x { font-size: 3em; } .fa-4x { font-size: 4em; } .fa-5x { font-size: 5em; } .icon-default { color: #ccc; } .icon-success { color: #468847; } .icon-info { color: #27a9e3; } .icon-warning { color: #dbc056; } .icon-danger { color: #B94A48; } /*** Close icon used for modal dialog and other UI element close buttons ***/ .close { display: inline-block; margin-top: 0px; margin-right: 0px; width: 9px; height: 9px; background-repeat: no-repeat !important; text-indent: -10000px; outline: none; background-image: url("../img/remove-icon-small.png") !important; } /*** General HR ***/ hr { margin: 20px 0; border: 0; border-top: 1px solid #E0DFDF; border-bottom: 1px solid #FEFEFE; } /*** Tools ***/ .display-none, .display-hide { display: none; } .no-space { margin: 0px !important; padding: 0px !important; } .no-margin { margin: 0; } .no-border { border: 0 !important; } .margin-bottom-5 { margin-bottom: 5px; } .margin-bottom-10 { margin-bottom: 10px !important; } .margin-top-10 { margin-top: 10px !important; } .margin-bottom-15 { margin-bottom: 15px !important; } .margin-bottom-20 { margin-bottom: 20px !important; } .margin-top-20 { margin-top: 20px !important; } .margin-bottom-25 { margin-bottom: 25px !important; } .margin-right-10 { margin-right: 10px !important; } .bold { font-weight: 600 !important; } .fix-margin { margin-left: 0px !important; } .border { border: 1px solid red; } .inline { display: inline; } .text-align-reverse { text-align: right; } /*** ie8 & ie9 modes ***/ .visible-ie8 { display: none; } .ie8 .visible-ie8 { display: inherit !important; } .visible-ie9 { display: none; } .ie9 .visible-ie9 { display: inherit !important; } .hidden-ie8 { display: inherit; } .ie8 .hidden-ie8 { display: none !important; } .hidden-ie9 { display: inherit; } .ie9 .hidden-ie9 { display: none !important; } /******************** GENERAL LAYOUT *********************/ /*** Header and header elements. ***/ .header { width: 100%; padding: 0 20px 0 20px; margin: 0; border: 0px; padding: 0px; box-shadow: none; height: 42px; min-height: 42px; &.navbar-fixed-top { z-index: 9995 !important; } .navbar-brand { display: inline-block; margin-top: -1px; margin-right: 0; padding-left: 0; padding-right: 0; width: 225px; img { margin-left: 20px; } &.text-logo { padding-left: 20px; padding-top: 12px; } } .navbar-toggle { margin: 8px 6px 4px 6px; padding: 0; padding-top: 2px; padding-bottom: 6px; background-image: none; filter: none; box-shadow: none; color: #fff; border: 0; &:hover { text-decoration: none; background: none; } } &.navbar .navbar-nav { margin-right: 20px; display: block; } .navbar-nav > li { margin: 0px; padding: 0px; &.dropdown { padding-left: 4px; padding-right: 4px; > a { padding-left: 4px; padding-right: 4px; &:last-child { padding-right: 0; } } &:last-child { padding-right: 2px; } .dropdown-toggle { margin: 0px; padding: 15px 10px 7px 10px; > i { font-size: 18px; } } .dropdown-menu > li > a > i { font-size: 14px; } &.user { .dropdown-toggle { padding: 7px 0px 6px 6px; &:hover { text-decoration: none; } .username { color: #ddd; } i { display: inline-block; margin-top: 5px; margin: 0; font-size: 16px; } } .dropdown-menu i { width: 15px; display: inline-block; } } .dropdown-toggle .badge { position: absolute; top: 8px; right: 20px; } } } .search-form { float: left; display: inline-block; padding: 0; height: 41px; margin: 0; .form-control { margin-top: 8px; border: 0; padding-top: 1px; padding-right: 27px; } .submit { position: relative; display: block; float: right; margin-top: -21px; margin-right: 8px; width: 13px; height: 15px; box-shadow: none; border: 0px; padding: 0px; background-color: none; background-repeat: no-repeat !important; outline: none !important; opacity: 0.8; filter: alpha(opacity = 80); &:hover { opacity: 1; filter: alpha(opacity = 100); } } } .navbar-nav { > li.dropdown.language { padding-left: 0; padding-right: 0; margin: 0; > { a { color: #ddd; font-size: 13px; padding: 11px 1px 11px 5px; > { img { margin-bottom: 2px; } i { font-size: 16px; } } } .dropdown-menu > li > a > img { margin-bottom: 2px; } } } .dropdown-menu { margin-top: 3px; } } } /*** Header Search ***/ /*** Language Bar ***/ /*** Page container ***/ .page-container { margin: 0px; padding: 0px; position: relative; &:before { display: table; content: " "; } &:after { display: table; content: " "; clear: both; } } .page-header-fixed .page-container { margin-top: 42px; } /*** IE 8 Fixes ***/ /*** Page sidebar ***/ .ie8 { .page-sidebar { width: 225px; float: left; position: relative; margin-right: -100%; } .page-content-wrapper { float: left; width: 100%; } .page-content { margin-left: 225px; margin-top: 0px; min-height: 760px; padding: 25px 20px 20px 20px; } } /*** Page content ***/ /*** IE 8 Fixes ***/ /*** Page sidebar ***/ .page-sidebar.navbar-collapse { padding: 0; } .page-sidebar-menu { list-style: none; margin: 0; padding: 0; margin: 0; padding: 0; > li { display: block; margin: 0; padding: 0; border: 0px; &.start > a { border-top-color: transparent !important; } &:last-child > a, &.last > a { border-bottom-color: transparent !important; } > a { display: block; position: relative; margin: 0; border: 0px; padding: 10px 15px; text-decoration: none; font-size: 14px; font-weight: 300; } } } .page-sidebar-fixed .page-sidebar-menu > li > a { -webkit-transition: all 0.2s ease; -moz-transition: all 0.2s ease; -o-transition: all 0.2s ease; transition: all 0.2s ease; } .page-sidebar-reversed.page-sidebar-fixed .page-sidebar-menu > li > a { -webkit-transition: none; -moz-transition: none; -o-transition: none; transition: none; } .page-sidebar-menu > li { > a i { font-size: 16px; margin-right: 5px; text-shadow: none; } &.break { margin-bottom: 20px; } &.open > a { font-size: 14px; } &.active > a { border: none; text-shadow: none; font-size: 14px; .selected { display: block; width: 8px; height: 25px; background-image: url("../img/sidebar-menu-arrow.png"); float: right; position: absolute; right: 0px; top: 8px; } } } .page-sidebar-reversed .page-sidebar-menu > li.active > a .selected { background-image: url("../img/sidebar-menu-arrow-reverse.png"); right: auto; left: 0; } .page-sidebar ul > li > a > .arrow:before { float: right; margin-top: 0px; margin-right: 5px; display: inline; font-size: 16px; font-family: FontAwesome; height: auto; content: "\f104"; font-weight: 300; text-shadow: none; } .page-sidebar-menu { > li > a > .arrow.open:before { float: right; margin-top: 0px; margin-right: 3px; display: inline; font-family: FontAwesome; height: auto; font-size: 16px; content: "\f107"; font-weight: 300; text-shadow: none; } li > a > .badge { float: right; margin-top: 1px; margin-right: 13px; } .sub-menu { padding: 0; } > li { > ul.sub-menu { display: none; list-style: none; clear: both; margin: 8px 0px 8px 0px; } &.active { > ul.sub-menu, > ul.sub-menu > li.active ul.sub-menu, > ul.sub-menu > li.active ul.sub-menu > li.active ul.sub-menu { display: block; } } > ul.sub-menu { > li { background: none; margin: 0px; padding: 0px; margin-top: 1px !important; > a { display: block; margin: 0px 0px 0px 0px; padding: 5px 0px; padding-left: 44px !important; text-decoration: none; font-size: 14px; font-weight: 300; background: none; } ul.sub-menu { display: none; list-style: none; clear: both; margin: 0px 0px 0px 0px; } } li > a > .arrow { &:before { float: right; margin-top: 1px; margin-right: 20px; display: inline; font-size: 16px; font-family: FontAwesome; height: auto; content: "\f104"; font-weight: 300; text-shadow: none; } &.open:before { float: right; margin-top: 1px; margin-right: 18px; display: inline; font-family: FontAwesome; height: auto; font-size: 16px; content: "\f107"; font-weight: 300; text-shadow: none; } } } > ul.sub-menu { > li ul.sub-menu li { background: none; margin: 0px; padding: 0px; margin-top: 1px !important; } li > ul.sub-menu > li > a { display: block; margin: 0px 0px 0px 0px; padding: 5px 0px; text-decoration: none; font-size: 14px; font-weight: 300; background: none; } > li > ul.sub-menu > li > { a { padding-left: 60px; } ul.sub-menu > li > a { padding-left: 80px; } } } > ul.sub-menu li > ul.sub-menu > li > a > i { font-size: 13px; } } } /* bagin: sidebar menu badges */ /* end: sidebar menu badges */ /* 3rd level sub menu */ /*** Sidebar Search ***/ .page-sidebar { .sidebar-search { padding: 0; margin: 0; } .header-responsive-search { display: none; } .sidebar-search .form-container { margin: 15px 20px 15px 20px; height: 35px; padding-top: 7px; .submit { display: block; float: right; margin-top: 3px; width: 13px; height: 15px; background-repeat: no-repeat; box-shadow: none; border: 0px; padding: 0px; outline: none !important; } input[type="text"] { margin: 0px; width: 165px; border: 0px; padding: 0 !important; font-size: 14px !important; box-shadow: none !important; font-size: 14px; font-weight: normal; &:focus { outline: none !important; } } } } /*** Sidebar toggler(show/hide) ***/ .sidebar-toggler { cursor: pointer; opacity: 0.5; filter: alpha(opacity = 50); width: 29px; height: 29px; background-repeat: no-repeat; &:hover { filter: alpha(opacity = 100); opacity: 1; } } .page-sidebar .sidebar-toggler { margin-top: 15px; margin-left: 175px; } .header .sidebar-toggler { float: left; display: inline-block; margin-top: 6px; margin-left: -42px; } /*** Page content ***/ .page-content { margin-top: 0px; padding: 0px; background-color: #fff; } .ie8 { .page-content { padding: 20px; margin-left: 225px; margin-top: 0px; min-height: 760px; } .page-sidebar-fixed .page-content { min-height: 600px; } .page-content.no-min-height { min-height: auto; } } .page-full-width .page-content { margin-left: 0px !important; } /*** Page title ***/ .page-title { padding: 0px; font-size: 30px; letter-spacing: -1px; display: block; color: #666; margin: 0px 0px 15px 0px; font-weight: 300; font-family: 'Open Sans', sans-serif; small { font-size: 14px; letter-spacing: 0px; font-weight: 300; color: #888; } } /*** Page breadcrumb ***/ .ie8 .row .page-breadcrumb.breadcrumb > li { margin-right: 1px; } .page-content .page-breadcrumb.breadcrumb { -webkit-border-radius: 0px; -moz-border-radius: 0px; border-radius: 0px; box-shadow: none; padding-right: 30px; padding-left: 8px; margin-top: 15px; margin-bottom: 25px; border: 0px !important; background-color: #eee; > li { > { a, i, span { color: #333; font-size: 14px; text-shadow: none; } i { color: #666; } } + li:before { display: none; } } .btn-group { right: 15px; position: absolute; margin-top: -8px; } > .btn-group .btn { padding-top: 8px; padding-bottom: 8px; } .dashboard-date-range { position: relative; top: -8px; margin-right: -30px; display: none; padding: 9px 9px 8px 9px; cursor: pointer; color: #fff; background-color: #e02222; > { span { font-size: 12px; font-weight: 300; color: #fff; text-transform: uppercase; } .fa-calendar { text-transform: none; color: #fff; margin-top: 0px; font-size: 14px; } .fa-angle-down { color: #fff; font-size: 16px; } } } } /* Dashboard breadcrumb Dropdown */ /* Dashboard date range panel */ /* hack for chrome and safari */ @media all and (-webkit-min-device-pixel-ratio: 0) { .page-content .page-breadcrumb.breadcrumb .dashboard-date-range { padding: 9px; } } /*** Footer ***/ .footer { padding: 8px 20px 5px 20px; font-size: 12px; &:after, &:before { content: ""; display: table; line-height: 0; } &:after { clear: both; } .footer-inner { float: left; display: inline-block; } .footer-tools { float: right; display: inline-block; .go-top { display: block; text-decoration: none; cursor: pointer; margin-top: -2px; margin-right: 0px; margin-bottom: 0px; font-size: 16px; padding: 0px 6px 0px 6px; i { font-size: 22px; margin-bottom: 5px; } } } } /******************** GENERAL UI ELEMENTS *********************/ /*** Icon stuff ***/ i.icon, a.icon { color: #999; margin-right: 5px; font-weight: normal; font-size: 13px; } i.icon-black { color: #000 !important; } a.icon { &:hover { text-decoration: none; -webkit-transition: all 0.1s ease-in-out; -moz-transition: all 0.1s ease-in-out; -o-transition: all 0.1s ease-in-out; -ms-transition: all 0.1s ease-in-out; transition: all 0.1s ease-in-out; opacity: .4; filter: alpha(opacity = 40); } &.huge i { font-size: 16px !important; } } i { &.big { font-size: 20px; } &.warning { color: #d12610; } &.critical { color: #37b7f3; } &.normal { color: #52e136; } } /*** Custom wells ***/ .well { background-color: #fafafa; border: 1px solid #eee; -webkit-border-radius: 0px; -moz-border-radius: 0px; border-radius: 0px; -webkit-box-shadow: none !important; -moz-box-shadow: none !important; box-shadow: none !important; &.mini { padding: 7px !important; } } /*** Form stuff ***/ /*** Bordered form layout ***/ /*** Input icons ***/ /* input with right aligned and colored icons */ /* input with left aligned icons */ .input-icon { position: relative; input { padding-left: 33px !important; } i { color: #ccc; display: block; position: absolute; margin: 11px 2px 4px 10px; width: 16px; height: 16px; font-size: 16px; text-align: center; } &.right { input { padding-left: 12px !important; padding-right: 33px !important; } i { right: 8px; float: right; } } } .has-success .input-icon > i { color: #468847; } .has-warning .input-icon > i { color: #c09853; } .has-error .input-icon > i { color: #b94a48; } /*** Portlets ***/ .portlet { clear: both; margin-top: 0px; margin-bottom: 25px; padding: 0px; > .portlet-title { margin-bottom: 15px; border-bottom: 1px solid #eee; &:after, &:before { content: ""; display: table; line-height: 0; } &:after { clear: both; } > .caption { float: left; display: inline-block; font-size: 18px; line-height: 18px; font-weight: 400; margin: 0; padding: 0; margin-bottom: 8px; > i { float: left; margin-top: 4px; display: inline-block !important; font-size: 13px; margin-right: 5px; color: #666; } } } &.blue > .portlet-title > .caption, &.green > .portlet-title > .caption, &.yellow > .portlet-title > .caption, &.red > .portlet-title > .caption, &.purple > .portlet-title > .caption, &.grey > .portlet-title > .caption { color: #fff; } &.box { &.blue > .portlet-title > .caption > i, &.green > .portlet-title > .caption > i, &.grey > .portlet-title > .caption > i, &.yellow > .portlet-title > .caption > i, &.red > .portlet-title > .caption > i, &.purple > .portlet-title > .caption > i, &.light-grey > .portlet-title > .caption > i { color: #fff; } } } .sortable .portlet > .portlet-title { cursor: move; } .portlet { > { .portlet-title > { .tools, .actions { display: inline-block; padding: 0; margin: 0; margin-top: 6px; float: right; } .tools > a { display: inline-block; height: 16px; margin-left: 5px; } .actions > .dropdown-menu i { color: #000 !important; } .tools > a { &.remove { margin-bottom: 2px; background-image: url(../img/portlet-remove-icon.png); background-repeat: no-repeat; width: 11px; } &.config { margin-bottom: 2px; background-image: url(../img/portlet-config-icon.png); background-repeat: no-repeat; width: 12px; } &.reload { margin-bottom: 2px; background-image: url(../img/portlet-reload-icon.png); width: 13px; } &.expand { margin-bottom: 2px; background-image: url(../img/portlet-expand-icon.png); width: 14px; } &.collapse { margin-bottom: 2px; background-image: url(../img/portlet-collapse-icon.png); width: 14px; } &:hover { text-decoration: none; -webkit-transition: all 0.1s ease-in-out; -moz-transition: all 0.1s ease-in-out; -o-transition: all 0.1s ease-in-out; -ms-transition: all 0.1s ease-in-out; transition: all 0.1s ease-in-out; opacity: .6; filter: 'alpha(opacity=60)'; } } .actions > { .btn-group { margin-top: -13px; } .btn { padding: 4px 10px; margin-top: -14px; } .btn-group > .btn { padding: 4px 10px; margin-top: -1px; } .btn.btn-sm { padding: 3px 8px; margin-top: -13px; } .btn-group > .btn-sm { padding: 3px 8px; margin-top: -1px; } } .pagination.pagination-sm { float: right !important; display: inline-block !important; margin: 0px; margin-top: -4px; } } .portlet-body { clear: both; padding: 0; } .portlet-empty { min-height: 125px; } .portlet-body.light-blue { background-color: #bfd5fa !important; } } &.light-blue { background-color: #bfd5fa !important; } > .portlet-body.blue, &.blue { background-color: #4b8df8 !important; } > .portlet-body.red, &.red { background-color: #e02222 !important; } > .portlet-body.yellow, &.yellow { background-color: #ffb848 !important; } > .portlet-body.green, &.green { background-color: #35aa47 !important; } > .portlet-body.purple, &.purple { background-color: #852b99 !important; } > .portlet-body.light-grey, &.light-grey { background-color: #fafafa !important; } > .portlet-body.grey, &.grey { background-color: #555555 !important; } } @media (max-width: 767px) { .portlet > .portlet-title > .actions.btn-set > { .btn-group, .btn { margin-top: 0px; margin-bottom: 5px; } } } /* draggable girds */ .ui-sortable-placeholder { border: 1px dotted black; visibility: visible !important; height: 100% !important; * { visibility: hidden; } } .sortable-box-placeholder { background-color: #f5f5f5; border: 1px dashed #DDDDDD; display: block; /* float: left;*/ margin-top: 0px !important; margin-bottom: 24px !important; * { visibility: hidden; } } /*** Solid colored portlet ***/ .portlet { &.solid { padding: 10px; > .portlet-title { > .tools { margin-top: 2px; border: 0px; } margin-bottom: 5px; border: 0px; } &.bordered > .portlet-title { margin-bottom: 15px; } &.red >, &.green >, &.yellow >, &.grey >, &.purple >, &.blue > { .portlet-title { border: 0; color: #fff; > .caption > i { border: 0; color: #fff; } } .portlet-body { border: 0; color: #fff; } } } &.bordered { border-left: 2px solid #ddd; } &.box { padding: 0px !important; > .portlet-title { padding: 8px 10px 2px 10px; border-bottom: 1px solid #eee; color: #fff !important; > .tools { margin-top: 3px; > a.remove { background-image: url(../img/portlet-remove-icon-white.png); } } } } &.solid > .portlet-title > .tools > a.remove { background-image: url(../img/portlet-remove-icon-white.png); } &.box > .portlet-title > .tools > a.config, &.solid > .portlet-title > .tools > a.config { background-image: url(../img/portlet-config-icon-white.png); } &.box > .portlet-title > .tools > a.reload, &.solid > .portlet-title > .tools > a.reload { background-image: url(../img/portlet-reload-icon-white.png); } &.box > .portlet-title > .tools > a.expand, &.solid > .portlet-title > .tools > a.expand { background-image: url(../img/portlet-expand-icon-white.png); } &.box > .portlet-title > .tools > a.collapse, &.solid > .portlet-title > .tools > a.collapse { background-image: url(../img/portlet-collapse-icon-white.png); } &.box { > { .portlet-body { background-color: #fff; padding: 10px; } .portlet-title { margin-bottom: 0px; } } &.blue { > .portlet-title { background-color: #4b8df8; } border: 1px solid #b4cef8; border-top: 0; } &.red { > .portlet-title { background-color: #e02222; } border: 1px solid #ef8476; border-top: 0; } &.yellow { > .portlet-title { background-color: #ffb848; } border: 1px solid #fccb7e; border-top: 0; } &.green { > .portlet-title { background-color: #35aa47; } border: 1px solid #77e588; border-top: 0; } &.purple { > .portlet-title { background-color: #852b99; } border: 1px solid #af5cc1; border-top: 0; } &.grey { > .portlet-title { background-color: #555555; } border: 1px solid #9d9c9c; border-top: 0; } &.light-grey { > .portlet-title { background-color: #aaa; } border: 1px solid #bbb; border-top: 0; } } } /*** Box portlet ***/ /* portlet buttons */ /*** Charts and statistics ***/ .chart, .pie, .bars { overflow: hidden; height: 300px; } /*** Statistic lists ***/ .item-list.table .percent { width: 30px; float: right; margin-right: 10px; margin-top: 3px; } /*** Chart tooltips ***/ .chart-tooltip { clear: both; z-index: 100; background-color: #736e6e !important; padding: 5px !important; color: #fff; .label { clear: both; display: block; margin-bottom: 2px; } } /*** Mini chart containers ***/ .bar-chart, .line-chart { display: none; } /*** Custom icon buttons ***/ .icon-btn { height: 60px; min-width: 80px; margin: 5px 5px 0 0; border: 1px solid #ddd; padding: 12px 0px 0px 0px; background-color: #fafafa !important; background-image: none !important; filter: none !important; -webkit-box-shadow: none !important; -moz-box-shadow: none !important; box-shadow: none !important; display: inline-block !important; color: #646464 !important; text-shadow: none !important; text-align: center; cursor: pointer; position: relative; -webkit-transition: all 0.3s ease !important; -moz-transition: all 0.3s ease !important; -ms-transition: all 0.3s ease !important; -o-transition: all 0.3s ease !important; transition: all 0.3s ease !important; i { font-size: 18px; } } .ie8 .icon-btn:hover { filter: none !important; } .icon-btn { &:hover { text-decoration: none !important; border-color: #999 !important; color: #444 !important; text-shadow: 0 1px 0px rgba(255, 255, 255, 1) !important; -webkit-transition: all 0.3s ease !important; -moz-transition: all 0.3s ease !important; -ms-transition: all 0.3s ease !important; -o-transition: all 0.3s ease !important; transition: all 0.3s ease !important; -webkit-box-shadow: none !important; -moz-box-shadow: none !important; box-shadow: none !important; .badge { -webkit-transition: all 0.3s ease !important; -moz-transition: all 0.3s ease !important; -ms-transition: all 0.3s ease !important; -o-transition: all 0.3s ease !important; transition: all 0.3s ease !important; -webkit-box-shadow: none !important; -moz-box-shadow: none !important; box-shadow: none !important; } } div { font-family: 'Open Sans', sans-serif; margin-top: 5px; margin-bottom: 20px; color: #000; font-size: 12px; font-weight: 300; } .badge { position: absolute; font-family: 'Open Sans', sans-serif; font-size: 11px !important; font-weight: 300; top: -5px; right: -5px; padding: 3px 6px 3px 6px; color: white !important; text-shadow: none; border-width: 0; border-style: solid; -webkit-border-radius: 12px !important; -moz-border-radius: 12px !important; border-radius: 12px !important; -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; } } /* extended dropdowns */ .dropdown-menu { &.extended { min-width: 160px !important; max-width: 300px !important; width: 233px !important; background-color: #ffffff !important; &:before, &:after { border-bottom-color: #ddd !important; } li { a { display: block; padding: 5px 10px !important; clear: both; font-weight: normal; line-height: 20px; white-space: normal !important; } i { margin-right: 3px; } a { font-size: 13px; padding: 10px !important; background-color: #ffffff; &:hover { background-image: none; background-color: #f5f5f5; color: #000; filter: none; } } p { padding: 10px; background-color: #eee; margin: 0px; font-size: 14px; font-weight: 300; color: #000; } a { padding: 7px 0 5px 0px; list-style: none; border-bottom: 1px solid #f4f4f4 !important; font-size: 12px; text-shadow: none; } &:first-child a { border-top: none; border-bottom: 1px solid #f4f4f4 !important; } &:last-child a { border-top: 1px solid white !important; border-bottom: 1px solid #f4f4f4 !important; } &.external > a { font-size: 13px; font-weight: 400; > i { margin-top: 3px; float: right; } } } } .dropdown-menu-list.scroller { padding-right: 0 !important; padding-left: 0; list-style: none; } &.notification li > a .time { font-size: 12px; font-weight: 600; text-align: right; font-style: italic; } &.inbox li > a { .photo { float: left; padding-right: 6px; > img { height: 40px; width: 40px; } } .subject { display: block; .from { font-size: 14px; font-weight: 400; color: #02689b; } .time { font-size: 12px; font-weight: 600; font-style: italic; position: relative; float: right; } } .message { display: block !important; font-size: 12px; } } &.tasks { .task { margin-bottom: 5px; .desc { font-size: 13px; font-weight: 300; } .percent { font-size: 14px; font-weight: 600; font-family: 'Open Sans', sans-serif; float: right; display: inline-block; } } .progress { display: block; height: 11px; margin: 0px; } } } /* header notifications dropdowns */ /* header inbox dropdowns */ /* header tasks */ /*** General list for item with image ***/ .item-list { li { .img { height: 50px; width: 50px; float: left; margin-top: 3px; margin-right: 5px; } padding: 7px 0 5px 0px; list-style: none; border-top: 1px solid white; border-bottom: 1px solid #EBEBEB; font-size: 12px; &:first-child { border-top: none; border-bottom: 1px solid #EBEBEB; } &:last-child { border-top: none; border-bottom: none; } .label { margin-right: 5px; } } margin: 0px; list-style: none; &.todo li { .label { position: absolute; right: 80px; } .actions { position: absolute; right: 45px; } } } /*** Custom tables ***/ .table-toolbar { margin-bottom: 15px; } .table { &.table-full-width { width: 100% !important; } .m-btn { margin-top: 0px; margin-left: 0px; margin-right: 5px; } thead tr th { font-size: 14px; font-weight: 600; } } .table-advance { margin-bottom: 10px !important; thead { color: #999; tr th { background-color: #DDD; font-size: 14px; font-weight: 400; color: #666; } } div { &.success, &.info, &.important, &.warning, &.danger { position: absolute; margin-top: -5px; float: left; width: 2px; height: 30px; margin-right: 20px !important; } } tr td { border-left-width: 0px; &:first-child { border-left-width: 1px !important; } &.highlight:first-child a { margin-left: 15px; } } td.highlight div { &.success { border-left: 2px solid #66ee66; } &.info { border-left: 2px solid #87ceeb; } &.important { border-left: 2px solid #f02c71; } &.warning { border-left: 2px solid #fdbb39; } &.danger { border-left: 2px solid #e23e29; } } } /*** Star rating ***/ .rating { unicode-bidi: bidi-override; direction: rtl; font-size: 30px; span.star { font-family: FontAwesome; font-weight: normal; font-style: normal; display: inline-block; &:hover { cursor: pointer; } &:before { content: "\f006"; padding-right: 5px; color: #999999; } &:hover { &:before, ~ span.star:before { content: "\f005"; color: #e3cf7a; } } } } /*** Item block with details shown on hover ***/ .item { overflow: hidden; display: block; margin-bottom: 20px; .details { width: 100%; display: none; background-color: #000; color: #fff !important; padding: 5px; text-align: center; position: relative; bottom: 30px; margin-bottom: -30px; overflow: hidden; z-index: 6; } &:hover { .details { display: block; opacity: 0.7; filter: alpha(opacity = 70); } .zoom-icon { opacity: 0.5; filter: alpha(opacity = 50); } } } /*** Zoom icon overlay on images ***/ .zoom { cursor: pointer; width: 100%; height: 100%; position: relative; z-index: 5; .zoom-icon { background-image: url("../img/overlay-icon.png"); background-color: #222; background-repeat: no-repeat; background-position: 50%; position: absolute; width: inherit; height: inherit; opacity: 0; filter: alpha(opacity = 0); z-index: 6; top: 0; } } /*** Chats ***/ .chats { margin: 0; padding: 0; margin-top: -15px; li { list-style: none; padding: 5px 0; margin: 10px auto; font-size: 12px; img.avatar { height: 45px; width: 45px; -webkit-border-radius: 50% !important; -moz-border-radius: 50% !important; border-radius: 50% !important; } &.in img.avatar { float: left; margin-right: 10px; } .name { color: #3590c1; font-size: 13px; font-weight: 400; } .datetime { color: #333; font-size: 13px; font-weight: 400; } &.out img.avatar { float: right; margin-left: 10px; } .message { display: block; padding: 5px; position: relative; } &.in .message { text-align: left; border-left: 2px solid #35aa47; margin-left: 65px; background: #fafafa; .arrow { display: block; position: absolute; top: 5px; left: -8px; width: 0; height: 0; border-top: 8px solid transparent; border-bottom: 8px solid transparent; border-right: 8px solid #35aa47; } } &.out { .message { .arrow { display: block; position: absolute; top: 5px; right: -8px; border-top: 8px solid transparent; border-bottom: 8px solid transparent; border-left: 8px solid #da4a38; } border-right: 2px solid #da4a38; margin-right: 65px; background: #fafafa; text-align: right; } .name, .datetime { text-align: right; } } .message .body { display: block; } } } .chat-form { margin-top: 15px; padding: 10px; background-color: #e9eff3; overflow: hidden; clear: both; .input-cont { margin-right: 40px; .form-control { width: 100% !important; margin-bottom: 0px; } input { border: 1px solid #ddd; width: 100% !important; margin-top: 0; background-color: #fff !important; &:focus { border: 1px solid #4b8df9 !important; } } } .btn-cont { margin-top: -42px; position: relative; float: right; width: 44px; .arrow { position: absolute; top: 17px; right: 43px; border-top: 8px solid transparent; border-bottom: 8px solid transparent; border-right: 8px solid #4d90fe; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } &:hover { .arrow { border-right-color: #0362fd; } .btn { background-color: #0362fd; } } .btn { margin-top: 8px; } } } /*** System feeds ***/ .feeds { margin: 0px; padding: 0px; list-style: none; li { background-color: #fafafa; margin-bottom: 7px; &:before { display: table; line-height: 0; content: ""; } &:after { display: table; line-height: 0; content: ""; clear: both; } &:last-child { margin-bottom: 0px; } } .col1 { float: left; width: 100%; clear: both; } .col2 { float: left; width: 75px; margin-left: -75px; } .col1 .cont { float: left; margin-right: 75px; overflow: hidden; .cont-col1 { float: left; margin-right: -100%; .label { display: inline-block; padding: 5px 4px 6px 5px; vertical-align: middle; text-align: center; > i { text-align: center; font-size: 14px; } } } .cont-col2 { float: left; width: 100%; .desc { margin-left: 35px; padding-top: 4px; padding-bottom: 5px; overflow: hidden; } } } .col2 .date { padding: 4px 9px 5px 4px; text-align: right; font-style: italic; color: #c1cbd0; } } /*** Users ***/ .user-info { margin-bottom: 10px !important; img { float: left; margin-right: 5px; } .details { display: inline-block; } .label { font-weight: 300; font-size: 11px; } } /*** Accordions ***/ .accordion-heading { background: #eee; a { text-decoration: none; &:hover { text-decoration: none; } } } /*** Vertical inline menu ***/ .ver-inline-menu { padding: 0; margin: 0; list-style: none; li { position: relative; margin-bottom: 1px; i { width: 37px; height: 37px; display: inline-block; color: #b9cbd5; font-size: 15px; padding: 12px 10px 10px 8px; margin: 0 8px 0 0; text-align: center; background: #e0eaf0 !important; } a { font-size: 13px; color: #557386; display: block; background: #f0f6fa; border-left: solid 2px #c4d5df; } &:hover { a { background: #e0eaf0; text-decoration: none; } i { background: #e0eaf0; text-decoration: none; color: #fff; background: #c4d5df !important; } } &.active a, &:hover a { font-size: 13px; } &.active { a { border-left: solid 2px #0c91e5; color: #fff; background: #169ef4; text-decoration: none; } i { color: #fff; background: #169ef4; text-decoration: none; background: #0c91e5 !important; } &:after { content: ''; display: inline-block; border-bottom: 6px solid transparent; border-top: 6px solid transparent; border-left: 6px solid #169ef4; position: absolute; top: 12px; right: -5px; } } } } /*** Custom tabs ***/ .nav-tabs > li > a > .badge, .nav-pills > li > a > .badge { margin-top: -3px; } .nav-tabs > li > a, .nav-pills > li > a { font-size: 14px; } .nav-tabs-sm > li > a, .nav-pills-sm > li > a { font-size: 13px; } .tabbable-custom { margin-bottom: 15px; padding: 0px; overflow: hidden; > { .nav-tabs { border: none; margin: 0px; } .tab-content { background-color: #fff; border: 1px solid #ddd; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; padding: 10px; } } &.nav-justified .tab-content { margin-top: -1px; } } .tabs-below.tabbable-custom.nav-justified .tab-content { margin-top: 0px; margin-bottom: -2px; } .tabbable-custom { &.boxless > .tab-content { padding: 15px 0; border-left: none; border-right: none; border-bottom: none; } .nav-tabs > li { margin-right: 2px; border-top: 2px solid transparent; > a { margin-right: 0; &:hover { background: none; border-color: transparent; } } &.active { border-top: 3px solid #d12610; margin-top: 0; position: relative; > a { border-top: none; font-weight: 400; &:hover { border-top: none; background: #fff; border-color: #d4d4d4 #d4d4d4 transparent; } } } margin-right: 2px; border-top: 2px solid transparent; } } /* below tabs */ .tabs-below.tabbable-custom .nav-tabs > li { > a { border-top: none; border-bottom: 2px solid transparent; margin-top: -1px; } &.active { border-top: none; border-bottom: 3px solid #d12610; margin-bottom: 0; position: relative; > a { border-bottom: none; &:hover { background: #fff; border-color: #d4d4d4 #d4d4d4 transparent; } } } } /*full width tabs with bigger titles */ .tabbable-custom.tabbable-full-width { > .tab-content { padding: 15px 0; border-left: none; border-right: none; border-bottom: none; } .nav-tabs > li > a { color: #424242; font-size: 15px; padding: 9px 15px; } } /*** Custom portlet tabs ***/ .portlet-tabs > { .nav-tabs { position: relative; top: -41px; margin-right: 10px; overflow: hidden; > { li { float: right; > a { color: #fff; padding-top: 8px; padding-bottom: 10px; line-height: 16px; margin-top: 6px; margin-left: 0px; margin-right: 0px; border-left: 0; border-right: 0; -webkit-border-radius: 0px; -moz-border-radius: 0px; border-radius: 0px; } &:last-child > a { border-right: 0; } margin-left: 1px; &.active { color: #333; border-top-color: transparent; > a { margin-bottom: 0px; border-bottom: 0; margin-left: 0px; margin-right: 0px; border-left: 0; border-right: 0; border-top-color: transparent !important; } } > a:hover { color: #333; margin-bottom: 0; border-bottom-color: transparent; margin-left: 0; margin-right: 0; border-left: 0; border-right: 0; border-top-color: transparent; background-color: #fff; } } .active > a { color: #555555; cursor: default; background-color: #fff; &:hover { background-color: #fff !important; } } } border-bottom: none; } .tab-content { padding: 10px !important; margin: 0px; margin-top: -50px !important; } } .portlet.tabbable .portlet-body { padding: 0px; } .tab-pane > p:last-child { margin-bottom: 0px; } /* reverse aligned tabs */ .tabs-reversed > li { float: right; margin-right: 0; > a { margin-right: 0; } } /*** Dashboard container ***/ #dashboard { overflow: hidden; } /*** Dashboard stats ***/ .dashboard-stat { margin-bottom: 25px; } .portlet .dashboard-stat:last-child { margin-bottom: 0; } .dashboard-stat { &:before { display: table; line-height: 0; content: ""; } &:after { display: table; line-height: 0; content: ""; clear: both; } .visual { width: 80px; height: 80px; display: block; float: left; padding-top: 10px; padding-left: 15px; margin-bottom: 10px; i { font-size: 65px; line-height: 65px; color: #fff; } font-size: 35px; line-height: 35px; } .details { position: absolute; right: 15px; padding-right: 10px; .number { padding-top: 15px; text-align: right; font-size: 34px; line-height: 34px; letter-spacing: -1px; margin-bottom: 5px; font-weight: 300; color: #fff; } .desc { text-align: right; font-size: 16px; letter-spacing: 0px; font-weight: 300; color: #fff; } } .more { clear: both; display: block; padding: 5px 10px 5px 10px; text-transform: uppercase; font-weight: 300; font-size: 11px; color: #fff; opacity: 0.7; filter: alpha(opacity = 70); &:hover { text-decoration: none; opacity: 1; filter: alpha(opacity = 100); } > i { display: inline-block; margin-top: 1px; float: right; } } &.blue { background-color: #27a9e3; .more { background-color: #208dbe; } } &.green { background-color: #28b779; .more { background-color: #10a062; } } &.red { background-color: #e7191b; .more { background-color: #bc0d0e; } } &.yellow { background-color: #ffb848; .more { background-color: #cb871b; } } &.purple { background-color: #852b99; .more { background-color: #6e1881; } } } @media (min-width: 992px) and (max-width: 1024px) { .dashboard-stat .visual i { font-size: 28px; line-height: 28px; } } /*** Text Stats ***/ .text-stat { h3 { margin-top: 5px; margin-bottom: 0px; font-size: 18px; } span { font-size: 12px; text-transform: uppercase; } } @media (max-width: 767px) { .text-stat { margin-top: 20px; } } /*** Tiles(new in v1.1.1) ***/ .tiles { margin-right: -10px; &:before { display: table; content: " "; } &:after { display: table; content: " "; clear: both; } } .tile { display: block; letter-spacing: 0.02em; float: left; height: 135px; width: 135px !important; cursor: pointer; text-decoration: none; color: #ffffff; position: relative; font-weight: 300; font-size: 12px; letter-spacing: 0.02em; line-height: 20px; overflow: hidden; border: 4px solid transparent; margin: 0 10px 10px 0; &:after, &:before { content: ""; float: left; } &.double { width: 280px !important; } &.double-down { height: 280px !important; } &:active, &.selected { border-color: #ccc !important; } &:hover { border-color: #aaa !important; } &.selected { .corner:after { content: ""; display: inline-block; border-left: 40px solid transparent; border-bottom: 40px solid transparent; border-right: 40px solid #ccc; position: absolute; top: -3px; right: -3px; } .check:after { content: ""; font-family: FontAwesome; font-size: 13px; content: "\f00c"; display: inline-block; position: absolute; top: 2px; right: 2px; } } * { color: #ffffff; } .tile-body { height: 100%; vertical-align: top; padding: 10px 10px; overflow: hidden; position: relative; font-weight: 400; font-size: 12px; color: #000000; color: #ffffff; margin-bottom: 10px; img { float: left; margin-right: 10px; &.pull-right { float: right !important; margin-left: 10px; margin-right: 0px; } } .content { display: inline-block; } > i { margin-top: 17px; display: block; font-size: 56px; line-height: 56px; text-align: center; } } &.double-down i { margin-top: 95px; } .tile-body { h1, h2, h3, h4, h5, h6, p { padding: 0; margin: 0; line-height: 14px; } h3, h4 { margin-bottom: 5px; } h1:hover, h2:hover, h3:hover, h4:hover, h5:hover, h6:hover { color: #ffffff; } p { &:hover { color: #ffffff; color: rgba(0, 0, 0, 0.8); } font-weight: 400; font-size: 13px; color: #000000; color: #ffffff; line-height: 20px; overflow: hidden; &:active { color: rgba(0, 0, 0, 0.4); } &:hover { color: #ffffff; } } } &.icon > .tile-body { padding: 0; } .tile-object { position: absolute; bottom: 0; left: 0; right: 0; min-height: 30px; background-color: transparent; *zoom: 1; &:before { display: table; content: ""; } &:after { display: table; content: ""; clear: both; } > { .name { position: absolute; bottom: 0; left: 0; margin-bottom: 5px; margin-left: 10px; margin-right: 15px; font-weight: 400; font-size: 13px; color: #ffffff; > i { vertical-align: middle; display: block; font-size: 24px; height: 18px; width: 24px; } } .number { position: absolute; bottom: 0; right: 0; margin-bottom: 0; color: #ffffff; text-align: center; font-weight: 600; font-size: 14px; letter-spacing: 0.01em; line-height: 14px; margin-bottom: 8px; margin-right: 10px; } } } &.image { > .tile-body { padding: 0 !important; > img { width: 100%; height: auto; min-height: 100%; max-width: 100%; } } .tile-body h3 { display: inline-block; } } } /*** Theme Panel ***/ .theme-panel { width: 400px; margin-top: -20px; margin-right: 1px; z-index: 999; float: right; position: relative; > { .toggler { top: 4px; right: 0; padding: 20px; cursor: pointer; position: absolute; background: #c9c9c9 url(../img/icon-color.png) center no-repeat; &:hover { background-color: #3d3d3d !important; } } .toggler-close { display: none; top: 4px; right: 0; padding: 20px; cursor: pointer; position: absolute; background: #3d3d3d url(../img/icon-color-close.png) center no-repeat !important; &:hover { background-color: #222 !important; } } .theme-options { top: 4px; right: 40px; display: none; position: absolute; background: #3d3d3d; > .theme-option { color: #cfcfcf; padding: 15px; border-top: 1px solid #585858; margin-top: 0px; margin-bottom: 0px; &.theme-colors { border-top: 0; > span { display: block; width: auto; } > ul { list-style: none; padding: 0; display: block; margin-bottom: 1px !important; margin-top: 10px; > li { width: 37px; height: 37px; margin: 0 4px; cursor: pointer; list-style: none; float: left; border: solid 1px #707070; &:first-child { margin-left: 0; } &:hover, &.current { border: solid 2px #ebebeb; } &.color-black { background: #333438; } &.color-grey { background: #6d6d6d; } &.color-blue { background: #124f94; } &.color-brown { background: #623f18; } &.color-purple { background: #701584; } &.color-white { background: #fff; } &.color-fantasy { background: #525A68; } } } } > span { text-transform: uppercase; display: inline-block; width: 138px; font-size: 14px; } > select.form-control { display: inline; width: 100px; text-transform: lowercase; } } } } } /*** Top bar menu ***/ /* enable arrow for dropdown menu */ .header .nav > li > .dropdown-menu { &:before { position: absolute; top: -7px; right: 9px; display: inline-block !important; border-right: 7px solid transparent; border-bottom: 7px solid #ccc; border-left: 7px solid transparent; border-bottom-color: rgba(0, 0, 0, 0.2); content: ''; } &:after { position: absolute; top: -6px; right: 10px; display: inline-block !important; border-right: 6px solid transparent; border-bottom: 6px solid #fff; border-left: 6px solid transparent; content: ''; } } /*** Mega Menu(new in v1.6) ***/ .mega-menu { .nav, .collapse, .mega-menu-dropup, .mega-menu-dropdown { position: static; } .container { position: relative; } .mega-menu-dropdown .dropdown-menu { left: auto; width: auto; } .nav.navbar-right .dropdown-menu { left: auto; right: 0; } .mega-menu-content { padding: 10px; margin: 0; } .mega-menu-full .dropdown-menu { left: 20px; right: 20px; } } .mega-menu-responsive-content { padding: 10px 15px 10px 60px; } .page-boxed .mega-menu .mega-menu-dropdown { .dropdown-menu { top: 42px; } &.mega-menu-full .dropdown-menu { margin: 0; padding: 0; left: 18px; right: 18px; } } .mega-menu .mega-menu-submenu { width: auto !important; padding: 0px 15px !important; margin: 0 !important; &:last-child { border-right: 0; } li { > { h3 { font-size: 14px; margin-top: 10px; padding-left: 5px; } a { padding: 5px !important; margin: 0 !important; } } padding: 2px !important; margin: 0 !important; list-style: none; } } /*** Horezantal Menu(new in v1.2) ***/ .header .hor-menu { margin: 0; float: left; ul.nav li { > a { font-size: 14px; padding: 11px 10px; } &.current .selected, &.active .selected { left: 50%; bottom: 0; position: absolute; border-left: 6px solid transparent; border-right: 6px solid transparent; border-top: 6px solid #e02222; display: inline-block; margin: 0; width: 0px; height: 0px; margin-left: -7px; margin-bottom: -6px; } } .dropdown-menu { margin-top: 0; border: none; box-shadow: none; } .classic-menu-dropdown { .dropdown-submenu > { .dropdown-menu { top: 0; } a:after { top: 8px; margin-right: 0px; } } .dropdown-menu { li > a { padding: 7px 18px !important; margin-bottom: 1px; } .arrow { display: none; } li { > a:hover, &:hover > a, &.active > a { filter: none !important; } } } } .nav > li > .dropdown-menu { &:after, &:before { border-bottom: none !important; } } .hor-menu-search-form-toggler { display: inline-block; padding: 12px 22px 12px 22px !important; cursor: pointer; background: url(../img/hor-menu-search.png) no-repeat center; &:hover { opacity: 0.8; filter: alpha(opacity = 80); } } a.hor-menu-search-form-toggler-close { display: none; } .search-form { margin: 0; top: 42px; right: 0px; padding: 0 4px; display: none; z-index: 999; position: absolute; .btn { padding: 7px 20px; height: 32px; width: 10px; display: inline-block; &:hover { opacity: 0.8; filter: alpha(opacity = 80); } } form { margin-bottom: 0; input { background: none; width: 200px; border: none; margin-top: 6px; } } } } /*drop-down*/ /*search*/ /*** Top News Blocks(new in v1.2.2) ***/ .top-news { color: #fff; margin: 8px 0; a, em, span { display: block; text-align: left; } a { padding: 10px; position: relative; margin-bottom: 10px; .top-news-icon { right: 8px; bottom: 15px; opacity: 0.3; font-size: 35px; position: absolute; filter: alpha(opacity = 30); /*For IE8*/ } } em { margin-bottom: 0; font-style: normal; } span { font-size: 18px; margin-bottom: 5px; } } /*** Block Images(new in v1.2.2) ***/ .blog-images { margin-bottom: 0; li { padding: 0; margin: 0; display: inline; a:hover { text-decoration: none; } img { width: 50px; height: 50px; opacity: 0.6; margin: 0 2px 8px; &:hover { opacity: 1; box-shadow: 0 0 0 4px #72c02c; transition: all 0.4s ease-in-out 0s; -moz-transition: all 0.4s ease-in-out 0s; -webkit-transition: all 0.4s ease-in-out 0s; } } } } /*Sidebar Tags*/ ul.sidebar-tags { a { color: #555; font-size: 12px; padding: 3px 5px; background: #f7f7f7; margin: 0 2px 5px 0; display: inline-block; &:hover { background: #EEE; text-decoration: none; -webkit-transition: all 0.3s ease-in-out; -moz-transition: all 0.3s ease-in-out; -o-transition: all 0.3s ease-in-out; transition: all 0.3s ease-in-out; i { background: #EEE; text-decoration: none; -webkit-transition: all 0.3s ease-in-out; -moz-transition: all 0.3s ease-in-out; -o-transition: all 0.3s ease-in-out; transition: all 0.3s ease-in-out; } } i { color: #777; } } li { padding: 0; } } /*** Social Icons(new in v1.2.2) ***/ .social-icons { padding: 0; margin: 0; &:after, &:before { content: ""; display: table; } &:after { clear: both; } li { float: left; display: inline; list-style: none; margin-right: 5px; margin-bottom: 5px; text-indent: -9999px; a { width: 28px; height: 28px; display: block; background-position: 0 0; background-repeat: no-repeat; transition: all 0.3s ease-in-out; -o-transition: all 0.3s ease-in-out; -ms-transition: all 0.3s ease-in-out; -moz-transition: all 0.3s ease-in-out; -webkit-transition: all 0.3s ease-in-out; } } } a.social-icon { width: 28px; height: 28px; display: block; background-position: 0 0; background-repeat: no-repeat; transition: all 0.3s ease-in-out; -o-transition: all 0.3s ease-in-out; -ms-transition: all 0.3s ease-in-out; -moz-transition: all 0.3s ease-in-out; -webkit-transition: all 0.3s ease-in-out; } .social-icons li:hover a { background-position: 0 -38px; } .social-icons-color li a { opacity: 0.7; background-position: 0 -38px !important; &:hover { opacity: 1; } } .social-icons { .amazon { background: url(../img/social/amazon.png) no-repeat; } .behance { background: url(../img/social/behance.png) no-repeat; } .blogger { background: url(../img/social/blogger.png) no-repeat; } .deviantart { background: url(../img/social/deviantart.png) no-repeat; } .dribbble { background: url(../img/social/dribbble.png) no-repeat; } .dropbox { background: url(../img/social/dropbox.png) no-repeat; } .evernote { background: url(../img/social/evernote.png) no-repeat; } .facebook { background: url(../img/social/facebook.png) no-repeat; } .forrst { background: url(../img/social/forrst.png) no-repeat; } .github { background: url(../img/social/github.png) no-repeat; } .googleplus { background: url(../img/social/googleplus.png) no-repeat; } .jolicloud { background: url(../img/social/jolicloud.png) no-repeat; } .last-fm { background: url(../img/social/last-fm.png) no-repeat; } .linkedin { background: url(../img/social/linkedin.png) no-repeat; } .picasa { background: url(../img/social/picasa.png) no-repeat; } .pintrest { background: url(../img/social/pintrest.png) no-repeat; } .rss { background: url(../img/social/rss.png) no-repeat; } .skype { background: url(../img/social/skype.png) no-repeat; } .spotify { background: url(../img/social/spotify.png) no-repeat; } .stumbleupon { background: url(../img/social/stumbleupon.png) no-repeat; } .tumblr { background: url(../img/social/tumblr.png) no-repeat; } .twitter { background: url(../img/social/twitter.png) no-repeat; } .vimeo { background: url(../img/social/vimeo.png) no-repeat; } .wordpress { background: url(../img/social/wordpress.png) no-repeat; } .xing { background: url(../img/social/xing.png) no-repeat; } .yahoo { background: url(../img/social/yahoo.png) no-repeat; } .youtube { background: url(../img/social/youtube.png) no-repeat; } .vk { background: url(../img/social/vk.png) no-repeat; } .instagram { background: url(../img/social/instagram.png) no-repeat; } .reddit { background: url(../img/social/reddit.png) no-repeat; } .aboutme { background: url(../img/social/aboutme.png) no-repeat; } .flickr { background: url(../img/social/flickr.png) no-repeat; } .foursquare { background: url(../img/social/foursquare.png) no-repeat; } .gravatar { background: url(../img/social/gravatar.png) no-repeat; } .klout { background: url(../img/social/klout.png) no-repeat; } .myspace { background: url(../img/social/myspace.png) no-repeat; } .quora { background: url(../img/social/quora.png) no-repeat; } } /*** Inline Social Icons ***/ .social-icon { display: inline-block !important; width: 28px; height: 28px; background-position: 0 0; background-repeat: no-repeat; transition: all 0.3s ease-in-out; -o-transition: all 0.3s ease-in-out; -ms-transition: all 0.3s ease-in-out; -moz-transition: all 0.3s ease-in-out; -webkit-transition: all 0.3s ease-in-out; &.amazon { background: url(../img/social/amazon.png) no-repeat; } &.behance { background: url(../img/social/behance.png) no-repeat; } &.blogger { background: url(../img/social/blogger.png) no-repeat; } &.deviantart { background: url(../img/social/deviantart.png) no-repeat; } &.dribbble { background: url(../img/social/dribbble.png) no-repeat; } &.dropbox { background: url(../img/social/dropbox.png) no-repeat; } &.evernote { background: url(../img/social/evernote.png) no-repeat; } &.facebook { background: url(../img/social/facebook.png) no-repeat; } &.forrst { background: url(../img/social/forrst.png) no-repeat; } &.github { background: url(../img/social/github.png) no-repeat; } &.googleplus { background: url(../img/social/googleplus.png) no-repeat; } &.jolicloud { background: url(../img/social/jolicloud.png) no-repeat; } &.last-fm { background: url(../img/social/last-fm.png) no-repeat; } &.linkedin { background: url(../img/social/linkedin.png) no-repeat; } &.picasa { background: url(../img/social/picasa.png) no-repeat; } &.pintrest { background: url(../img/social/pintrest.png) no-repeat; } &.rss { background: url(../img/social/rss.png) no-repeat; } &.skype { background: url(../img/social/skype.png) no-repeat; } &.spotify { background: url(../img/social/spotify.png) no-repeat; } &.stumbleupon { background: url(../img/social/stumbleupon.png) no-repeat; } &.tumblr { background: url(../img/social/tumblr.png) no-repeat; } &.twitter { background: url(../img/social/twitter.png) no-repeat; } &.vimeo { background: url(../img/social/vimeo.png) no-repeat; } &.wordpress { background: url(../img/social/wordpress.png) no-repeat; } &.xing { background: url(../img/social/xing.png) no-repeat; } &.yahoo { background: url(../img/social/yahoo.png) no-repeat; } &.youtube { background: url(../img/social/youtube.png) no-repeat; } &.vk { background: url(../img/social/vk.png) no-repeat; } &.instagram { background: url(../img/social/instagram.png) no-repeat; } &.reddit { background: url(../img/social/reddit.png) no-repeat; } &.aboutme { background: url(../img/social/aboutme.png) no-repeat; } &.flickr { background: url(../img/social/flickr.png) no-repeat; } &.foursquare { background: url(../img/social/foursquare.png) no-repeat; } &.gravatar { background: url(../img/social/gravatar.png) no-repeat; } &.klout { background: url(../img/social/klout.png) no-repeat; } &.myspace { background: url(../img/social/myspace.png) no-repeat; } &.quora { background: url(../img/social/quora.png) no-repeat; } &:hover { background-position: 0 -38px; } } .social-icon-color { opacity: 0.7; background-position: 0 -38px !important; &:hover { opacity: 1; } } /*** Notes ***/ /* Common styles for all types */ .note { margin: 0 0 20px 0; padding: 15px 30px 15px 15px; border-left: 5px solid #eee; h1, h2, h3, h4 { margin-top: 0; } p:last-child { margin-bottom: 0; } code, .highlight { background-color: #fff; } } /* Variations */ .note-danger { background-color: #FAEAE6; border-color: #ed4e2a; } .note-warning { background-color: #FCF3E1; border-color: #fcb322; } .note-info { background-color: #E8F6FC; border-color: #57b5e3; } .note-success { background-color: #EBFCEE; border-color: #3cc051; } /*** Demo Utils ***/ .scrollspy-example { position: relative; height: 200px; margin-top: 10px; overflow: auto; } .util-btn-margin-bottom-5 .btn, .util-btn-group-margin-bottom-5 .btn-group { margin-bottom: 5px !important; } .fontawesome-demo { i { font-size: 18px; } li { padding-top: 5px; padding-bottom: 5px; } } .glyphicons-demo ul, .bs-glyphicons { padding-left: 0; padding-bottom: 1px; margin-bottom: 20px; list-style: none; overflow: hidden; } .glyphicons-demo { ul li { float: left; width: 25%; height: 115px; padding: 10px; margin: 0 -1px -1px 0; font-size: 12px; line-height: 1.4; text-align: center; border: 1px solid #ddd; } .glyphicon { display: block; margin: 5px auto 10px; font-size: 24px; } ul li:hover { background-color: rgba(86, 61, 124, 0.1); } } @media (min-width: 768px) { .glyphicons-demo ul li { width: 12.5%; } } /*** Forms ****/ .static-info { margin-bottom: 10px; .name { font-size: 14px; } .value { font-size: 14px; font-weight: 600; } &.align-reverse { .name, .value { text-align: right; } } } input.placeholder, textarea.placeholder { color: #aaa !important; } .help-block { margin-top: 5px; margin-bottom: 5px; } .form-inline input { margin-bottom: 0px !important; } .control-label { margin-top: 2px; } .form-control-static { font-size: 14px; padding-top: 7px; } .control-label .required { color: #e02222; font-size: 12px; padding-left: 2px; } .switch-wrapper { display: inline-block; } .form { padding: 0 !important; } .form-body { padding: 10px; } .form-actions { padding: 20px 10px; margin-top: 20px; background-color: #f5f5f5; border-top: 1px solid #e5e5e5; *zoom: 1; &.nobg { background-color: transparent; } &.top { margin-top: 0; margin-bottom: 20px; border-top: 0; border-bottom: 1px solid #e5e5e5; } &.fluid { padding: 20px 0; > [class^="col-"] { padding-left: 13px; } } &:before { display: table; line-height: 0; content: ""; } &:after { display: table; line-height: 0; content: ""; clear: both; } } .form-section { margin: 30px 0px 25px 0px; padding-bottom: 5px; border-bottom: 1px solid #eee; } .form .form-section:first-child { margin-top: 5px; } .help-inline { font-size: 13px; color: #737373; display: inline-block; padding: 5px; } /* left, right aligned form actions */ .form-actions { &.right { padding-left: 0; padding-right: 10px; text-align: right; } &.left { padding-left: 10px; padding-right: 0; text-align: left; } } /* Checkboxes */ .form-group .checkbox { padding-left: 0; } .checkbox-list > label, .radio-list > label { display: block; &.checkbox-inline, &.radio-inline { display: inline-block; &:first-child { padding-left: 0; } } } /* Radios */ .form-horizontal { .radio-list { .radio { padding-top: 1px; } > label { margin-bottom: 0; } } .radio > span { margin-top: 2px; } } /* Rows seperated form layout */ .form-row-seperated { .form-group { margin: 0; border-bottom: 1px solid #efefef; padding: 10px 0px 10px 0px; &.last { border-bottom: 0; margin-bottom: 0; padding-bottom: 10px; } } .form-actions { margin-top: 0; } .form-body { padding: 0; margin-top: 0; } .help-block { margin-bottom: 0; } } /* form bordered */ .form-bordered { .form-body { margin: 0; padding: 0; } .form-actions { margin-top: 0; } .form-group { margin: 0; border-bottom: 1px solid #efefef; &.last { border-bottom: 0; } } .help-block { margin-bottom: 0; } .control-label { padding-top: 16px; } .form-group > div { padding: 10px; border-left: 1px solid #efefef; } .form-actions.fluid > .row > div { padding-left: 10px; } } .form-horizontal.form-bordered { &.form-row-stripped .form-group:nth-child(even), &.form-label-stripped .form-group:nth-child(even) { background-color: #fcfcfc; } &.form-row-stripped .form-control { background: #fff !important; } &.form-label-stripped .form-group:nth-child(even) > div { background-color: #ffffff; } } /*** Bordered form layout ***/ .form-bordered .form-control { margin: 0; } /*** Disabled Menu Link ***/ .disabled-link > a { > span { &.text, &.title { font-style: italic !important; color: #888 !important; } } &:hover { cursor: not-allowed !important; } } /*** Responsive & Scrollable Tables ***/ .table-scrollable { width: 100%; overflow-x: auto; overflow-y: hidden; border: 1px solid #dddddd; margin: 10px 0 !important; > { .table { width: 100% !important; margin: 0 !important; margin-bottom: 0; background-color: #fff; > { thead > tr > th, tbody > tr > th, tfoot > tr > th, thead > tr > td, tbody > tr > td, tfoot > tr > td { white-space: nowrap; } } } .table-bordered { border: 0; > { thead > tr > th:first-child, tbody > tr > th:first-child, tfoot > tr > th:first-child, thead > tr > td:first-child, tbody > tr > td:first-child, tfoot > tr > td:first-child { border-left: 0; } thead > tr > th:last-child, tbody > tr > th:last-child, tfoot > tr > th:last-child, thead > tr > td:last-child, tbody > tr > td:last-child, tfoot > tr > td:last-child { border-right: 0; } thead > tr:last-child > th, tbody > tr:last-child > th, tfoot > tr:last-child > th, thead > tr:last-child > td, tbody > tr:last-child > td, tfoot > tr:last-child > td { border-bottom: 0; } } } } } /*** Responsive Flip Scroll Tables ***/ .flip-scroll table { width: 100%; } @media only screen and (max-width: 768px) { .flip-scroll { .flip-content:after { visibility: hidden; display: block; font-size: 0; content: " "; clear: both; height: 0; } * { html .flip-content, &:first-child + html .flip-content { zoom: 1; } } table { width: 100%; border-collapse: collapse; border-spacing: 0; } th, td { margin: 0; vertical-align: top; } th { text-align: left; border: 0 !important; border-bottom: 1px solid #ddd !important; border-right: 1px solid #ddd !important; font-size: 13px !important; padding: 5px; width: auto !important; } table { display: block; position: relative; width: 100%; } thead { display: block; float: left; } tbody { display: block; width: auto; position: relative; overflow-x: auto; white-space: nowrap; } thead tr { display: block; } th { display: block; text-align: right; } tbody tr { display: inline-block; vertical-align: top; margin-left: -5px; } td { display: block; min-height: 1.25em; text-align: left; border-top: 0 !important; border-left: 0 !important; border-right: 0 !important; } th { border-bottom: 0; border-left: 0; } td { border-left: 0; border-right: 0; border-bottom: 0; } tbody tr { border-left: 1px solid #ddd; } th:last-child, td:last-child { border-bottom: 1px solid #ddd; } } /* sort out borders */ } /*** UI Loading ***/ .loading-message { display: inline-block; min-width: 125px; padding: 10px; margin: 0 auto; color: #000 !important; font-size: 13px; font-weight: 400; text-align: center; vertical-align: middle; span { line-height: 20px; vertical-align: middle; } &.loading-message-boxed { border: 1px solid #ddd; background-color: #eee; -webkit-box-shadow: 0 1px 8px rgba(0, 0, 0, 0.1); -moz-box-shadow: 0 1px 8px rgba(0, 0, 0, 0.1); box-shadow: 0 1px 8px rgba(0, 0, 0, 0.1); } } .page-loading { position: fixed; top: 50%; left: 50%; min-width: 125px; margin-left: -50px; margin-top: -30px; padding: 7px; text-align: center; color: #333; font-size: 13px; border: 1px solid #ddd; background-color: #eee; vertical-align: middle; -webkit-box-shadow: 0 1px 8px rgba(0, 0, 0, 0.1); -moz-box-shadow: 0 1px 8px rgba(0, 0, 0, 0.1); box-shadow: 0 1px 8px rgba(0, 0, 0, 0.1); span { line-height: 20px; vertical-align: middle; } }
<template> <div> <PageContent :deltaHeight='pageContentDeltaHeight'> <div class="container pt-3 pt-sm-5 mb-3"> <h1>Upload Supporting Documents</h1> <hr class="mt-0"/> <div class="row"> <div class="col-md-8"> <div> <p class="font-weight-bold">Upload your Canada Revenue Agency Notice of Assessment or Reassessment for 2020</p> <hr/> <FileUploader v-model="ahCRADocuments" /> </div> <div v-if="hasSpouse"> <p class="font-weight-bold">Upload your spouse's Canada Revenue Agency Notice of Assessment or Reassessment for 2020</p> <hr/> <FileUploader v-model="spouseCRADocuments" /> </div> </div> <div class="col-md-4"> <TipBox title="Tip"> <p> If you are uploading a copy of a Notice of Assessment of Reassessment from the Canada Revenue Agency website, make sure the image contains: </p> <ul> <li>Your Name</li> <li>The Tax Year</li> <li>Your Net Income(line 23600)</li> <li>If you have a Regisered Disability Savings Plan(line 12500)</li> <li>A JPG, PNG, GIF, BMP, or PDF file.</li> </ul> </TipBox> </div> </div> </div> </PageContent> <ContinueBar @continue="validateFields()" /> </div> </template> <script> import pageStateService from '@/services/page-state-service'; import { enrolmentRoutes, isPastPath, } from '@/router/routes'; import { scrollTo, scrollToError, getTopScrollPosition } from '@/helpers/scroll'; import { getConvertedPath, } from '@/helpers/url'; import { MODULE_NAME as enrolmentModule, RESET_FORM, SET_AH_CRA_DOCUMENTS, SET_SPOUSE_CRA_DOCUMENTS, } from '@/store/modules/enrolment-module'; import logService from '@/services/log-service'; import { ContinueBar, PageContent, FileUploader, } from 'common-lib-vue'; import pageContentMixin from '@/mixins/page-content-mixin'; import TipBox from '@/components/TipBox'; export default { name: 'DocumentsPage', mixins: [pageContentMixin], components: { ContinueBar, PageContent, FileUploader, TipBox, }, data: () => { return { ahCRADocuments: [], spouseCRADocuments: [], hasSpouse: false, }; }, created() { logService.logNavigation( this.$store.state.enrolmentModule.applicationUuid, enrolmentRoutes.DOCUMENTS_PAGE.path, enrolmentRoutes.DOCUMENTS_PAGE.title ); this.ahCRADocuments = this.$store.state.enrolmentModule.ahCRADocuments; this.spouseCRADocuments = this.$store.state.enrolmentModule.spouseCRADocuments; this.hasSpouse = this.$store.state.enrolmentModule.hasSpouse !== 'N'; }, validations() { const validations = {}; return validations; }, methods: { validateFields() { this.$v.$touch() if (this.$v.$invalid) { scrollToError(); return; } this.$store.dispatch(`${enrolmentModule}/${SET_AH_CRA_DOCUMENTS}`, this.ahCRADocuments); if (this.hasSpouse) { this.$store.dispatch(`${enrolmentModule}/${SET_SPOUSE_CRA_DOCUMENTS}`, this.spouseCRADocuments); } this.navigateToNextPage(); }, navigateToNextPage() { // Navigate to next path. const toPath = getConvertedPath( this.$router.currentRoute.path, enrolmentRoutes.CONTACT_INFO_PAGE.path ); pageStateService.setPageComplete(toPath); pageStateService.visitPage(toPath); this.$router.push(toPath); scrollTo(0); }, }, computed: {}, // Required in order to block back navigation. beforeRouteLeave(to, from, next) { pageStateService.setPageIncomplete(from.path); if (to.path === enrolmentRoutes.HOME_PAGE.path) { this.$store.dispatch(enrolmentModule + '/' + RESET_FORM); next(); } else if ((pageStateService.isPageComplete(to.path)) || isPastPath(to.path, from.path)) { next(); } else { // Navigate to self. const topScrollPosition = getTopScrollPosition(); const toPath = getConvertedPath( this.$router.currentRoute.path, enrolmentRoutes.DOCUMENTS_PAGE.path ); next({ path: toPath, replace: true }); setTimeout(() => { scrollTo(topScrollPosition); }, 0); } } } </script> <style scoped> </style>
-- 1) 查询累计人流量大于30的地点名称和累计人流量,累积人流量请用visitors作标题名称。 -- 查询结果按照人流量从高到低排序,人流量相同时,依地点名称的字典顺序排序。 -- (注意:同一人多次逛同一地点,去几次算几次) -- 请用一条SQL语句实现该查询: select * from ( select location_name,count(loc_id) as visitors from location,itinerary where location.id = itinerary.loc_id group by location.id having count(loc_id)>30 ) tmp order by visitors desc,location_name; -- 2) 查询每个隔离地及该地正在进行隔离的人数,以number为隔离人数的标题. -- 查询结果依隔离人数由多到少排序。人数相同时,依隔离地点名排序。 -- 请用一条SQL语句实现该查询: select * from( select location_name,count(p_id) as number from isolation_record,isolation_location where isolation_location.id = isolation_record.isol_loc_id and state = 1 group by isolation_location.id ) tmp order by number desc,location_name; -- 3) 查询行程表中所有属于同一个人的接续行程信息。输出内容包括: -- 人员编号,姓名,重合时间,起始地点id,起始地点,结束地点id,结束地点。 -- 查询结果依人员编号排序。 -- 请用一条SQL语句实现该查询: select person.id, person.fullname, person.telephone, t1.e_time as reclosing_time, t1.loc_id as loc1, l1.location_name as address1, t2.loc_id as loc2, l2.location_name as address2 from person, location l1, location l2, itinerary t1, itinerary t2 where person.id > 30 and person.id = t1.p_id and l1.id = t1.loc_id and l2.id = t2.loc_id and t1.p_id = t2.p_id and t1.e_time = t2.s_time order by person.id, reclosing_time; -- 4) 查询充珉瑶和贾涵山的行程情况。查询结果包括:姓名、电话、到过什么地方(地名),何时到达,何时离开 。 -- 列名原样列出,不必用别名。查询结果依人员编号降序排序。 select a.fullname,a.telephone,tmp.location_name,tmp.s_time,tmp.e_time from person a left join( select b.fullname,location.location_name,s_time,e_time from person b,location,itinerary where b.id = itinerary.p_id and itinerary.loc_id = location.id ) tmp on a.fullname = tmp.fullname where a.fullname in ("充珉瑶","贾涵山") order by a.id desc,s_time; -- 5) 查询地名中带有‘店’字的地点编号和名称。查询结果按地点编号排序。 -- 请用一条SQL语句实现该查询: select id, location_name from location where location_name like "%店%" order by id; -- 6) 新发现一位确诊者,已知他在2021.2.2日20:05:40到21:25:40之间在“活动中心”逗留, -- 凡在此间在同一地点逗留过的,视为接触者,请查询接触者的姓名和电话。查询结果按姓名排序. -- 请用一条SQL语句实现该查询: select fullname, telephone from person, itinerary, location where person.id = itinerary.p_id and itinerary.loc_id = location.id and location_name = "活动中心" and (itinerary.s_time between "2021-02-02 20:05:40" and "2021-02-02 21:25:40" or itinerary.e_time between "2021-02-02 20:05:40" and "2021-02-02 21:25:40" or "2021-02-02 20:05:40" between itinerary.s_time and itinerary.e_time) order by fullname; -- 7) 查询正在使用的隔离点名,查询结果按隔离点的编号排序。 -- 请用一条SQL语句实现该查询: # 查询仍在使用的隔离点名称。注意,隔离记录里如果只有隔离结束或确诊转院的记录, # 表明该隔离点已暂时停用,只要还有一个人在此处隔离, # 表明该隔离点仍在使用。查询结果按隔离点编号排序。 select location_name from isolation_location where exists( select * from isolation_record where isolation_location.id = isolation_record.isol_loc_id and state = 1 ) order by id; -- 8) 用一条带exists关键字的SQL语句查询前30位有出行记录的人员姓名和电话。查询结果按照人员编号排序。 -- 请用一条SQL语句实现该查询: select fullname, telephone from person where exists( select * from itinerary where person.id = itinerary.p_id ) order by person.id limit 30 ; -- 9) 写一条带NOT EXISTS 子查询的SQL语句实现下述查询要求: -- 查询人员表中没有去过地点“Today便利店”的人数。请给统计出的人数命名为number。 -- 请用一条SQL语句实现该查询: select count(person.id) as number from person where not exists( select * from itinerary, location where person.id = itinerary.p_id and itinerary.loc_id = location.id and location.location_name = "Today便利店" ); -- 10) 查询人员表中去过所有地点的人员姓名。查询结果依人员姓名的字典顺序排序。 -- 请用一条SQL语句实现该查询: select fullname from person where not exists( select * from location where location.id not in ( select itinerary.loc_id from itinerary where itinerary.loc_id = location.id and person.id = itinerary.p_id ) ) order by fullname; -- 11) 建立反映所有隔离点现状的视图isolation_location_status。 -- 内容包括:地点编号,隔离地点名,房间容量,已占用量 -- 请保持原列名不变,已占用量由统计函籹计算得出,该列命名为occupied。 -- 正在隔离的人占用着隔离点的位置,隔离结束或已转院的人不占用位置。 create view isolation_location_status as select l.id, l.location_name, l.capacity, ifnull(tmp.cut, 0) as occupied from isolation_location l left join ( select r.isol_loc_id, count(r.isol_loc_id) as cut from isolation_record r where r.state = 1 group by r.isol_loc_id ) tmp on l.id = tmp.isol_loc_id; -- 12) 从视图isolation_location_status中查询各隔离点的剩余空房间的数目。 -- 需要列出的数据项:隔离点名称,剩余房间数。其中剩余房间数为计算得出,请给该列命名为available_rooms -- 查询结果依隔离点编号排序。 -- 请用一条SQL语句实现该查询: select location_name, capacity - occupied as available_rooms from isolation_location_status order by id; -- 13) 筛查发现,靳宛儿为无症状感染者。现需查询其接触者姓名名单和电话,以便通知并安排隔离。查询结题按姓名排序。 -- 凡行程表中,在同一地点逗留时间与靳宛儿有交集的,均视为接触者。 -- 请用一条SQL语句实现该查询: select fullname, telephone from person, itinerary, ( select i.loc_id, i.s_time, i.e_time from person p, itinerary i where p.id = i.p_id and p.fullname = "靳宛儿" ) tmp where person.fullname <> "靳宛儿" and person.id = itinerary.p_id and itinerary.loc_id = tmp.loc_id and ( itinerary.s_time between tmp.s_time and tmp.e_time or itinerary.e_time between tmp.s_time and tmp.e_time or tmp.s_time between itinerary.s_time and itinerary.e_time or tmp.e_time between itinerary.s_time and itinerary.e_time ) order by fullname; -- 14) 依据密切接触表的内容查询每个地点的密切接触者的数量,列出内容包括:地点名称,密接者人数。 -- 人数由统计获得,列名命名为close_contact_number.查询结果依密接者人数降序排列。 -- 密接者人数相同时,依地点名称排序。 -- 请用一条SQL语句实现该查询: select * from ( select location_name, count(loc_id) as close_contact_number from location, close_contact where location.id = close_contact.loc_id group by close_contact.loc_id ) tmp order by close_contact_number desc, location_name; -- 15) 查询感染人数最多的人员编号,姓名,和被其感染的人数。 -- 感染人数由统计所得,命名为infected_number. -- 请用一条SQL语句实现该查询: select case_p_id, fullname, count(case_p_id) as infected_number from close_contact, person where person.id = close_contact.case_p_id group by case_p_id order by infected_number desc limit 1; -- 16) 查询2021-02-02 10:00:00到14:00:00期间,行程记录最频繁的3个人的姓名及行程记录条数。 -- 记录条数命名为record_number. 记录数并列的,按姓名顺序排列。 -- 请用一条SQL语句实现该查询: select * from ( select fullname, count(p_id) as record_number from person, itinerary where person.id = itinerary.p_id and (itinerary.s_time between "2021-02-02 10:00:00" and "2021-02-02 14:00:00" or itinerary.e_time between "2021-02-02 10:00:00" and "2021-02-02 14:00:00" or "2021-02-02 10:00:00" between itinerary.s_time and itinerary.e_time) group by itinerary.p_id) tmp order by record_number desc, fullname limit 3; -- 17 查询隔离点中,房间数第二多的隔离点名称和房间数。 -- 请用一条SQL语句实现该查询: select location_name, capacity from isolation_location where capacity = (select distinct capacity from isolation_location order by capacity desc limit 1,1);
s3 = session.resource('s3') s3_client = session.client('s3') bucket = s3.Bucket('cis4130projectcz') # getting all files file_paths = [x.key for x in bucket.objects.all()] del file_paths[0] # getting file year df_years = {} for file in file_paths: year = file.split("_")[3] if year not in df_years: df_years[year] = [file] else: df_years[year].append(file) obj=s3_client.get_object(Bucket=bucket._name,Key=file) # establishing library of dtypes instead of setting low_memory=false dtype = { 'unique_key': int, 'created_date': object, 'complaint_type': object, 'incident_zip': object, 'borough': object } # setting up specific columns required_columns = ['unique_key','created_date','complaint_type','incident_zip','city','borough'] def load_dataframe(file): obj = s3_client.get_object(Bucket=bucket._name, Key=file) return pd.read_csv(obj['Body'], usecols=required_columns, dtype = dtype) # spreading the operation across multiple threads for faster processing def consolidate_yearly_records(files): executor = concurrent.futures.ThreadPoolExecutor() year_dfs = list(executor.map(load_dataframe, files)) return pd.concat(year_dfs, ignore_index=True) service_years = ['2010','2011','2012','2013','2014','2015','2016','2017','2018','2019','2020','2021','2022'] # performing exploratory data analysis and printing the results for x in service_years: df = consolidate_yearly_records(df_years[x]) number_of_requests = df['unique_key'].count() rows = list(df.shape)[0] columns = list(df.shape)[1] column_names = list(df.columns) min_date = df['created_date'].min() max_date = df['created_date'].max() null_values = df.isnull().sum() print(f"Here is all the info for {x}!\nTotal number of service requests: {number_of_requests} \nTotal number of rows: {rows}\nTotal number of columns: {columns}\nThe column names are: {column_names}\nThe earliest date is: {min_date}\nThe latest date is: {max_date} \nTotal number of missing values in each column:\n{null_values}")
package com.study.leetcode201_300.LeetCode251_275; public class LeetCode268 { public static void main(String[] args) { } /** * 辅助空间 * * @param nums * @return */ public int missingNumber1(int[] nums) { int[] result = new int[nums.length + 1]; for (int num : nums) { result[num] = 1; } for (int i = 0; i < result.length; i++) { if (result[i] == 0) { return i; } } return 0; } public int missingNumber2(int[] nums) { for (int i = 0; i < nums.length; i++) { int temp = 0; while (nums[i] != nums.length && nums[i] != i) { temp = nums[nums[i]]; nums[nums[i]] = nums[i]; nums[i] = temp; } } for (int i = 0; i < nums.length; i++) { if (i != nums[i]) { return i; } } return nums.length; } /** * 位运算 * * @param nums * @return */ public int missingNumber3(int[] nums) { int xor = 0; for (int num : nums) { xor ^= num; } for (int i = 0; i <= nums.length; i++) { xor ^= i; } return xor; } /** * 数学求和 * * @param nums * @return */ public int missingNumber(int[] nums) { int n = nums.length; int total = n * (n + 1) / 2; int arrSum = 0; for (int num : nums) { arrSum += num; } return total - arrSum; } }
<!-- 會員註冊頁面 --> <section class="container"> <!-- Bulma的container會有一點margin空間 --> <div class="columns"> <div class="column is-3"> <%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> <%= render "devise/shared/error_messages", resource: resource %> <div class="field"> <%= f.label :email, class: 'label' %> <!-- class label是block型態 所以不用再手動br換行 --> <%= f.email_field :email, autofocus: true, autocomplete: "email", class: 'input' %> </div> <div class="field"> <%= f.label :password, '密碼', class: 'label' %> <% if @minimum_password_length %> <em>(至少 <%= @minimum_password_length %> 個字元)</em> <% end %> <%= f.password_field :password, autocomplete: "new-password", class: 'input' %> </div> <div class="field"> <%= f.label :password_confirmation, '確認密碼', class: 'label' %> <%= f.password_field :password_confirmation, autocomplete: "new-password", class: 'input' %> </div> <div class="actions"> <%= f.submit "註冊", class: 'button is-primary is-medium' %> </div> <% end %> <%= render "devise/shared/links" %> </div> <div class="column is-9"> <%= image_tag 'https://images.unsplash.com/photo-1568043210943-0e8aac4b9734?q=80&w=1470&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D', alt: '註冊圖片' %> </div> </div> </section>
import { getDatasetTable, getObjectsForDataset, getTablesForDataset, } from "./lib/integrations"; import { Dataset } from "../app/lib/types"; import { isEqual } from "lodash"; import { IntegrationObject, IntegrationTable, } from "../app/lib/integration-types"; import { datasetsTable, objectsTable, rowsTable, tablesTable, } from "../app/db/schema"; import { db } from "./db/db.server"; import { and, eq } from "drizzle-orm"; import { deserialize, serialize } from "../app/utils/serialization"; import { writeOperation } from "./lib/operations"; export async function updateRowFromTableType( dataset: Dataset, tableKey: string, data: any, ) { const table = getDatasetTable(dataset, tableKey); if (!table) { return; } // Upsert table const [dbTable] = await db .insert(tablesTable) .values({ datasetId: dataset.id, name: table.name, key: table.id }) .onConflictDoUpdate({ target: [tablesTable.datasetId, tablesTable.key], set: { name: table.name }, }) .returning(); if (!table.rowId || !dbTable) { console.log("Find the id", data); return; } const id = table.rowId(dataset, data); await updateRow(data, id, dbTable.id); } export async function updateRow(data: any, id: string, tableId: string) { const [existing] = await db .select() .from(rowsTable) .where(and(eq(rowsTable.tableId, tableId), eq(rowsTable.sourceId, id))) .limit(1); if (existing && isEqual(deserialize(existing.data), data)) { return false; } const [upserted] = await db .insert(rowsTable) .values({ tableId, sourceId: id, data: serialize(data) }) .onConflictDoUpdate({ target: [rowsTable.tableId, rowsTable.sourceId], set: { data: serialize(data), sourceId: id }, }) .returning(); if (upserted) { writeOperation({ type: "row", tableId, data: data }); } return !!upserted; } export async function updateObject( dataset: Dataset, data: any, id: string | null, objectType: string, ) { const [existing] = await db .select() .from(objectsTable) .where( and( eq(objectsTable.objectType, objectType), eq(objectsTable.datasetId, dataset.id), ), ) .limit(1); if (existing && isEqual(deserialize(existing.data), data)) { return false; } const [upserted] = await db .insert(objectsTable) .values({ objectType: objectType, // Do we need sourceId here? sourceId: id, data: serialize(data), datasetId: dataset.id, }) .onConflictDoUpdate({ target: [objectsTable.objectType, objectsTable.datasetId], set: { data: serialize(data), sourceId: id }, }) .returning(); if (upserted) { writeOperation({ type: "object", datasetId: dataset.id, objectType, data: data, }); } return !!upserted; } export async function syncObject( dataset: Dataset, objectDefinition: IntegrationObject & { id: string }, ) { if (!objectDefinition.get || !objectDefinition.objId) { return; } // Call fetch for each object definition const data = await objectDefinition.get(dataset); await updateObject( dataset, data, data ? objectDefinition.objId(dataset, data) : null, objectDefinition.id, ); } export async function syncTable( dataset: Dataset, table: IntegrationTable & { id: string }, ) { if (!table.get) { return; } // Call fetch on each table const data = await table.get(dataset); // Save the rows on the DB if (!Array.isArray(data)) { console.error("Data is not an array"); return; } // Upsert table let [dbTable] = await db .insert(tablesTable) .values({ datasetId: dataset.id, name: table.name, key: table.id }) .onConflictDoUpdate({ target: [tablesTable.datasetId, tablesTable.key], set: { name: table.name }, }) .returning(); if (!table.rowId || !dbTable) { console.log("Find the id", data[0]); return; } let updated = 0; for (let rowData of data) { const id = table.rowId(dataset, rowData); const result = await updateRow(rowData, id, dbTable.id); if (result) { updated++; } } } export async function syncDataset(dataset: Dataset) { if ( !dataset.integrationType || (!dataset.credentials?.token && !dataset.credentials?.accessToken) ) { return; } // Load all objects const objects = getObjectsForDataset(dataset); for (let object of objects) { await syncObject(dataset, object); } // Load all tables const tables = getTablesForDataset(dataset); for (let table of tables) { await syncTable(dataset, table); } } export async function syncAll() { // Load all datasets const datasets = await db.select().from(datasetsTable); for (let dataset of datasets) { await syncDataset(dataset); } }
import * as React from 'react'; import { useState, useEffect } from 'react'; import './style.css'; import { hw } from './Headwind/Headwind'; export default function App() { const [color, setColor] = useState('red'); const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'violet']; const updateColor = () => { let newColorIndex = colors.indexOf(color) + 1; if (newColorIndex >= colors.length) newColorIndex = 0; setColor(colors[newColorIndex]); }; const css = `bg-${color} @focus:@hover:(bg-green color-sexypink font animate-bounce)` return ( <div className={hw(`flex`)}> <p>Start editing to see some magic happen :)</p> <h1 className={hw(css)} onClick={updateColor} tabIndex={1} > Hello StackBlitz! </h1> </div> ); }
<!DOCTYPE html> <html lang="en"> <head> <base href="http://bguiz.github.io/js-standards/"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <meta name="keyword" content=""> <link rel="shortcut icon" href="http://bguiz.github.io/js-standards//favicon.ico" type="image/x-icon" /> <title>AngularJs Constants</title> <link href="http://bguiz.github.io/js-standards//css/bootstrap-theme.css" rel="stylesheet"> <link href="http://bguiz.github.io/js-standards//assets/font-awesome/css/font-awesome.min.css" rel="stylesheet" /> <link href="http://bguiz.github.io/js-standards//css/style.css" rel="stylesheet"> <link href="http://bguiz.github.io/js-standards//css/style-responsive.css" rel="stylesheet" /> <link href="http://bguiz.github.io/js-standards//css/monokai_sublime.css" rel="stylesheet" /> </head> <body> <section id="container" class=""> <header class="header black-bg"> <div class="toggle-nav"> <i class="fa fa-bars"></i> <div class="icon-reorder tooltips" data-original-title="Toggle Navigation" data-placement="bottom"></div> </div> <a href="http://bguiz.github.io/js-standards/" class="logo"><img src="http://bguiz.github.io/js-standards/img/logo.png" style="height:40px;"></a> <div class="top-nav notification-row"> <div class="hidden-xs nav-github pull-right"> <span rel="show-github" data-user="bguiz" data-repo="js-standards" data-type="follow"></span> <span rel="show-github" data-user="bguiz" data-repo="js-standards"></span> <span rel="show-github" data-user="bguiz" data-repo="js-standards" data-type="fork"></span> </div> </div> <div class="nav title-row" id="top_menu"> <h1 class="nav top-menu"> AngularJs Constants </h1> </div> </header> <aside> <div id="sidebar" class="nav-collapse "> <ul class="sidebar-menu"> <li class="sub-menu"> <a href="javascript:;" class=""> <span>Getting Started</span> <span class="menu-arrow fa fa-angle-right"></span> </a> <ul class="sub"> <li><a href="http://bguiz.github.io/js-standards/intro"> Intro </a> </li> </ul> </li> <li class="sub-menu"> <a href="javascript:;" class=""> <span>Javascript</span> <span class="menu-arrow fa fa-angle-right"></span> </a> <ul class="sub"> <li><a href="http://bguiz.github.io/js-standards/es5/comments"> Comments (JS) </a> </li> <li><a href="http://bguiz.github.io/js-standards/es5/files"> Files </a> </li> <li><a href="http://bguiz.github.io/js-standards/es5/hoisting"> Hoisting </a> </li> <li><a href="http://bguiz.github.io/js-standards/es5/functions"> Functions </a> </li> <li><a href="http://bguiz.github.io/js-standards/es5/naming"> Naming </a> </li> <li><a href="http://bguiz.github.io/js-standards/es5/control"> Control </a> </li> <li><a href="http://bguiz.github.io/js-standards/es5/equality"> Equality </a> </li> <li><a href="http://bguiz.github.io/js-standards/es5/types"> Types </a> </li> <li><a href="http://bguiz.github.io/js-standards/es5/lint"> Linting </a> </li> </ul> </li> <li class="sub-menu active"> <a href="javascript:;" class=""> <span>AngularJs</span> <span class="menu-arrow fa fa-angle-down"></span> </a> <ul class="sub open"> <li><a href="http://bguiz.github.io/js-standards/angularjs/single-responsibility"> Single Responsibility </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/iife"> IIFE </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/modules"> Modules </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/controllers"> Controllers </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/services"> Services </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/factories"> Factories </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/data-services"> Data Services </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/directives"> Directives </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/resolving-promises-for-a-controller"> Resolving Promises for a Controller </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/manual-annotating-for-dependency-injection"> Manual Annotating for Dependency Injection </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/minification-and-annotation"> Minification and Annotation </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/exception-handling"> Exception Handling </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/naming"> Naming </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/application-structure-lift-principle"> Application Structure LIFT Principle </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/application-structure"> Application Structure </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/modularity"> Modularity </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/startup-logic"> Startup Logic </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/angular-wrapper-services"> Angular $ Wrapper Services </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/testing"> Testing </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/animations"> Animations </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/comments"> Comments </a> </li> <li class="active"><a href="http://bguiz.github.io/js-standards/angularjs/constants"> Constants </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/file-templates-and-snippets"> File Templates and Snippets </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/yeoman-generator"> Yeoman Generator </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/routing"> Routing </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/task-automation"> Task Automation </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/angularjs-docs"> AngularJS docs </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/folder-structure"> Angular Folder Structure </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/logging"> Logging </a> </li> <li><a href="http://bguiz.github.io/js-standards/angularjs/credit"> Credits </a> </li> </ul> </li> <li> <a href="https://github.com/bguiz/js-standards/issues" target="blank"> <i class='fa fa-life-ring'></i> Issues </a> </li> <li> <a href="http://bguiz.github.io/js-standards/angularjs/" target="blank"> <i class='fa fa-edit'></i> Edit </a> </li> </ul> </div> </aside> <section id="main-content"> <section class="wrapper"> <div class="row"> <div class="row-nav-prev col-md-1"> <a class="navigation prev" href="http://bguiz.github.io/js-standards/angularjs/comments"> <i class="fa fa-angle-left"></i> </a> </div> <div class="row-content col-md-10"> <section class="panel"> <div class="panel-body"> <h2 id="constants:9e8c0020b1ac64536071395e70b2990d">Constants</h2> <h3 id="vendor-globals:9e8c0020b1ac64536071395e70b2990d">Vendor Globals</h3> <h6 id="style-y240-style-y240:9e8c0020b1ac64536071395e70b2990d">[Style <a href="#style-y240">Y240</a>]</h6> <ul> <li><p>Create an AngularJS Constant for vendor libraries&rsquo; global variables.</p> <p><em>Why?</em>: Provides a way to inject vendor libraries that otherwise are globals. This improves code testability by allowing you to more easily know what the dependencies of your components are (avoids leaky abstractions). It also allows you to mock these dependencies, where it makes sense.</p> <pre><code class="language-javascript">// constants.js /* global toastr:false, moment:false */ (function() { 'use strict'; angular .module('app.core') .constant('toastr', toastr) .constant('moment', moment); })(); </code></pre></li> </ul> <h6 id="style-y241-style-y241:9e8c0020b1ac64536071395e70b2990d">[Style <a href="#style-y241">Y241</a>]</h6> <ul> <li><p>Use constants for values that do not change and do not come from another service. When constants are used only for a module that may be reused in multiple applications, place constants in a file per module named after the module. Until this is required, keep constants in the main module in a <code>constants.js</code> file.</p> <p><em>Why?</em>: A value that may change, even infrequently, should be retrieved from a service so you do not have to change the source code. For example, a url for a data service could be placed in a constants but a better place would be to load it from a web service.</p> <p><em>Why?</em>: Constants can be injected into any angular component, including providers.</p> <p><em>Why?</em>: When an application is separated into modules that may be reused in other applications, each stand-alone module should be able to operate on its own including any dependent constants.</p> <pre><code class="language-javascript">// Constants used by the entire app angular .module('app.core') .constant('moment', moment); // Constants used only by the sales module angular .module('app.sales') .constant('events', { ORDER_CREATED: 'event_order_created', INVENTORY_DEPLETED: 'event_inventory_depleted' }); </code></pre></li> </ul> </div> </section> </div> <div class="row-nav-next col-md-1"> <a class="navigation prev" href="http://bguiz.github.io/js-standards/angularjs/file-templates-and-snippets"> <i class="fa fa-angle-right"></i> </a> </div> </div> </section> </section> </section> <script src="http://bguiz.github.io/js-standards/js/jquery-2.1.1.min.js"></script> <script src="http://bguiz.github.io/js-standards/js/jquery.scrollTo.min.js"></script> <script src="http://bguiz.github.io/js-standards/js/bootstrap.min.js"></script> <script src="http://bguiz.github.io/js-standards/js/highlight.pack.js"></script> <script>hljs.initHighlightingOnLoad();</script> <script src="http://bguiz.github.io/js-standards/js/scripts.js"></script> <script async defer id="github-bjs" src="http://bguiz.github.io/js-standards/js/buttons.js"></script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-37884921-1', 'bguiz.com'); ga('send', 'pageview'); </script> </body> </html>
// Fill out your copyright notice in the Description page of Project Settings. #include "PlayerBase.h" #include "EnhancedInputComponent.h" #include "EnhancedInputSubsystems.h" #include "Kismet/GameplayStatics.h" #include "Math/Vector.h" #include "Components/CapsuleComponent.h" #include "Kismet/KismetMathLibrary.h" // Sets default values APlayerBase::APlayerBase() { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; // Creating timelines CameraTiltTimeline = CreateDefaultSubobject<UTimelineComponent>(FName("CameraTiltTimeline")); CameraTiltInterp.BindUFunction(this, FName("CameraTilt")); SlideSpeedTimeline = CreateDefaultSubobject<UTimelineComponent>(FName("SlideSpeedTimeline")); SlideSpeedInterp.BindUFunction(this, FName("Sliding")); GrappleDragTimeline = CreateDefaultSubobject<UTimelineComponent>(FName("GrappleDragTimeline")); GrappleDragSpeedInterp.BindUFunction(this, FName("GrappleDragUpdate")); // Binding on hit on overlap GetCapsuleComponent()->OnComponentHit.AddDynamic(this, &APlayerBase::OnHit); GetCapsuleComponent()->OnComponentBeginOverlap.AddDynamic(this, &APlayerBase::OnBeginOverlap); } // Called when the game starts or when spawned void APlayerBase::BeginPlay() { Super::BeginPlay(); MovementComponent = GetCharacterMovement(); // setting the default movement variables DefaultCrouchSpeed = MovementComponent->MaxWalkSpeedCrouched; DefaultAirControl = MovementComponent->AirControl; DefaultGravityScale = MovementComponent->GravityScale; DefaultAcceleration = MovementComponent->MaxAcceleration; //Adding interps to timelines if (CameraTiltCurve) { CameraTiltTimeline->AddInterpFloat(CameraTiltCurve, CameraTiltInterp, FName("Degrees"), FName("Tilt")); } if (SlideSpeedCurve) { SlideSpeedTimeline->AddInterpFloat(SlideSpeedCurve, SlideSpeedInterp, FName("Speed"), FName("SpeedTrack")); } if (GrappleDragForceCurve) { GrappleDragTimeline->AddInterpFloat(GrappleDragForceCurve, GrappleDragSpeedInterp, FName("Speed"), FName("GrappleDragSpeed")); } } // Called every frame void APlayerBase::Tick(float DeltaTime) { Super::Tick(DeltaTime); // Slide off check AActor* Floor = MovementComponent->CurrentFloor.HitResult.GetActor(); FVector ImpactNormal = MovementComponent->CurrentFloor.HitResult.ImpactNormal; if (Floor) // Checking if player should slide off the floor he is standing on or if he should stop sliding { float RelativePitchDegrees; float RelativeRollDegrees; UKismetMathLibrary::GetSlopeDegreeAngles(Floor->GetActorRightVector(), ImpactNormal, FVector(0, 0, 1), RelativePitchDegrees, RelativeRollDegrees); if (UKismetMathLibrary::Abs(RelativePitchDegrees) > SlidingOffAngle || UKismetMathLibrary::Abs(RelativeRollDegrees) > SlidingOffAngle) { if (!MovementComponent->IsCrouching()) { CrouchSlide(); } float WorldPitchDegrees; float WorldRollDegrees; float GeneralAngle = UKismetMathLibrary::FMax(UKismetMathLibrary::Abs(RelativePitchDegrees), UKismetMathLibrary::Abs(RelativeRollDegrees)); float SlideOffSpeedMultiplier = 0.5f; uint32 SlideOffAcceleration = 4000; UKismetMathLibrary::GetSlopeDegreeAngles(FVector(0, 1, 0), ImpactNormal, FVector(0, 0, 1), WorldPitchDegrees, WorldRollDegrees); bIsSlidingOff = true; MovementComponent->MaxWalkSpeedCrouched = DefaultCrouchSpeed * GeneralAngle * SlideOffSpeedMultiplier; MovementComponent->MaxAcceleration = SlideOffAcceleration; MovementComponent->AddInputVector(FVector(WorldPitchDegrees, WorldRollDegrees, GeneralAngle).GetSafeNormal() * -1, true); } else { if (bIsSlidingOff) { StopSlidingOff(); } } } else { if (bIsSlidingOff) { StopSlidingOff(); } } } // Called to bind functionality to input void APlayerBase::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); if (GetController()) { BindController(GetController()); } if (UEnhancedInputComponent* PlayerEnhancedInputComponent = Cast<UEnhancedInputComponent>(PlayerInputComponent)) { // Binding inputs if (IAWalk) { PlayerEnhancedInputComponent->BindAction(IAWalk, ETriggerEvent::Triggered, this, &APlayerBase::Walk); } if (IAJump) { PlayerEnhancedInputComponent->BindAction(IAJump, ETriggerEvent::Started, this, &APlayerBase::InputJump); } if (IALook) { PlayerEnhancedInputComponent->BindAction(IALook, ETriggerEvent::Triggered, this, &APlayerBase::Look); } if (IADash) { PlayerEnhancedInputComponent->BindAction(IADash, ETriggerEvent::Started, this, &APlayerBase::Dash); } if (IACrouchSlide) { PlayerEnhancedInputComponent->BindAction(IACrouchSlide, ETriggerEvent::Started, this, &APlayerBase::CrouchSlideStarted); PlayerEnhancedInputComponent->BindAction(IACrouchSlide, ETriggerEvent::Triggered, this, &APlayerBase::CrouchSlideTriggered); PlayerEnhancedInputComponent->BindAction(IACrouchSlide, ETriggerEvent::Completed, this, &APlayerBase::CrouchSlideCompleted); } if (IAGrapple) { PlayerEnhancedInputComponent->BindAction(IAGrapple, ETriggerEvent::Started, this, &APlayerBase::UseGrapple); } if (IAPause) { PlayerEnhancedInputComponent->BindAction(IAPause, ETriggerEvent::Started, this, &APlayerBase::PauseCalled); } } } void APlayerBase::BindController(AController* NewController) { APlayerController* PlayerController = Cast<APlayerControllerBase>(NewController); // Adding Mapping Context if (ULocalPlayer* LocalPlayer = Cast<ULocalPlayer>(PlayerController->GetLocalPlayer())) { if (UEnhancedInputLocalPlayerSubsystem* InputSystem = LocalPlayer->GetSubsystem<UEnhancedInputLocalPlayerSubsystem>()) { if (!InputMappingContext.IsNull()) { InputSystem->AddMappingContext(InputMappingContext.LoadSynchronous(), 1); } } } } void APlayerBase::OnHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpuls, const FHitResult& Hit) { if (OtherComp->ComponentHasTag(WallRunTag) && CanWallRun(Hit.ImpactNormal)) { // init wall run CurrentSide = FindRunSide(Hit.ImpactNormal); WallRunDirection = FindRunDirection(Hit.ImpactNormal, CurrentSide); BeginWallRun(); } if (OtherComp->ComponentHasTag(KillBoxTag)) { APlayerControllerBase* PlayerController = Cast<APlayerControllerBase>(GetController()); PlayerController->ShowDeathWidget(); } } void APlayerBase::OnBeginOverlap(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult) { if (OtherComp->ComponentHasTag(JumpPadTag)) { float LaunchForce; float ForceMultiplier = 0.6f; LaunchForce = FMath::Abs(MovementComponent->Velocity.Z) * ForceMultiplier + JumpPadAdditionalForce; LaunchCharacter(FVector(0, 0, LaunchForce), false, true); } } bool APlayerBase::CanWallBeRunOn(const FVector& WallNormal) { float WallAcceptedAngle = -0.05f; double WallAngle = UKismetMathLibrary::DegAcos(FVector::DotProduct(WallNormal.GetSafeNormal2D(), WallNormal)); bool WallAngleRunnable = WallAngle < MovementComponent->GetWalkableFloorAngle(); return WallNormal.Z >= WallAcceptedAngle && WallAngleRunnable; } void APlayerBase::EnteredLadder(const FVector& LadderForward) { if (bCanEnterLadder) { bCanEnterLadder = false; LadderForwardVector = LadderForward; bIsOnLadder = true; MovementComponent->SetMovementMode(EMovementMode::MOVE_Flying); MovementComponent->StopMovementImmediately(); } } void APlayerBase::ExittedLadder() { bIsOnLadder = false; if (!bIsGrappling) { MovementComponent->SetMovementMode(EMovementMode::MOVE_Walking); } float LadderCooldown = 0.2f; GetWorldTimerManager().SetTimer(LadderCooldownHandle, [this]() { bCanEnterLadder = true; }, LadderCooldown, false); } void APlayerBase::ExitLadderBoost() { uint32 LaunchForce = 50; LaunchCharacter(GetActorUpVector() * LaunchForce, false, false); } void APlayerBase::OnDestroyed() { if (ScanDashIcon.IsValid()) { GetWorldTimerManager().ClearTimer(ScanDashIcon); } } void APlayerBase::Walk(const FInputActionValue& IAValue) { const FVector2D MoveVector = IAValue.Get<FVector2D>(); float XAxis = MoveVector.X; YWalkAxis = MoveVector.Y; if (bIsOnLadder) { if (XAxis != 0) { if (FVector::DotProduct(LadderForwardVector, GetActorRightVector() * XAxis) < 0) { AddMovementInput(GetActorUpVector(), 1); } else { AddMovementInput(GetActorUpVector(), -1); } } if (YWalkAxis != 0) { if (FVector::DotProduct(LadderForwardVector, GetActorForwardVector() * YWalkAxis) < 0) { AddMovementInput(GetActorUpVector(), 1); } else { AddMovementInput(GetActorUpVector(), -1); } } } else { if (bIsSlidingOff) // player has restricted move while sliding off { XAxis /= 10; YWalkAxis = 0; } AddMovementInput(GetActorRightVector(), XAxis); // moving in X-axis AddMovementInput(GetActorForwardVector(), YWalkAxis); // moving in Y-axis } } void APlayerBase::Look(const FInputActionValue& IAValue) { const FVector2D LookVector = IAValue.Get<FVector2D>(); AddControllerYawInput(LookVector.X * MouseXSensitivity); AddControllerPitchInput(LookVector.Y * MouseYSensitivity * -1); } void APlayerBase::InputJump() { StopCrouching(); if (bIsOnLadder) { uint32 LaunchFromLadderForce = 1000; LaunchCharacter(LadderForwardVector * LaunchFromLadderForce, false, false); ExittedLadder(); } else if (bIsWallRunning) { LaunchCharacter(FindLaunchFromWallVelocity(), false, false); EndWallRun(); } else if (bIsSlidingOff) { LaunchCharacter(FVector(0,0,MovementComponent->JumpZVelocity), false, true); } else { Jump(); } } void APlayerBase::Dash() // Dash ability { if (!bDashOnCooldown && !bIsGrappling) { bDashOnCooldown = true; uint32 DashForce; if (MovementComponent->IsFalling()) { DashForce = 2550; // Dash is stronger if player is not in air } else { DashForce = 2700; } LaunchCharacter(GetControlRotation().Vector() * DashForce, true, true); APlayerControllerBase* PlayerController = Cast<APlayerControllerBase>(GetController()); GetWorldTimerManager().SetTimer(ScanDashIcon, [this, PlayerController]() { PlayerController->UpdateDashIconScanHudWidget((DashCooldown - GetWorldTimerManager().GetTimerRemaining(ResetDashIconScan)) / DashCooldown); }, 0.01f, true); GetWorldTimerManager().SetTimer(ResetDashIconScan, [this, PlayerController]() { GetWorldTimerManager().ClearTimer(ScanDashIcon); PlayerController->UpdateDashIconScanHudWidget(0.f); }, DashCooldown, false); GetWorldTimerManager().SetTimer(DashTimerHandle, [this]() {bDashOnCooldown = false; }, DashCooldown, false); } } void APlayerBase::CrouchSlideStarted() { if (MovementComponent->IsMovingOnGround()) { CrouchSlide(); } else { bHoldingCrouch = true; } } void APlayerBase::CrouchSlideTriggered() { if (bHoldingCrouch) { bHoldingCrouch = false; if (!MovementComponent->IsCrouching()) { CrouchSlideStarted(); } } } void APlayerBase::CrouchSlideCompleted() { if (!bIsSlidingOff) { UnCrouch(); MovementComponent->MaxWalkSpeedCrouched = DefaultCrouchSpeed; } } void APlayerBase::PauseCalled() { APlayerControllerBase* PlayerController = Cast<APlayerControllerBase>(GetController()); PlayerController->PauseUnpause(); } void APlayerBase::CrouchSlide() // if player is fast enough we initiate slide if not we initiate normal crouch { double PlayerSpeed = UKismetMathLibrary::VSizeXY(MovementComponent->Velocity); Crouch(); if (PlayerSpeed >= SpeedNeededToSlide) { MovementComponent->MaxWalkSpeedCrouched = PlayerSpeed + SlideAdditionalSpeed; SlideSpeedDifference = MovementComponent->MaxWalkSpeedCrouched - DefaultCrouchSpeed; MovementComponent->AddImpulse(MovementComponent->Velocity.GetSafeNormal() * PlayerSpeed); SlideSpeedTimeline->PlayFromStart(); } else { MovementComponent->MaxWalkSpeedCrouched = DefaultCrouchSpeed; } } void APlayerBase::StopCrouching() { UnCrouch(); MovementComponent->MaxWalkSpeedCrouched = DefaultCrouchSpeed; } void APlayerBase::StopSlidingOff() { MovementComponent->MaxWalkSpeedCrouched = DefaultCrouchSpeed; MovementComponent->MaxAcceleration = DefaultAcceleration; bIsSlidingOff = false; StopCrouching(); } void APlayerBase::BeginWallRun() // setting the values for wall running or movement and tilting camera { MovementComponent->AirControl = 1; MovementComponent->GravityScale = 0; MovementComponent->SetPlaneConstraintNormal(FVector(0, 0, 1)); bIsWallRunning = true; CameraTiltTimeline->Play(); GetWorldTimerManager().SetTimer(WallRunTimer, this, &APlayerBase::UpdateWallRun, 0.1f, true); } void APlayerBase::EndWallRun() // setting the default values or movement and tilting camera back { MovementComponent->AirControl = DefaultAirControl; MovementComponent->GravityScale = DefaultGravityScale; MovementComponent->SetPlaneConstraintNormal(FVector(0, 0, 0)); bIsWallRunning = false; CameraTiltTimeline->Reverse(); GetWorldTimerManager().ClearTimer(WallRunTimer); } void APlayerBase::UpdateWallRun() // wall run function called every tick when wallrunning setting velocity or ending the wall run { FHitResult HitResult; FVector SideToTrace; switch (CurrentSide) { case Left: SideToTrace = FVector(0, 0, -1); break; case Right: SideToTrace = FVector(0, 0, 1); break; } uint32 TraceLength = 200; FVector TraceEnd = GetActorLocation() + FVector::CrossProduct(WallRunDirection, SideToTrace) * TraceLength; bool bHitWall = GetWorld()->LineTraceSingleByChannel(HitResult, GetActorLocation(), TraceEnd, ECC_Visibility, FCollisionQueryParams(FName(NAME_None), false, this)); if (bHitWall) { if (HitResult.Component->ComponentHasTag(WallRunTag) && FindRunSide(HitResult.ImpactNormal) == CurrentSide) { WallRunDirection = FindRunDirection(HitResult.ImpactNormal, CurrentSide); FVector WallRunForce = WallRunDirection * MovementComponent->GetMaxSpeed(); MovementComponent->Velocity = FVector(WallRunForce.X, WallRunForce.Y, 0); } else { EndWallRun(); } } else { EndWallRun(); } } bool APlayerBase::CanWallRun(const FVector& SurfaceNormal) { uint32 MinVelocity = 200; float PlayerVel = UKismetMathLibrary::Quat_UnrotateVector(FQuat(GetActorRotation()), GetVelocity()).X; return !bIsWallRunning && MovementComponent->IsFalling() && PlayerVel > MinVelocity && YWalkAxis >= 0 && CanWallBeRunOn(SurfaceNormal); } void APlayerBase::CameraTilt(float TimelineVal) // when wallrunning camera tilts a little bit { int32 CameraTiltSide; switch (CurrentSide) { case Left: CameraTiltSide = -1; break; case Right: CameraTiltSide = 1; break; } APlayerControllerBase* PlayerController = Cast<APlayerControllerBase>(GetController()); FRotator CurrentRoation = PlayerController->GetControlRotation(); PlayerController->SetControlRotation(FRotator(CurrentRoation.Pitch, CurrentRoation.Yaw, TimelineVal * CameraTiltSide)); } WallRunSide APlayerBase::FindRunSide(const FVector& WallNormal) { double DotResult = FVector2D::DotProduct(FVector2D(WallNormal), FVector2D(GetActorRightVector())); WallRunSide SideFound; if (DotResult < 0) { SideFound = Left; } else { SideFound = Right; } return SideFound; } FVector APlayerBase::FindRunDirection(const FVector& WallNormal, WallRunSide Side) { FVector RunSide; switch (Side) { case Left: RunSide = FVector(0, 0, -1); break; case Right: RunSide = FVector(0, 0, 1); break; default: break; } return FVector::CrossProduct(WallNormal, RunSide); } FVector APlayerBase::FindLaunchFromWallVelocity() const { FVector SideToJumpFrom; switch (CurrentSide) { case Left: SideToJumpFrom = FVector(0, 0, 1); break; case Right: SideToJumpFrom = FVector(0, 0, -1); break; } float LaunchForceMultiplier = 0.55f; FVector AdditionalUpForce = FVector(0, 0, 200); return FVector((FVector::CrossProduct(WallRunDirection, SideToJumpFrom) + FVector(0, 0, 1)) * MovementComponent->JumpZVelocity * LaunchForceMultiplier + AdditionalUpForce); } void APlayerBase::Sliding(float Speed) // Slide function called every tick when sliding // should add some left-right input constraints { MovementComponent->MaxWalkSpeedCrouched -= Speed * SlideSpeedDifference; SlideSpeedDifference = MovementComponent->MaxWalkSpeedCrouched - DefaultCrouchSpeed; if (MovementComponent->IsCrouching()) { if (MovementComponent->MaxWalkSpeedCrouched <= DefaultCrouchSpeed + 50) { MovementComponent->MaxWalkSpeedCrouched = DefaultCrouchSpeed; Crouch(); SlideSpeedTimeline->Stop(); } } else { SlideSpeedTimeline->Stop(); } } void APlayerBase::UseGrapple() { if (!bIsGrappling) { if (bCanUseGrapple && !bGrappleCanSecondUse && FindGrappleTarget()) { GrappleFirst(); } } else { GrappleSecond(); } } void APlayerBase::GrappleFirst() { APlayerControllerBase* PlayerController = Cast<APlayerControllerBase>(GetController()); GrappleLine = GetWorld()->SpawnActor<AGrappleLine>(GrappleLineClass, GetActorTransform(), FActorSpawnParameters()); GrappleLine->GrappleOn(GrappleTarget->GetActorLocation()); bGrappleCanSecondUse = true; GrappleTargetSphereColl = Cast<USphereComponent>(GrappleTarget->GetComponentByClass(USphereComponent::StaticClass())); bGrappleArrived = false; bIsGrappling = true; bCanUseGrapple = true; MovementComponent->SetMovementMode(EMovementMode::MOVE_Flying); MovementComponent->StopMovementImmediately(); PlayerController->SetIgnoreMoveInput(true); GrappleBeginningDistance = UKismetMathLibrary::Vector_Distance(GetActorLocation(), GrappleTarget->GetActorLocation()); GrappleDragTimeline->PlayFromStart(); } void APlayerBase::GrappleSecond() { APlayerControllerBase* PlayerController = Cast<APlayerControllerBase>(GetController()); GrappleLine->GrappleOff(); bIsGrappling = false; bGrappleCanSecondUse = false; PlayerController->SetIgnoreMoveInput(false); GrappleDragTimeline->Stop(); MovementComponent->SetMovementMode(MOVE_Walking); FVector ZImpulseToAddOnEnd; if (bGrappleArrived) { ZImpulseToAddOnEnd.Z = 225; } else { ZImpulseToAddOnEnd.Z = 185; } FVector GrappleForce = (MovementComponent->Velocity.GetSafeNormal() + ZImpulseToAddOnEnd) * GrappleImpulseMultiplier; MovementComponent->AddImpulse(GrappleForce); } void APlayerBase::GrappleDragUpdate(float TimelineVal) { FVector GrappleDirection; GrappleDirection = (GrappleTarget->GetActorLocation() - GetActorLocation()).GetSafeNormal(); FVector GrappleForce; GrappleForce = GrappleDirection * GrappleForceMultiplier * MovementComponent->Mass * TimelineVal; MovementComponent->AddForce(GrappleForce); if (GrappleTargetSphereColl->IsOverlappingActor(this)) { bGrappleArrived = true; GrappleSecond(); } } bool APlayerBase::FindGrappleTarget() { GrappleTarget = nullptr; float TraceRadius = GrappleRange; TArray<FHitResult> TraceResults; TArray<TEnumAsByte<EObjectTypeQuery>>GrappleTargetType; const EObjectTypeQuery GrappleType = UCollisionProfile::Get()->ConvertToObjectType(ECC_GameTraceChannel1); // grapple object type if(GrappleType)GrappleTargetType.Add(GrappleType); UKismetSystemLibrary::SphereTraceMultiForObjects(GetWorld(), GetActorLocation(), GetActorLocation(), TraceRadius, GrappleTargetType, false, TArray<AActor*>(), EDrawDebugTrace::None, TraceResults, false); float Difference = 999999; // Difference in distance between grapple target and player's cursor FVector PlayerLooks = UGameplayStatics::GetPlayerCameraManager(GetWorld(), 0)->GetActorForwardVector(); for( const auto& Hit : TraceResults) { AActor* TargetFound = Hit.GetActor(); bool bTargetOnScreen = TargetFound->WasRecentlyRendered(); FVector TargetDirection = FVector(TargetFound->GetActorLocation()-GetActorLocation()).GetSafeNormal(); float DistanceTargetToCursor = UKismetMathLibrary::Vector_Distance(TargetDirection, PlayerLooks); bool bTargetCloserToCursor = DistanceTargetToCursor < Difference; if (bTargetOnScreen && bTargetCloserToCursor) { Difference = DistanceTargetToCursor; GrappleTarget = TargetFound; } } return UKismetSystemLibrary::IsValid(GrappleTarget); }
/* * Updated 03/4/2023 - Samriddha Kharel */ /* compile with -g to collect debugging info needed for Valgrind ( -lm links the math library): gcc -g bucket_sort.c list.c -lm run with Valgrind: valgrind --leak-check=full ./a.out On some systems, but not all, you can also use the --show-leak-kinds=all flag: valgrind --leak-check=full --show-leak-kinds=all ./a.out run without Valgrind: ./a.out */ // This program sorts a number in ascending order using bucket sort Algorithm. #include <stdlib.h> #include <stdio.h> #include <math.h> #include "list.h" // useful if you want to use functions from list.c void print_array(int arr[], int N); void run1(); void bucket_sort(int * arr, int N); /* // function to insert a new node in a sorted list. E.g.: nodePT insert_sorted(nodePT L, nodePT newP); //or nodePT insert_sorted(nodePT L, int elem); // function to sort an array sing bucket sort. E.g.: void bucket_sort(int * arr, int N); */ struct Node { int data; struct Node* next; }; nodePT insert_sorted(nodePT L, int elem) { nodePT newNode = (nodePT)malloc(sizeof(struct node)); newNode->data = elem; newNode->next = NULL; if (L == NULL || elem < (L)->data) { newNode->next = L; L = newNode; } else { nodePT current = L; while (current->next != NULL && elem >= current->next->data) { current = current->next; } newNode->next = current->next; current->next = newNode; } } void bucket_sort(int *arr, int N) { double min; double max; int indx; int indexarr[N]; //--------------------------------------------------------------------- nodePT buckets[N]; for (int i = 0; i < N; i++) { buckets[i] = NULL; } int arrsize = sizeof(arr) / sizeof(arr[0]); max = *(arr+0); for (int i = 1; i < N; i++) { if (*(arr+i) > max) { max = *(arr+i); } } min = *(arr+0); for (int i = 1; i < N; i++) { if (*(arr+i) < min) { min = *(arr+i); } } //--------------------------------------------------------------------- printf("\n\nBucketsort: min=%d, max=%d, N=%d buckets\n",(int)min,(int)max,N); for (int i = 0; i < N; i++) { indx = floor((arr[i] - min) *N/ (1 + max- min)); indexarr[i]=indx; printf("arr[%d]= %d, idx = %d\n",i,arr[i],indx); buckets[indx] = insert_sorted(buckets[indx], arr[i]); } for (int i = 0; i < N; i++) { // Sort the linked list using insertion sort nodePT curr = buckets[i]; while (curr != NULL && curr->next != NULL) { nodePT prev = NULL; nodePT innerCurr = curr->next; while (innerCurr != NULL) { if (innerCurr->data < curr->data) { if (prev != NULL) { prev->next = innerCurr; } else { buckets[i] = innerCurr; } curr->next = innerCurr->next; innerCurr->next = curr; prev = innerCurr; innerCurr = curr->next; } else { prev = curr; curr = innerCurr; innerCurr = innerCurr->next; } } } } for (int i = 0; i < N; i++) { int flag = 0; printf("------ List at index %d :\n",i); nodePT curr = buckets[i]; if(curr != NULL) { printf(" List items: "); while (curr != NULL) { printf("%d ", curr->data); flag++; curr = curr->next; } printf("\nLength of above list = %d",flag); } else { printf("<print_list_horiz> : List is NULL"); } printf("\n"); } // Copy elements from buckets back into array in sorted order int index = 0; for (int i = 0; i < N; i++) { nodePT current = buckets[i]; while (current != NULL) { arr[index++] = current->data; current = current->next; } } // Free memory for (int i = 0; i < N; i++) { nodePT current = buckets[i]; while (current != NULL) { nodePT tempfree = current; current = current->next; free(tempfree); } } } void print_array(int arr[], int N) { int j; printf("\n array: "); for(j= 0; j<N; j++) { printf("%5d,", arr[j]); } printf("\n"); } //------------------------------------------------------------- void run1() { // Fill in your code here. You should not write everything in this function. // Write some helper functions to separate the work. char fname[50]; int min; int max; int N; FILE *fp; printf("Enter the filename: "); scanf("%s", fname); fp =fopen(fname, "r"); if (fp == NULL) { printf("File could not be opened.\n"); exit(0); } fscanf(fp, "%d", &N); int arr[N]; for (int i = 0; i < N; i++) { fscanf(fp, "%d", &arr[i]); } fclose(fp); // Close the file print_array(arr,N); bucket_sort(arr,N); print_array(arr,N); printf("\n-------run1 - this is a place holder. You need to edit this function.------ \n"); } int main() { printf("This program will read a file name, load data for an array from there and print the sorted array.\n"); printf("The array is sorted using bucket sort.\n"); printf("This will be repeated as long as the user wants.\n"); int option = 1; do { run1(); printf("\nDo you want to repeat? Enter 1 to repeat, or 0 to stop) "); char ch; scanf("%d%c",&option, &ch); // ch is used to remove the Enter from the input buffer } while (option == 1); return 0; }
import { View, Text, ScrollView, FlatList, TouchableOpacity, StyleSheet, ActivityIndicator } from "react-native"; import React, { useState, useEffect, useContext } from "react"; import { AuthContext } from '../Context/AuthContext'; import { useTheme } from "@react-navigation/native"; import axios from 'axios'; const Deliveries = ({ navigation }) => { const { token, url, ids } = useContext(AuthContext); const { colors } = useTheme(); const [loading, setLoading] = useState(false); const [lastServices, setLastServices] = useState([]); useEffect(() => { const reloadData = navigation.addListener('focus', () => { setLoading(true); axios.get(`${url}/couriers/courier-day-orders`, { params: { courier_id: ids, }, headers: { 'Authorization': `Bearer ${token}` } }) .then((response) => { setLoading(false); setLastServices(response.data.data); }) .catch((error) => { setLoading(false); console.log(error); }); }); return reloadData; }, []); return ( <View style={{ gap: 12, padding: 12, backgroundColor: colors.background }}> {/* Header */} <View style={{ paddingHorizontal: 24, flexDirection: 'row', alignItems: 'center', gap: 8 }}> <Text style={{ fontSize: 32, fontWeight: 'bold', color: '#000' }}>Entregas del día</Text> </View> <ScrollView style={{ backgroundColor: colors.background, marginBottom: 20 }} > <FlatList data={lastServices} renderItem={({ item }) => <Item item={item} />} keyExtractor={(item) => item.id} numColumns={1} horizontal={false} vertical={false} onEndReachedThreshold={0.1} ListEmptyComponent={() => ( <View style={{ flex: 1, alignItems: "center", justifyContent: "center", padding: 24, }} > <Text style={{ fontSize: 24, fontWeight: "600", color: colors.text, flex: 1, textAlign: "center", }} > No hay entregas del día </Text> </View> )} loading = {loading} LoadingView={() => ( <View style={{ flex: 1, alignItems: "center", justifyContent: "center", padding: 24, }} > <ActivityIndicator size="large" color="#014aad" animating={loading ? true : false} /> </View> )} /> </ScrollView> <ActivityIndicator size="large" color="#014aad" animating={loading ? true : false} /> </View> ); }; const styles = StyleSheet.create({ safeArea: { flex: 1, backgroundColor: '#fff' }, container: { flex: 1, flexDirection: 'column', justifyItems: 'center', alignItems: 'center', backgroundColor: '#fff', padding: 30 }, text: { paddingTop: 20 }, textLink: { paddingTop: 20, color: 'blue' }, sectionContainer: { marginTop: 32, paddingHorizontal: 24, }, sectionTitle: { fontSize: 24, fontWeight: '600', }, sectionDescription: { marginTop: 8, fontSize: 18, fontWeight: '400', }, highlight: { fontWeight: '700', }, }); const Item = ({ item }) => ( <TouchableOpacity style={{ padding: 6, backgroundColor: '#fff', shadowColor: '#000', shadowOffset: { width: 0, height: 2, }, shadowOpacity: 0.25, shadowRadius: 3.84, elevation: 5, padding: 30, margin: 10, flexDirection: 'row', gap: 12, borderRadius: 12, marginBottom: 20, }} > <View style={{ flex: 1, flexDirection: 'column', gap: 4 }}> <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}> <Text style={{ fontSize: 18, fontWeight: '600', color: '#000', }} numberOfLines={2} > Orden #{item.id.toString().padStart(6, '0')} </Text> <Text style={{ fontSize: 24, fontWeight: '600', color: '#000', }} numberOfLines={2} > {item.created_at.split('T')[1].split('.')[0].slice(0, -3)} </Text> </View> <Text style={{ fontSize: 18, color: '#000', paddingVertical: 4, fontWeight: 'bold' }}>{item.business.name}</Text> <Text style={{ fontSize: 12, color: '#000', paddingVertical: 4, }} numberOfLines={3} > <Text style={{fontWeight: 600}}>Dirección de Pick:</Text> {item.business.address} </Text> <Text style={{ fontSize: 12, color: '#000', paddingVertical: 4, }} numberOfLines={3} > <Text style={{fontWeight: 600}}>Dirección de Drop:</Text> {item.address.street + ' ' + item.address.external_number} {item.address.is_corner ? 'esquina con ' + item.address.corner_street : 'entre ' + item.address.between_street_1 + ' y ' + item.address.between_street_2} Col. {item.address.neighborhood.name} </Text> <Text style={{ fontSize: 12, color: '#000', paddingVertical: 4, }} > <Text style={{fontWeight: 600}}>Referencia:</Text> {item.address.reference} </Text> <Text style={{ fontSize: 12, color: '#000', paddingVertical: 4, }} > <Text style={{fontWeight: 600}}>Usuario:</Text> {item.client.first_name} {item.client.last_name} </Text> <Text style={{ fontSize: 12, color: '#000', paddingVertical: 4, }} > <Text style={{fontWeight: 600}}>Telefono:</Text> {item.client.phone_number} </Text> <Text style={{ fontSize: 12, color: '#000', paddingVertical: 4, }} > <Text style={{fontWeight: 600}}>Observaciones:</Text> {item.observations} </Text> <Text style={{ fontSize: 12, color: '#000', paddingVertical: 4, }} > <Text style={{fontWeight: 600}}>Monto:</Text> {item.amount} </Text> </View> </TouchableOpacity> ); export default Deliveries;
import { ChangeEvent, FormEvent, Fragment, useLayoutEffect, useRef, useState } from 'react'; import cn from 'classnames'; import Spinner from '../../spinner/spinner'; import { useAppDispatch, useAppSelector } from '../../../hooks/hooks'; import { changeReviewModalActive } from '../../../store/modal-slice/modal-slice'; import { selectSendCommentStatus, sendCommentAction } from '../../../store/comments-slice/comments-slice'; import { selectGuitar } from '../../../store/guitars-slice/guitars-slice'; import { FetchStatus, RatingLabelMap } from '../../../utils/const'; import styles from './reviews-modal.module.css'; const REG_EXP_NAME = /^[аА-яЯaA-zZ'][аА-яЯaA-zZ -' ]+[аА-яЯaA-zZ']?$/i; const REG_EXP_RATING = /[1-5]/; const REG_EXP_TEXT = /[аА-яЯaA-zZ]{3}/i; interface LoginField { value: string; regexp: RegExp; error: boolean; errorText: string; } type InitialState = { [key: string]: LoginField }; function ReviewsModal(): JSX.Element | null { const dispatch = useAppDispatch(); const guitar = useAppSelector(selectGuitar); const sendCommentStatus = useAppSelector(selectSendCommentStatus); const inputFocus = useRef<HTMLInputElement | null>(null); const [formState, setFormState] = useState<InitialState>({ name: { value: '', regexp: REG_EXP_NAME, error: false, errorText: 'Заполните поле', }, rating: { value: '0', regexp: REG_EXP_RATING, error: false, errorText: 'Поставьте оценку', }, advantage: { value: '', regexp: REG_EXP_TEXT, error: false, errorText: 'Заполните поле', }, disadvantage: { value: '', regexp: REG_EXP_TEXT, error: false, errorText: 'Заполните поле', }, comment: { value: '', regexp: REG_EXP_TEXT, error: false, errorText: 'Заполните поле', }, }); useLayoutEffect(() => { inputFocus.current?.focus(); }, []); if (!guitar) { return null; } const { name, id } = guitar; const ratingLabelMapRevers: [string, string][] = Object.entries(RatingLabelMap); const isValid = Object.values(formState).some(({ error }) => error); const isFormDisabled = sendCommentStatus === FetchStatus.Pending; const handleInputChange = (evt: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => { const { value, name } = evt.target; const regExp = formState[name].regexp; const isValid = regExp.test(value); setFormState((prevState) => ({ ...prevState, [name]: { ...prevState[name], error: !isValid, value, }, })); }; const handleModalClose = () => { dispatch(changeReviewModalActive(false)); }; const handleFormReviewSubmit = (evt: FormEvent<HTMLFormElement>) => { evt.preventDefault(); if (formState.rating.value === '0') { formState.rating.error = true; } const data = { guitarId: id, userName: formState.name.value, advantage: formState.advantage.value, disadvantage: formState.disadvantage.value, comment: formState.comment.value, rating: Number(formState.rating.value), }; dispatch(sendCommentAction(data)); }; return ( <div className="modal__content"> <h2 className="modal__header modal__header--review title title--medium">Оставить отзыв</h2> <h3 className="modal__product-name title title--medium-20 title--uppercase">{name}</h3> <form className="form-review" name="form-review" onSubmit={handleFormReviewSubmit}> <div className={cn('form-review__wrapper', { [styles.input_mb]: !formState.name.error })}> <div className="form-review__name-wrapper"> <label className="form-review__label form-review__label--required" htmlFor="user-name"> Ваше Имя </label> <input onChange={handleInputChange} ref={inputFocus} className="form-review__input form-review__input--name" id="user-name" type="text" autoComplete="off" name="name" value={formState.name.value} required disabled={isFormDisabled} /> {formState.name.error && <p className="form-review__warning">{formState.name.errorText}</p>} </div> <div> <span className="form-review__label form-review__label--required">Ваша Оценка</span> <div className={styles['rate']}> {ratingLabelMapRevers.map(([value, title]) => ( <Fragment key={title}> <input onChange={handleInputChange} className={`visually-hidden ${styles['rate__input']}`} id={`star-${value}`} name="rating" type="radio" value={value} checked={value === formState.rating.value} required disabled={isFormDisabled} /> <label className={styles['rate__label']} htmlFor={`star-${value}`} title={title} /> </Fragment> ))} {formState.rating.error && <p className="rate__message">{formState.rating.errorText}</p>} <div className={styles['rate__focus']} /> </div> </div> </div> <label className="form-review__label form-review__label--required" htmlFor="adv"> Достоинства </label> <input onChange={handleInputChange} className={cn('form-review__input', [styles.input_mb], { [styles.input_mb_error]: formState.advantage.error, })} id="adv" type="text" autoComplete="off" name="advantage" value={formState.advantage.value} required disabled={isFormDisabled} /> {formState.advantage.error && <p className="form-review__warning">{formState.advantage.errorText}</p>} <label className="form-review__label form-review__label--required" htmlFor="disadv"> Недостатки </label> <input onChange={handleInputChange} className={cn('form-review__input', { [styles.input_mb]: !formState.disadvantage.error, })} id="disadv" type="text" autoComplete="off" name="disadvantage" value={formState.disadvantage.value} required disabled={isFormDisabled} /> {formState.disadvantage.error && ( <p className={cn('form-review__warning', { [styles.input_mb_error]: formState.disadvantage.error })}> {formState.disadvantage.errorText} </p> )} <label className="form-review__label form-review__label--required" htmlFor="comment"> Комментарий </label> <textarea onChange={handleInputChange} className={cn('form-review__input', 'form-review__input--textarea', { [styles.input_mb]: !formState.comment.error, })} id="comment" rows={10} autoComplete="off" name="comment" value={formState.comment.value} required disabled={isFormDisabled} /> {formState.comment.error && ( <p className={cn('form-review__warning', { [styles.input_mb_error]: formState.comment.error })}> {formState.comment.errorText} </p> )} <button className="button button--medium-20 form-review__button" type="submit" disabled={isValid || isFormDisabled}> {isFormDisabled ? <Spinner className="spinner--small" /> : 'Отправить отзыв'} </button> </form> <button onClick={handleModalClose} className="modal__close-btn button-cross" type="button" aria-label="Закрыть"> <span className="button-cross__icon" /> <span className="modal__close-btn-interactive-area" /> </button> </div> ); } export default ReviewsModal;
// import logo from './logo.svg'; import React from "react"; import './App.css'; import Navbar from './components/Navbar'; import Textform from './components/Textform'; import About from './components/About'; import { useState } from 'react'; import { BrowserRouter, Routes, Route, Link, } from "react-router-dom"; function App() { const [mode,setMode] = useState('light'); const toggleMode = ()=>{ if(mode === 'light'){ setMode('dark'); document.body.style.backgroundColor='black'; // setInterval(()=>{document.title='text utils'},1500); // setInterval(()=>{document.title='Hello this is your first app'},2000); } else{ setMode('light'); document.body.style.backgroundColor='white'; } } return ( <> <Navbar name="Mansi" toggleMode={toggleMode} mode={mode}/> <div className="container"> <BrowserRouter> <Routes> <Route path="/about" element={<About />} /> <Route path="/" element={<Textform/>} /> </Routes> </BrowserRouter> </div> </> ); } export default App;
mod2<- lm(precio~calidad, data = moch) #aplicar los supuestos para ver si tenemos un buen modelo moch$ajus<-fitted(mod2) moch$resi<-residuals(mod2) moch$rstud<-rstudent(mod2) #Supuesto de normalidad install.packages("lmtest") require (lmtest) ks.test(moch$rstud, "pnorm") #histograma hist(moch$rstud, xlab="residuales", main="Hist residuales") #El p valor para el contraste de normalidad es mayor que 0.05 (P=0.9719) y ademas el histograma se parece a una distribucion normal (curva en forma de campana) entonces no hay problemas de normalidad #Supuesto de homogeneidad de varianzas bptest(mod2, studentize = FALSE, data=moch) #p=0.4154, mayor a 0.05, ie, que la varianza es constante a lo largo de la muestra dwtest(mod2, alternative = "two.sided", data = moch) #Aceptamos la hipotesis nula, entonces no existe correlacion entres los residuos con un p-valor superior a 0.05 (pvalue=0.2976)
<?php namespace OmniaDigital\CatalystCore\Livewire\Pages\Projects; use Livewire\Component; use OmniaDigital\CatalystCore\Facades\Catalyst; use OmniaDigital\CatalystCore\Models\Project; use App\Models\User; use OmniaDigital\CatalystCore\Support\Auth\WithGuestAccess; use OmniaDigital\CatalystLocation\Models\Location; use OmniaDigital\OmniaLibrary\Livewire\WithMap; use Spatie\MediaLibrary\MediaCollections\Models\Media; class Show extends Component { use WithGuestAccess; use WithMap; public $project; public $displayUrl = null; public $displayID = null; public ?User $userToAddAwardsTo; public $applicationsCount = 0; public $awardsToAdd = []; public $additionalInfo = [ 'likes', 'comments', 'members', ]; public $activity = [ 'user' => [ 'avatar' => 'https://via.placeholder.com/150', ], 'title' => 'Activity Title', 'created_at' => 'June 1, 2022', 'id' => 1, 'message' => 'Activity Message', 'project' => [ 'link' => '#', ], 'members' => [ [ 'avatar' => 'https://via.placeholder.com/150', 'name' => 'Member Name', 'link' => '#', ], ], ]; protected $listeners = ['addUserAwards', 'modal-closed' => 'resetAwardsSelection']; public function mount(Project $project) { $this->displayUrl = $project->sampleImages()->first()->getFullUrl(); $this->displayID = $project->sampleImages()->first()->id; // $this->applicationsCount = $project->projectApplications->count(); } public function getPlacesProperty() { $places = Location::select(['lat', 'lng', 'model_id', 'model_type']) ->where('model_id', $this->project->id) ->where('model_type', Project::class) ->hasCoordinates() ->with('model') ->get() ->map(function (Location $location) { return [ 'id' => $location->id, 'name' => $location->model->name, 'lat' => $location->lat, 'lng' => $location->lng, ]; }); return $places->all(); } public function getRecentPostsProperty() { return $this->project->posts()->take(2)->get(); } public function showPost($post) { return $this->redirectroute('catalyst-social.posts.show', $post['id']); } public function setImage(Media $media) { $this->displayUrl = $media->getFullUrl(); $this->displayID = $media->id; } public function resetAwardsSelection() { $this->reset('awardsToAdd'); } public function addUserAwards($userID) { $this->dispatch('add-awards-modal', type: 'open'); $this->userToAddAwardsTo = User::find($userID); } public function addAward(User $user) { $user->awards()->attach($this->awardsToAdd); $this->dispatch('notify', message: 'Awards Added', type: 'success'); $this->dispatch('add-awards-modal', type: 'close'); } public function getRemainingAwards(User $user) { return Award::whereNotIn('id', $user->awards()->pluck('awards.id')->toArray())->get(); } /** * If we decide to allow the project owners to decide if their project is public * or private then we can edit this method to account for that. */ public function getIsPublicProperty() { return false; } public function getIsMemberProperty() { return $this->project->hasUser(auth()->user()); } public function getCanViewProjectContentProperty() { if (Catalyst::isAllowingGuestAccess()) { return true; } return $this->isPublic || $this->isMember; } public function render() { return view('catalyst::livewire.pages.projects.show'); } }