text
stringlengths
184
4.48M
<script lang="ts"> export let title: string; export let description: string = ''; export let photoURL: string; export let technologies: string[] = []; export let extra: string; import IntersectionObserver from 'svelte-intersection-observer'; let element: HTMLElement; let display = false; </script> <IntersectionObserver {element} threshold={0.2} on:observe={(e) => { console.log(e.detail); // IntersectionObserverEntry console.log(e.detail.isIntersecting); // true | false display = e.detail.isIntersecting; }} > <!-- svelte-ignore a11y-click-events-have-key-events --> <div class="opacity-0 bg-gray-800 flex lg:flex-col flex-row pb-3 rounded-xl hover:shadow-2xl hover:shadow-black hover:scale-105 transition-all duration-700 cursor-pointer card mb-3 blur" on:click class:opacity-100={display} class:blur-none={display} class:translate-x-10={!display} bind:this={element} > <div class="absolute bottom-2 right-3 text-gray-400 font-bold font-mono text-sm">{extra}</div> <div class="w-1/3 lg:w-full"> <img src={photoURL} alt="" class="max-w-full h-auto rounded-t-xl" /> </div> <div class="w-2/3 lg:w-full"> <p class="text-white md:text-2xl text-lg font-bold ml-3 mt-3 transition-colors duration-500 title" > {title} </p> {#if description != ''} <p class="text-white max-w-fit mx-3 mt-2 text-base"> {description} </p> {/if} {#if technologies.length > 0} <ul class="flex flex-row gap-2 flex-wrap mt-5 mx-3 text-sm md:text-base w-10/12"> {#each technologies as tech} <li class="text-gray-400 font-light font-mono text-xs">{tech}</li> {/each} </ul> {/if} </div> </div> </IntersectionObserver> <style> .card:hover .title { color: #818cf8; } </style>
require('dotenv').config() import { BigNumber, utils } from 'ethers' import prompt from 'prompt' import { getAddBonderMessage, getRemoveBonderMessage, getSetL1GovernanceMessage, getSetAmmWrapperMessage, getSetL1BridgeAddressMessage, getSetL1BridgeCallerMessage, getAddActiveChainIdsMessage, getRemoveActiveChainIdsMessage, getSetMinimumForceCommitDelayMessage, getSetMaxPendingTransfersMessage, getSetHopBridgeTokenOwnerMessage, getSetMinimumBonderFeeRequirementsMessage, getSetMessengerMessage, getSetDefaultGasLimitUint256Message, getSetDefaultGasLimitUint32Message, getSetMessengerProxyMessage } from '../../test/shared/contractFunctionWrappers' const FUNCTIONS = { ADD_BONDER: 'addBonder', REMOVE_BONDER: 'removeBonder', SET_L1_GOVERNANCE: 'setL1Governance', SET_AMM_WRAPPER: 'setAmmWrapper', SET_L1_BRIDGE_ADDRESS: 'setL1BridgeAddress', SET_L1_BRIDGE_CALLER: 'setL1BridgeCaller', ADD_ACTIVE_CHAIN_IDS: 'addActiveChainIds', REMOVE_ACTIVE_CHAIN_IDS: 'removeActiveChainIds', SET_MINIMUM_FORCE_COMMIT_DELAY: 'setMinimumForceCommitDelay', SET_MAX_PENDING_TRANSFERS: 'setMaxPendingTransfers', SET_HOP_BRIDGE_TOKEN_OWNER: 'setHopBridgeTokenOwner', SET_MINIMUM_BONDER_FEE_REQUIREMENTS: 'setMinimumBonderFeeRequirements', SET_MESSENGER: 'setMessenger', SET_DEFAULT_GAS_LIMIT_256: 'setDefaultGasLimit256', SET_DEFAULT_GAS_LIMIT_32: 'setDefaultGasLimit32', SET_MESSENGER_PROXY: 'setMessengerProxy' } export async function getUpdateContractStateMessage (functionToCall: string, input: any) { const messageToSend: string = getMessageToSend(functionToCall, input) return messageToSend } const getMessageToSend = ( functionToCall: string, input: any ): string => { functionToCall = functionToCall.toLowerCase() switch(functionToCall) { case FUNCTIONS.ADD_BONDER.toLowerCase(): { return getAddBonderMessage(input) } case FUNCTIONS.REMOVE_BONDER.toLowerCase(): { return getRemoveBonderMessage(input) } case FUNCTIONS.SET_L1_GOVERNANCE.toLowerCase(): { return getSetL1GovernanceMessage(input) } case FUNCTIONS.SET_AMM_WRAPPER.toLowerCase(): { return getSetAmmWrapperMessage(input) } case FUNCTIONS.SET_L1_BRIDGE_ADDRESS.toLowerCase(): { return getSetL1BridgeAddressMessage(input) } case FUNCTIONS.SET_L1_BRIDGE_CALLER.toLowerCase(): { return getSetL1BridgeCallerMessage(input) } case FUNCTIONS.ADD_ACTIVE_CHAIN_IDS.toLowerCase(): { return getAddActiveChainIdsMessage([BigNumber.from(input)]) } case FUNCTIONS.REMOVE_ACTIVE_CHAIN_IDS.toLowerCase(): { return getRemoveActiveChainIdsMessage([BigNumber.from(input)]) } case FUNCTIONS.SET_MINIMUM_FORCE_COMMIT_DELAY.toLowerCase(): { return getSetMinimumForceCommitDelayMessage(input) } case FUNCTIONS.SET_MAX_PENDING_TRANSFERS.toLowerCase(): { return getSetMaxPendingTransfersMessage(input) } case FUNCTIONS.SET_HOP_BRIDGE_TOKEN_OWNER.toLowerCase(): { return getSetHopBridgeTokenOwnerMessage(input) } case FUNCTIONS.SET_MINIMUM_BONDER_FEE_REQUIREMENTS.toLowerCase(): { throw new Error('This function requires two inputs. Please manually enter the second input.') const firstInput: BigNumber = BigNumber.from(input) const secondInput: BigNumber = BigNumber.from('0') return getSetMinimumBonderFeeRequirementsMessage(firstInput, secondInput) } case FUNCTIONS.SET_MESSENGER.toLowerCase(): { return getSetMessengerMessage(input) } case FUNCTIONS.SET_DEFAULT_GAS_LIMIT_256.toLowerCase(): { return getSetDefaultGasLimitUint256Message(input) } case FUNCTIONS.SET_DEFAULT_GAS_LIMIT_32.toLowerCase(): { return getSetDefaultGasLimitUint32Message(input) } case FUNCTIONS.SET_MESSENGER_PROXY.toLowerCase(): { return getSetMessengerProxyMessage(input) } default: { throw new Error('Unknown function') } } }
/** * @file tpl_can_demo_driver.c * * @section desc File description * * See tpl_can_demo_driver.h for description. * * @section copyright Copyright * * Trampoline OS * * Trampoline is copyright (c) IRCCyN 2005+ * Trampoline is protected by the French intellectual property law. * * (C) BayLibre 2023 * * This software is distributed under the Lesser GNU Public Licence * * @section infos File informations * * $Date$ * $Rev$ * $Author$ * $URL$ */ #include <Can.h> #include <stdio.h> #include <string.h> #include <tpl_can_demo_driver.h> #include <tpl_os.h> static int can_demo_driver_init(struct tpl_can_controller_config_t *config); static int can_demo_driver_set_baudrate(struct tpl_can_controller_t *ctrl, CanControllerBaudrateConfig *baud_rate_config); static Std_ReturnType can_demo_driver_transmit(struct tpl_can_controller_t *ctrl, const Can_PduType *pdu_info); static Std_ReturnType can_demo_driver_receive(struct tpl_can_controller_t *ctrl, Can_PduType *pdu_info); static int can_demo_driver_is_data_available(struct tpl_can_controller_t *ctrl); struct can_demo_driver_priv { int is_can_fd_enabled; }; static struct can_demo_driver_priv can_demo_driver_controller_priv[2]; tpl_can_controller_t can_demo_driver_controller_1 = { 0x12341111, can_demo_driver_init, can_demo_driver_set_baudrate, can_demo_driver_transmit, can_demo_driver_receive, can_demo_driver_is_data_available, &can_demo_driver_controller_priv[0] }; tpl_can_controller_t can_demo_driver_controller_2 = { 0x12342222, can_demo_driver_init, can_demo_driver_set_baudrate, can_demo_driver_transmit, can_demo_driver_receive, can_demo_driver_is_data_available, &can_demo_driver_controller_priv[1] }; static int can_demo_driver_init(struct tpl_can_controller_config_t *config) { struct can_demo_driver_priv *priv = config->controller->priv; // Determine the CAN protocol version if (config->baud_rate_config.use_fd_configuration) priv->is_can_fd_enabled = 1; else priv->is_can_fd_enabled = 0; printf("[%s:%d] Initializing controller 0x%08X...\r\n", __func__, __LINE__, config->controller->base_address); printf("Protocol version : %s\r\nNominal baud rate : %u kbps\r\n", priv->is_can_fd_enabled ? "CAN-FD" : "CAN classic 2.0", config->baud_rate_config.CanControllerBaudRate); if (priv->is_can_fd_enabled) printf("Data baud rate (only for CAN-FD) : %u kbps\r\n", config->baud_rate_config.can_fd_config.CanControllerFdBaudRate); return 0; } static int can_demo_driver_set_baudrate(struct tpl_can_controller_t *ctrl, CanControllerBaudrateConfig *baud_rate_config) { printf("[%s:%d] Setting a new baud rate for controller 0x%08X. Protocol version : %s, nominal baud rate : %u kbps", __func__, __LINE__, ctrl->base_address, baud_rate_config->use_fd_configuration ? "CAN-FD" : "CAN classic 2.0", baud_rate_config->CanControllerBaudRate); if (baud_rate_config->use_fd_configuration) printf(", CAN-FD data baud rate : %u kbps", baud_rate_config->can_fd_config.CanControllerFdBaudRate); printf(".\r\n"); return 0; } static Std_ReturnType can_demo_driver_transmit(struct tpl_can_controller_t *ctrl, const Can_PduType *pdu_info) { uint32 i; printf("[%s:%d] Transmission request for controller 0x%08X, CAN ID = 0x%X, flags = 0x%02X, payload length = %u, payload = ", __func__, __LINE__, ctrl->base_address, pdu_info->id & TPL_CAN_ID_EXTENDED_MASK, TPL_CAN_ID_TYPE_GET(pdu_info->id), pdu_info->length); for (i = 0; i < pdu_info->length; i++) printf("0x%02X ", pdu_info->sdu[i]); printf("\r\n"); return 0; } static Std_ReturnType can_demo_driver_receive(struct tpl_can_controller_t *ctrl, Can_PduType *pdu_info) { if (ctrl->base_address == can_demo_driver_controller_1.base_address) { pdu_info->id = 0x1ab | TPL_CAN_ID_TYPE_STANDARD; // Random value strcpy((char *) pdu_info->sdu, "Test"); pdu_info->length = strlen((char *) pdu_info->sdu); } else if (ctrl->base_address == can_demo_driver_controller_2.base_address) { pdu_info->id = 0xcafeb0b | TPL_CAN_ID_TYPE_FD_EXTENDED; // Random value strcpy((char *) pdu_info->sdu, "The CAN-FD frame longer payload."); pdu_info->length = strlen((char *) pdu_info->sdu); } return E_OK; } static int can_demo_driver_is_data_available(struct tpl_can_controller_t *ctrl) { (void) ctrl; return 1; }
import PropTypes from "prop-types"; import { useState } from "react"; import { Navigate, useLocation } from "react-router-dom"; import useAuth from "../hooks/useAuth"; import Login from "../pages/auth/Login"; import LoadingScreen from "../components/LoadingScreen"; AuthGuard.propTypes = { children: PropTypes.node, }; export default function AuthGuard({ children }) { const { isAuthenticated, isInitialized } = useAuth(); const { pathname } = useLocation(); const [requestedLocation, setRequestedLocation] = useState(null); if (!isInitialized) { return <LoadingScreen />; } if (!isAuthenticated) { if (pathname !== requestedLocation) { setRequestedLocation(pathname); } return <Login />; } if (requestedLocation && pathname !== requestedLocation) { setRequestedLocation(null); return <Navigate to={requestedLocation} />; } return <>{children}</>; }
package exprs_test import ( "fmt" "reflect" "testing" exprs "github.com/evilsocket/opensnitch/daemon/firewall/nftables/exprs" "github.com/evilsocket/opensnitch/daemon/firewall/nftables/nftest" "github.com/google/nftables/expr" "golang.org/x/sys/unix" ) func TestExprProtocol(t *testing.T) { nftest.SkipIfNotPrivileged(t) conn, newNS := nftest.OpenSystemConn(t) defer nftest.CleanupSystemConn(t, newNS) nftest.Fw.Conn = conn testProtos := []string{ exprs.NFT_PROTO_TCP, exprs.NFT_PROTO_UDP, exprs.NFT_PROTO_UDPLITE, exprs.NFT_PROTO_SCTP, exprs.NFT_PROTO_DCCP, exprs.NFT_PROTO_ICMP, exprs.NFT_PROTO_ICMPv6, } protoValues := []byte{ unix.IPPROTO_TCP, unix.IPPROTO_UDP, unix.IPPROTO_UDPLITE, unix.IPPROTO_SCTP, unix.IPPROTO_DCCP, unix.IPPROTO_ICMP, unix.IPPROTO_ICMPV6, } for idx, proto := range testProtos { t.Run(fmt.Sprint("test-protoExpr-", proto), func(t *testing.T) { protoExpr, err := exprs.NewExprProtocol(proto) if err != nil { t.Errorf("%s - Error creating expr Log: %s", proto, protoExpr) return } r, _ := nftest.AddTestRule(t, conn, protoExpr) if r == nil { t.Errorf("Error adding rule with proto %s expression", proto) } if len(r.Exprs) != 2 { t.Errorf("%s - expected 2 Expressions, found %d", proto, len(r.Exprs)) } e := r.Exprs[0] meta, ok := e.(*expr.Meta) if !ok { t.Errorf("%s - invalid proto expr: %T", proto, e) } //fmt.Printf("%s, %+v\n", reflect.TypeOf(e).String(), e) if reflect.TypeOf(e).String() != "*expr.Meta" { t.Errorf("%s - first expression should be *expr.Meta, instead of: %s", proto, reflect.TypeOf(e)) } if meta.Key != expr.MetaKeyL4PROTO { t.Errorf("%s - invalid proto expr.Meta.Key: %d", proto, expr.MetaKeyL4PROTO) } e = r.Exprs[1] cmp, ok := e.(*expr.Cmp) if !ok { t.Errorf("%s - invalid proto cmp expr: %T", proto, e) } //fmt.Printf("%s, %+v\n", reflect.TypeOf(e).String(), e) if reflect.TypeOf(e).String() != "*expr.Cmp" { t.Errorf("%s - second expression should be *expr.Cmp, instead of: %s", proto, reflect.TypeOf(e)) } if cmp.Op != expr.CmpOpEq { t.Errorf("%s - expr.Cmp should be CmpOpEq, instead of: %d", proto, cmp.Op) } if cmp.Data[0] != protoValues[idx] { t.Errorf("%s - expr.Data differs: %d<->%d", proto, cmp.Data, protoValues[idx]) } }) } }
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:level_map_example/LevelMapSDK/src/model/bg_image.dart'; import 'package:level_map_example/LevelMapSDK/src/model/image_details.dart'; import 'package:level_map_example/LevelMapSDK/src/model/images_to_paint.dart'; import 'package:level_map_example/LevelMapSDK/src/model/level_map_params.dart'; import 'package:level_map_example/LevelMapSDK/src/model/student_model.dart'; import 'package:level_map_example/LevelMapSDK/src/utils/image_offset_extension.dart'; import 'package:level_map_example/main.dart'; import 'dart:math' as math; class LevelMapPainter extends CustomPainter { final LevelMapParams params; final ImagesToPaint? imagesToPaint; final Paint _pathPaint; final Paint _shadowPaint; /// Describes the fraction to reach next level. /// If the [LevelMapParams.currentLevel] is 6.5, [_nextLevelFraction] is 0.5. final double _nextLevelFraction; LevelMapPainter({required this.params, this.imagesToPaint}) : _pathPaint = Paint() ..strokeWidth = params.pathStrokeWidth ..color = params.pathColor ..strokeCap = StrokeCap.round, _shadowPaint = Paint() ..strokeWidth = params.pathStrokeWidth ..color = params.pathColor.withOpacity(0.2) ..strokeCap = StrokeCap.round, _nextLevelFraction = params.currentLevel.remainder(params.currentLevel.floor()); @override void paint(Canvas canvas, Size size) { canvas.save(); canvas.translate(0, size.height); if (imagesToPaint != null) { _drawBGImages(canvas); _drawStartLevelImage(canvas, size.width); _drawPathEndImage(canvas, size.width, size.height); } final double _centerWidth = size.width / 2; double _p2_dx_VariationFactor = params.firstCurveReferencePointOffsetFactor!.dx; double _p2_dy_VariationFactor = params.firstCurveReferencePointOffsetFactor!.dy; for (int thisLevel = 0; thisLevel < params.levelCount; thisLevel++) { final Offset p1 = Offset(_centerWidth, -(thisLevel * params.levelHeight)); final Offset p2 = getP2OffsetBasedOnCurveSide(thisLevel, _p2_dx_VariationFactor, _p2_dy_VariationFactor, _centerWidth); final Offset p3 = Offset(_centerWidth, -((thisLevel * params.levelHeight) + params.levelHeight)); _drawBezierCurve(canvas, p1, p2, p3, thisLevel + 1); if (params.enableVariationBetweenCurves) { _p2_dx_VariationFactor = _p2_dx_VariationFactor + params.curveReferenceOffsetVariationForEachLevel[thisLevel].dx; _p2_dy_VariationFactor = _p2_dy_VariationFactor + params.curveReferenceOffsetVariationForEachLevel[thisLevel].dy; } } canvas.restore(); } void _drawBGImages(Canvas canvas) { final List<BGImage>? _bgImages = imagesToPaint!.bgImages; if (_bgImages != null) { _bgImages.forEach((bgImage) { bgImage.offsetsToBePainted.forEach((offset) { _paintImage(canvas, bgImage.imageDetails, offset); }); }); } } void _drawStartLevelImage(Canvas canvas, double canvasWidth) { if (imagesToPaint!.startLevelImage != null) { final ImageDetails _startLevelImage = imagesToPaint!.startLevelImage!; final Offset _offset = Offset(canvasWidth / 2, 0).toBottomCenter(_startLevelImage.size); _paintImage(canvas, _startLevelImage, _offset); } } void _drawPathEndImage(Canvas canvas, double canvasWidth, double canvasHeight) { if (imagesToPaint!.pathEndImage != null) { final ImageDetails _pathEndImage = imagesToPaint!.pathEndImage!; final Offset _offset = Offset(canvasWidth / 2, -canvasHeight).toTopCenter(_pathEndImage.size.width); _paintImage(canvas, _pathEndImage, _offset); } } Offset getP2OffsetBasedOnCurveSide(int thisLevel, double p2_dx_VariationFactor, double p2_dy_VariationFactor, double centerWidth) { final double clamped_dxFactor = p2_dx_VariationFactor.clamp(params.minReferencePositionOffsetFactor.dx, params.maxReferencePositionOffsetFactor.dx); final double clamped_dyFactor = p2_dy_VariationFactor.clamp(params.minReferencePositionOffsetFactor.dy, params.maxReferencePositionOffsetFactor.dy); final double p2_dx = thisLevel.isEven ? centerWidth * (1 - clamped_dxFactor) : centerWidth + (centerWidth * clamped_dxFactor); final double p2_dy = -((thisLevel * params.levelHeight) + (params.levelHeight * (thisLevel.isEven ? clamped_dyFactor : 1 - clamped_dyFactor))); return Offset(p2_dx, p2_dy); } void _drawBezierCurve(Canvas canvas, Offset p1, Offset p2, Offset p3, int thisLevel) { final double _dashFactor = params.dashLengthFactor; //TODO: Customise the empty dash length with this multiplication factor 2. for (double t = _dashFactor; t <= 1; t += _dashFactor * 2) { Offset offset1 = Offset(_compute(t, p1.dx, p2.dx, p3.dx), _compute(t, p1.dy, p2.dy, p3.dy)); Offset offset2 = Offset(_compute(t + _dashFactor, p1.dx, p2.dx, p3.dx), _compute(t + _dashFactor, p1.dy, p2.dy, p3.dy)); canvas.drawLine(offset1, offset2, _pathPaint); if (params.showPathShadow) { canvas.drawLine(Offset(offset1.dx + params.shadowDistanceFromPathOffset.dx, offset1.dy + params.shadowDistanceFromPathOffset.dy), Offset(offset2.dx + params.shadowDistanceFromPathOffset.dx, offset2.dy + params.shadowDistanceFromPathOffset.dy), _shadowPaint); } } if (imagesToPaint != null) { final Offset _offsetToPaintImage = Offset(_compute(0.5, p1.dx, p2.dx, p3.dx), _compute(0.5, p1.dy, p2.dy, p3.dy)); ImageDetails imageDetails; // if (params.currentLevel >= thisLevel) { // imageDetails = imagesToPaint!.completedLevelImage; // } else {} imageDetails = imagesToPaint!.lockedLevelImage; _paintLevelNo(canvas, imageDetails, _offsetToPaintImage.toBottomCenter(imageDetails.size), thisLevel); for (var element in params.studentLevelList) { if (element.currentLevel == thisLevel) { _paintStudentCurrentLevel( canvas, imagesToPaint!.currentLevelImage, _offsetToPaintImage.toCenter(imagesToPaint!.currentLevelImage.size), element); } } final double _curveFraction; final int _flooredCurrentLevel = params.currentLevel.floor(); if (_flooredCurrentLevel == thisLevel && _nextLevelFraction <= 0.5) { _curveFraction = 0.5 + _nextLevelFraction; // _paintImage(canvas, imagesToPaint!.currentLevelImage, _offsetToPaintImage.toCenter(imageDetails.size)); } else if (_flooredCurrentLevel == thisLevel - 1 && _nextLevelFraction > 0.5) { _curveFraction = _nextLevelFraction - 0.5; } else { return; } // final Offset _offsetToPaintCurrentLevelImage = // Offset(_compute(_curveFraction, p1.dx, p2.dx, p3.dx), _compute(_curveFraction, p1.dy, p2.dy, p3.dy)); // _paintImage(canvas, imagesToPaint!.currentLevelImage, _offsetToPaintCurrentLevelImage.toBottomCenter(imageDetails.size)); } } void _paintImage(Canvas canvas, ImageDetails imageDetails, Offset offset) { paintImage( canvas: canvas, rect: Rect.fromLTWH(offset.dx, offset.dy, imageDetails.size.width, imageDetails.size.height), image: imageDetails.imageInfo.image, ); } void _paintLevelNo(Canvas canvas, ImageDetails imageDetails, Offset offset, int levelNo) { final textPainter = TextPainter( text: TextSpan( text: levelNo.toString(), style: GoogleFonts.alfaSlabOne( color: kPrimary, fontSize: 24, ), ), textDirection: TextDirection.ltr, textAlign: TextAlign.center); textPainter.layout(); paintImage( canvas: canvas, rect: Rect.fromLTWH(offset.dx, offset.dy, imageDetails.size.width, imageDetails.size.height), image: imageDetails.imageInfo.image, ); textPainter.paint(canvas, Offset((offset.dx + (levelNo < 10 ? 16 : 8)), offset.dy + 14)); } void _paintStudentCurrentLevel(Canvas canvas, ImageDetails imageDetails, Offset offset, StudentModel student) { final namePainter = TextPainter( text: TextSpan( text: "${student.name}\n${student.currentLevel}th Level", style: GoogleFonts.josefinSans( color: kPrimary, fontSize: 14, fontWeight: FontWeight.bold, ), ), textDirection: TextDirection.ltr, textAlign: TextAlign.start); namePainter.layout(); Offset _offset = Offset(offset.dx + 40, offset.dy - 75); paintImage( canvas: canvas, rect: Rect.fromLTWH(_offset.dx, _offset.dy, imageDetails.size.width, imageDetails.size.height), image: imageDetails.imageInfo.image, ); // Offset centerOffset = Offset(_offset.dx + imageDetails.size.width / 2.0, _offset.dy + imageDetails.size.height / 2.0); namePainter.paint(canvas, Offset(_offset.dx + 20, _offset.dy + 25)); // namePainter.paint(canvas, centerOffset); // namePainter.paint(canvas, Offset((offset.dx + (student.currentLevel < 10 ? 16 : 8)), offset.dy + 14)); } double _compute(double t, double p1, double p2, double p3) { ///To learn about these parameters, visit https://en.wikipedia.org/wiki/B%C3%A9zier_curve return (((1 - t) * (1 - t) * p1) + (2 * (1 - t) * t * p2) + (t * t) * p3); } @override bool shouldRepaint(covariant LevelMapPainter oldDelegate) => oldDelegate.imagesToPaint != imagesToPaint; }
import 'package:cafe_hollywood/screens/MainTab/main_tab.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:intl_phone_field/phone_number.dart'; class AuthService { final FirebaseAuth _auth = FirebaseAuth.instance; bool get isAuth { return _auth.currentUser != null; } String get customerID { return _auth.currentUser?.uid ?? ""; } String get displayName { return _auth.currentUser?.displayName ?? ''; } String get phoneNumber { return _auth.currentUser?.phoneNumber ?? ''; } String? _currentUID(User? user) { return user != null ? user.uid : null; } Stream<String?> get currentUserID { return _auth.authStateChanges().map(_currentUID); } Future signInAnon() async { try { UserCredential result = await _auth.signInAnonymously(); User? user = result.user; return user?.uid; } catch (error) { print('error signing in ${error.toString()}'); // print(error.toString()); return null; } } Future signInWithPhone() async {} Future signOut() async { _auth.signOut(); } Future createUserWithPhone( String phone, String? displayName, BuildContext context) async { _auth.verifyPhoneNumber( phoneNumber: phone, timeout: Duration(seconds: 0), verificationCompleted: (AuthCredential authCredential) { _auth .signInWithCredential(authCredential) .then((UserCredential result) { Navigator.of(context).pop(); // to pop the dialog box Navigator.of(context).pushReplacementNamed('/home'); }).catchError((e) { // return e.toString(); print(e.toString()); }); }, verificationFailed: (FirebaseAuthException exception) { print(exception.toString()); }, codeSent: (String verificationId, int? forceResendingToken) { final _codeController = TextEditingController(); showDialog( context: context, barrierDismissible: false, builder: (context) => AlertDialog( title: Text("Enter Verification Code From Text Message"), content: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[TextField(controller: _codeController)], ), actions: <Widget>[ FlatButton( child: Text("submit"), textColor: Colors.white, color: Colors.black, onPressed: () { var _credential = PhoneAuthProvider.credential( verificationId: verificationId, smsCode: _codeController.text.trim()); _auth .signInWithCredential(_credential) .then((UserCredential result) { if (displayName != null && _auth.currentUser != null) { _auth.currentUser! .updateProfile(displayName: displayName); } Navigator.of(context).pop(); // to pop the dialog box Navigator.push( context, CupertinoPageRoute( builder: (context) => MainTabBar())); // Navigator.of(context).pushReplacementNamed('/home'); }).catchError((e) { return "error"; }); }, ) ], ), ); }, codeAutoRetrievalTimeout: (String verificationId) { verificationId = verificationId; }); } }
import { res, dbDataResponse } from "../../assets/types/types" import { Server } from '../../server/server'; const { randomUUID } = require("crypto"); import { dbTables, dbTable } from '../../assets/types/types' import { Model, Op } from 'sequelize'; export class ClientSelects { private UUID = randomUUID; private getTable (name : string) : dbTable | undefined { console.log(Server.getDatabaseTables()) const aux = Server.getDatabaseTables().find((model) => name == model.getTableName()) return aux; } private response (status : boolean, message : string, data? : any) { if (status) { return { OK : status, message : message, data: data } }else { return { OK : false, messageError : message } } } public get_pizzas() { const pizzas = this.getTable('PIZZAs') const category = this.getTable('CATEGORies') if (typeof pizzas != 'undefined' && typeof category != 'undefined') { return category.findAll( { include : pizzas, }) .then((data) => this.response(true, 'All pizzas', data)) .catch((error : Error) => this.response(false, error.message)) } else return this.response(false, 'type of model is undefined') } public get_only_pizza() { const pizzas = this.getTable('PIZZAs') if (typeof pizzas != 'undefined') { return pizzas.findAll() .then((data) => this.response(true, 'All pizzas', data)) .catch((error : Error) => this.response(false, error.message)) } else return this.response(false, 'type of model is undefined') } async getAccount(any : string | number, password : string) { const client = this.getTable('CLIENTs') if(typeof client != 'undefined') { return await client.findOne({ where: { [Op.or]: [ { EMAIL: any }, { PHONE_NUMBER: any }, ], PASS_WORD: password, } }) .then((data) => data ? this.response(true, 'Logado com sucesso!', data) : this.response(false, 'Email ou senha errada')) .catch((error : Error) => this.response(false, error.name)) } return this.response(false, 'Error: model is type of undefined : (') } public get_info_pizza(pizzaID : string ) { const pizzas = this.getTable('PIZZAs') const category = this.getTable('CATEGORies') const igredients = this.getTable('IGREDIENTs') if(typeof pizzas != 'undefined' && typeof category != 'undefined' && typeof igredients != 'undefined' ) { return pizzas.findByPk(pizzaID, { include : [category ,igredients] }).then((data) => this.response(true, 'pizza', data)) .catch((error :Error) => this.response(false, error.message)) } else return 'type of model is undefined' } public get_pizza_cart(clientID : string) { const cart = this.getTable('CARTs') const pizzas = this.getTable('PIZZAs') if(typeof pizzas != 'undefined' && typeof cart != 'undefined' ) { return cart.findAll( { where : {CLIENTID : clientID}, include : [pizzas] }).then((data) => data) .catch((error :Error) => error.message) } else return 'type of model is undefined' } public count_cart(clientID : string) { const cart = this.getTable('CARTs') if(typeof cart != 'undefined' ) { return cart.count( { where : {CLIENTID : clientID}, }).then((num) => this.response(true, 'all products on cart', num) ) .catch((error :Error) => this.response(false, error.message)) } else return 'type of model is undefined' } public get_cart(clientID : string) { const cart = this.getTable('CARTs') const pizzas = this.getTable('PIZZAs') if(typeof cart != 'undefined' && typeof pizzas != 'undefined') { return cart.findAll( { where : {CLIENTID : clientID}, include : [pizzas] }).then((data) => this.response(true, 'all products on cart', {products : data, counter : data.length}) ) .catch((error :Error) => this.response(false, error.message)) } else return 'type of model is undefined' } public get_orders(clientID : string) { const orders = this.getTable('ORDERs') const items = this.getTable('ORDER_ITEMs') if(typeof orders != 'undefined' && typeof items != 'undefined') { return orders.findAll( { where : {CLIENTID : clientID}, include : [items] }).then((data) => this.response(true, 'all orders', data) ) .catch((error :Error) => this.response(false, error.message)) } else return 'type of model is undefined' } }
#!/usr/bin/env python3 import torch import pandas as pd from dataset import * import pdb from medcam import medcam import matplotlib.pyplot as plt from itertools import chain from tqdm import tqdm from vae_3d import VAE_regressor from bids.layout import BIDSLayout from sklearn.linear_model import LinearRegression import seaborn as sns import sys img = sys.argv[1] output = sys.argv[2] try: mni = sys.argv[3] print(f'Reading MNI spaced image(s): {img}') print(f'Output will be saved to: {output}') except: mni = 'native' print(f'Reading Native spaced image(s): {img}') print(f'Output will be saved to: {output}') print('Warning!! Brain age might not be accurate if the image is not MNI Spaced. The code will help you convert the inference image to the MNI space if it is not.') ''' Example Usage: wmba /ix1/tibrahim/jil202/ratiomap/img/derivatives/ratiomap/639_20200128135731/wm_639_20200128135731_ratio.nii.gz /ix1/tibrahim/jil202/ratiomap/img/derivatives/ratiomap/639_20200128135731/wm_639_20200128135731_ratio_wmba.csv wmba /ix1/tibrahim/jil202/ratiomap/img/derivatives/ratiomap/639_20200128135731/mni_639_20200128135731_ratio.nii.gz /ix1/tibrahim/jil202/ratiomap/img/derivatives/ratiomap/639_20200128135731/wm_639_20200128135731_ratio_wmba.csv MNI ''' wm_path = natsorted(glob.glob(f'{img}')) if mni == 'MNI': wm_dataset = ratio_dataset(wm_path, MNI=True) else: wm_dataset = ratio_dataset(wm_path, MNI=False) wm_loader = DataLoader(wm_dataset, batch_size=1, shuffle=False) device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') class agePrediction(torch.nn.Module): def __init__(self, pretrainedModel): super(agePrediction, self).__init__() pretrainedModel.eval() self.encoder = pretrainedModel.encoder self.z_mean = pretrainedModel.z_mean self.z_log_sigma = pretrainedModel.z_log_sigma self.regressor = pretrainedModel.regressor def forward(self, x): img = x x = self.encoder(img) x = torch.flatten(x, start_dim=1) z_mean = self.z_mean(x) z_log_sigma = self.z_log_sigma(x) r_predict = self.regressor(torch.unsqueeze(torch.cat((z_mean, z_log_sigma),1),2)) return r_predict wm_model = torch.load('/ix1/haizenstein/jil202/wm_VAE/trained_model/pytorch/model/2-8VAE_wm_HCP_105.pth', map_location=device) wm_model = wm_model.to(device) wm_model.eval() wm_model = agePrediction(wm_model) age_prediction = [] IDs = [] for idx, [img, ID] in enumerate(tqdm(wm_loader)): IDs.append(list(ID)) img = torch.unsqueeze(img, 1).float().to(device) brainAge = [age.item() for age in wm_model(img).detach().cpu()] age_prediction.append(brainAge) age_prediction = list(chain.from_iterable(age_prediction)) IDs = list(chain.from_iterable(IDs)) predictedModel = {"SubjectID": IDs, "wm_brainAge":age_prediction} predictedModel = pd.DataFrame(predictedModel) predictedModel.to_csv(f'{output}')
package com.masterproject.musigame.images; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import static com.masterproject.musigame.images.ImageMother.Images.ids; import static com.masterproject.musigame.images.ImageMother.imageBuilder; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; @Tag("unit") @Tag("service") @DisplayName("Images service should") class ImagesServiceTests { private ImagesService service; private InMemoryImagesRepository repository; private final ImageId KNOWN_IMAGE_ID = ids().sample(); @BeforeEach void setUp() { repository = new InMemoryImagesRepository(KNOWN_IMAGE_ID); service = new ImagesService(repository); } @Test @DisplayName("get an image with known ImageId") void getImageWithKnownImageId() { Image expected = imageBuilder(KNOWN_IMAGE_ID).build(); var actual = service.findById(KNOWN_IMAGE_ID); assertThat(actual.get().getImageId().getValue()).isEqualTo(expected.getImageId().getValue()); } @Test @DisplayName("get all images") void getAllImages() { var actual = service.findAll(); assertThat(actual.get().size()).isGreaterThan(0); } @Test @DisplayName("not get an image with unknown ImageId") void notGetImageWithUnknownImageId() { var actual = service.findById(ids().sample()); assertThat(actual).isEmpty(); } @Test @DisplayName("throw an exception when ImageId is null") void throwExceptionWhenImageIdIsNull() { assertThrows(IllegalArgumentException.class, () -> service.findById(null)); } }
/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include "PrecompiledHeadersServer.h" #include "LuaScripting.h" #include "ServerContext.h" #include "OrthancInitialization.h" #include "../Core/Lua/LuaFunctionCall.h" #include "../Core/HttpServer/StringHttpOutput.h" #include "Scheduler/DeleteInstanceCommand.h" #include "Scheduler/StoreScuCommand.h" #include "Scheduler/StorePeerCommand.h" #include "Scheduler/ModifyInstanceCommand.h" #include "Scheduler/CallSystemCommand.h" #include "OrthancRestApi/OrthancRestApi.h" #include <glog/logging.h> #include <EmbeddedResources.h> namespace Orthanc { ServerContext* LuaScripting::GetServerContext(lua_State *state) { const void* value = LuaContext::GetGlobalVariable(state, "_ServerContext"); return const_cast<ServerContext*>(reinterpret_cast<const ServerContext*>(value)); } // Syntax in Lua: RestApiGet(uri, builtin) int LuaScripting::RestApiGet(lua_State *state) { ServerContext* serverContext = GetServerContext(state); if (serverContext == NULL) { LOG(ERROR) << "Lua: The Orthanc API is unavailable"; lua_pushnil(state); return 1; } // Check the types of the arguments int nArgs = lua_gettop(state); if ((nArgs != 1 && nArgs != 2) || !lua_isstring(state, 1) || // URI (nArgs == 2 && !lua_isboolean(state, 2))) // Restrict to built-in API? { LOG(ERROR) << "Lua: Bad parameters to RestApiGet()"; lua_pushnil(state); return 1; } const char* uri = lua_tostring(state, 1); bool builtin = (nArgs == 2 ? lua_toboolean(state, 2) : false); std::string result; if (HttpToolbox::SimpleGet(result, serverContext->GetHttpHandler().RestrictToOrthancRestApi(builtin), uri)) { lua_pushlstring(state, result.c_str(), result.size()); } else { LOG(ERROR) << "Lua: Error in RestApiGet() for URI: " << uri; lua_pushnil(state); } return 1; } int LuaScripting::RestApiPostOrPut(lua_State *state, bool isPost) { ServerContext* serverContext = GetServerContext(state); if (serverContext == NULL) { LOG(ERROR) << "Lua: The Orthanc API is unavailable"; lua_pushnil(state); return 1; } // Check the types of the arguments int nArgs = lua_gettop(state); if ((nArgs != 2 && nArgs != 3) || !lua_isstring(state, 1) || // URI !lua_isstring(state, 2) || // Body (nArgs == 3 && !lua_isboolean(state, 3))) // Restrict to built-in API? { LOG(ERROR) << "Lua: Bad parameters to " << (isPost ? "RestApiPost()" : "RestApiPut()"); lua_pushnil(state); return 1; } const char* uri = lua_tostring(state, 1); size_t bodySize = 0; const char* bodyData = lua_tolstring(state, 2, &bodySize); bool builtin = (nArgs == 3 ? lua_toboolean(state, 3) : false); std::string result; if (isPost ? HttpToolbox::SimplePost(result, serverContext->GetHttpHandler().RestrictToOrthancRestApi(builtin), uri, bodyData, bodySize) : HttpToolbox::SimplePut(result, serverContext->GetHttpHandler().RestrictToOrthancRestApi(builtin), uri, bodyData, bodySize)) { lua_pushlstring(state, result.c_str(), result.size()); } else { LOG(ERROR) << "Lua: Error in " << (isPost ? "RestApiPost()" : "RestApiPut()") << " for URI: " << uri; lua_pushnil(state); } return 1; } // Syntax in Lua: RestApiPost(uri, body, builtin) int LuaScripting::RestApiPost(lua_State *state) { return RestApiPostOrPut(state, true); } // Syntax in Lua: RestApiPut(uri, body, builtin) int LuaScripting::RestApiPut(lua_State *state) { return RestApiPostOrPut(state, false); } // Syntax in Lua: RestApiDelete(uri, builtin) int LuaScripting::RestApiDelete(lua_State *state) { ServerContext* serverContext = GetServerContext(state); if (serverContext == NULL) { LOG(ERROR) << "Lua: The Orthanc API is unavailable"; lua_pushnil(state); return 1; } // Check the types of the arguments int nArgs = lua_gettop(state); if ((nArgs != 1 && nArgs != 2) || !lua_isstring(state, 1) || // URI (nArgs == 2 && !lua_isboolean(state, 2))) // Restrict to built-in API? { LOG(ERROR) << "Lua: Bad parameters to RestApiDelete()"; lua_pushnil(state); return 1; } const char* uri = lua_tostring(state, 1); bool builtin = (nArgs == 2 ? lua_toboolean(state, 2) : false); if (HttpToolbox::SimpleDelete(serverContext->GetHttpHandler().RestrictToOrthancRestApi(builtin), uri)) { lua_pushboolean(state, 1); } else { LOG(ERROR) << "Lua: Error in RestApiDelete() for URI: " << uri; lua_pushnil(state); } return 1; } IServerCommand* LuaScripting::ParseOperation(const std::string& operation, const Json::Value& parameters) { if (operation == "delete") { LOG(INFO) << "Lua script to delete resource " << parameters["Resource"].asString(); return new DeleteInstanceCommand(context_); } if (operation == "store-scu") { std::string localAet; if (parameters.isMember("LocalAet")) { localAet = parameters["LocalAet"].asString(); } else { localAet = context_.GetDefaultLocalApplicationEntityTitle(); } std::string modality = parameters["Modality"].asString(); LOG(INFO) << "Lua script to send resource " << parameters["Resource"].asString() << " to modality " << modality << " using Store-SCU"; return new StoreScuCommand(context_, localAet, Configuration::GetModalityUsingSymbolicName(modality), true); } if (operation == "store-peer") { std::string peer = parameters["Peer"].asString(); LOG(INFO) << "Lua script to send resource " << parameters["Resource"].asString() << " to peer " << peer << " using HTTP"; OrthancPeerParameters parameters; Configuration::GetOrthancPeer(parameters, peer); return new StorePeerCommand(context_, parameters, true); } if (operation == "modify") { LOG(INFO) << "Lua script to modify resource " << parameters["Resource"].asString(); DicomModification modification; OrthancRestApi::ParseModifyRequest(modification, parameters); std::auto_ptr<ModifyInstanceCommand> command(new ModifyInstanceCommand(context_, modification)); return command.release(); } if (operation == "call-system") { LOG(INFO) << "Lua script to call system command on " << parameters["Resource"].asString(); const Json::Value& argsIn = parameters["Arguments"]; if (argsIn.type() != Json::arrayValue) { throw OrthancException(ErrorCode_BadParameterType); } std::vector<std::string> args; args.reserve(argsIn.size()); for (Json::Value::ArrayIndex i = 0; i < argsIn.size(); ++i) { // http://jsoncpp.sourceforge.net/namespace_json.html#7d654b75c16a57007925868e38212b4e switch (argsIn[i].type()) { case Json::stringValue: args.push_back(argsIn[i].asString()); break; case Json::intValue: args.push_back(boost::lexical_cast<std::string>(argsIn[i].asInt())); break; case Json::uintValue: args.push_back(boost::lexical_cast<std::string>(argsIn[i].asUInt())); break; case Json::realValue: args.push_back(boost::lexical_cast<std::string>(argsIn[i].asFloat())); break; default: throw OrthancException(ErrorCode_BadParameterType); } } return new CallSystemCommand(context_, parameters["Command"].asString(), args); } throw OrthancException(ErrorCode_ParameterOutOfRange); } void LuaScripting::InitializeJob() { lua_.Execute("_InitializeJob()"); } void LuaScripting::SubmitJob(const std::string& description) { Json::Value operations; LuaFunctionCall call2(lua_, "_AccessJob"); call2.ExecuteToJson(operations); if (operations.type() != Json::arrayValue) { throw OrthancException(ErrorCode_InternalError); } ServerJob job; ServerCommandInstance* previousCommand = NULL; for (Json::Value::ArrayIndex i = 0; i < operations.size(); ++i) { if (operations[i].type() != Json::objectValue || !operations[i].isMember("Operation")) { throw OrthancException(ErrorCode_InternalError); } const Json::Value& parameters = operations[i]; std::string operation = parameters["Operation"].asString(); ServerCommandInstance& command = job.AddCommand(ParseOperation(operation, operations[i])); if (!parameters.isMember("Resource")) { throw OrthancException(ErrorCode_InternalError); } std::string resource = parameters["Resource"].asString(); if (resource.empty()) { previousCommand->ConnectOutput(command); } else { command.AddInput(resource); } previousCommand = &command; } job.SetDescription(description); context_.GetScheduler().Submit(job); } LuaScripting::LuaScripting(ServerContext& context) : context_(context) { lua_.SetGlobalVariable("_ServerContext", &context); lua_.RegisterFunction("RestApiGet", RestApiGet); lua_.RegisterFunction("RestApiPost", RestApiPost); lua_.RegisterFunction("RestApiPut", RestApiPut); lua_.RegisterFunction("RestApiDelete", RestApiDelete); lua_.Execute(Orthanc::EmbeddedResources::LUA_TOOLBOX); lua_.SetHttpProxy(Configuration::GetGlobalStringParameter("HttpProxy", "")); } void LuaScripting::ApplyOnStoredInstance(const std::string& instanceId, const Json::Value& simplifiedTags, const Json::Value& metadata, const std::string& remoteAet, const std::string& calledAet) { static const char* NAME = "OnStoredInstance"; if (lua_.IsExistingFunction(NAME)) { InitializeJob(); LuaFunctionCall call(lua_, NAME); call.PushString(instanceId); call.PushJson(simplifiedTags); call.PushJson(metadata); call.PushJson(remoteAet); call.PushJson(calledAet); call.Execute(); SubmitJob(std::string("Lua script: ") + NAME); } } void LuaScripting::SignalStoredInstance(const std::string& publicId, DicomInstanceToStore& instance, const Json::Value& simplifiedTags) { boost::recursive_mutex::scoped_lock lock(mutex_); Json::Value metadata = Json::objectValue; for (ServerIndex::MetadataMap::const_iterator it = instance.GetMetadata().begin(); it != instance.GetMetadata().end(); ++it) { if (it->first.first == ResourceType_Instance) { metadata[EnumerationToString(it->first.second)] = it->second; } } ApplyOnStoredInstance(publicId, simplifiedTags, metadata, instance.GetRemoteAet(), instance.GetCalledAet()); } void LuaScripting::OnStableResource(const ServerIndexChange& change) { const char* name; switch (change.GetChangeType()) { case ChangeType_StablePatient: name = "OnStablePatient"; break; case ChangeType_StableStudy: name = "OnStableStudy"; break; case ChangeType_StableSeries: name = "OnStableSeries"; break; default: throw OrthancException(ErrorCode_InternalError); } Json::Value tags, metadata; if (context_.GetIndex().LookupResource(tags, change.GetPublicId(), change.GetResourceType()) && context_.GetIndex().GetMetadata(metadata, change.GetPublicId())) { boost::recursive_mutex::scoped_lock lock(mutex_); if (lua_.IsExistingFunction(name)) { InitializeJob(); LuaFunctionCall call(lua_, name); call.PushString(change.GetPublicId()); call.PushJson(tags["MainDicomTags"]); call.PushJson(metadata); call.Execute(); SubmitJob(std::string("Lua script: ") + name); } } } void LuaScripting::SignalChange(const ServerIndexChange& change) { if (change.GetChangeType() == ChangeType_StablePatient || change.GetChangeType() == ChangeType_StableStudy || change.GetChangeType() == ChangeType_StableSeries) { OnStableResource(change); } } bool LuaScripting::FilterIncomingInstance(const Json::Value& simplified, const std::string& remoteAet) { static const char* NAME = "ReceivedInstanceFilter"; boost::recursive_mutex::scoped_lock lock(mutex_); if (lua_.IsExistingFunction(NAME)) { LuaFunctionCall call(lua_, NAME); call.PushJson(simplified); call.PushString(remoteAet); if (!call.ExecutePredicate()) { return false; } } return true; } void LuaScripting::Execute(const std::string& command) { LuaScripting::Locker locker(*this); if (locker.GetLua().IsExistingFunction(command.c_str())) { LuaFunctionCall call(locker.GetLua(), command.c_str()); call.Execute(); } } }
#This code examines the difference between DE K27 targets which are DM or not. #It uses the DE gene lists generated in 10_RNAseqAnalysis and 06_featureCountsGeneLists #Author: Lea Faivre #Date: 231031 # Libraries ----------------------------------------------------------------------------------- library(readxl) library(tidyverse) library(RColorBrewer) library(xlsx) library(dplyr) library(tidyr) library(ggplot2) library(rio) library(ggvenn) library(ggpubr) # Data import --------------------------------------------------------------------------------- DE_FC <- list( h = read_excel("Data/RNAseq_Nvs3h.xlsx") %>% select(Gene, log2FoldChange) %>% dplyr::rename(DE_FC_3h = log2FoldChange), d = read_excel("Data/RNAseq_Nvs3d.xlsx") %>% select(Gene, log2FoldChange) %>% dplyr::rename(DE_FC_3d = log2FoldChange)) DMGenes <- import_list("Data/DMGenes_FC.xlsx", setclass = "tbl") DMGenes <- lapply(DMGenes, function(x){ x %>% select(Gene, log2FCNvs3h, log2FCNvs3d, Name) }) DEGenes <- import_list("Data/DEGenes.xlsx", setclass = "tbl") DE <- list("h_UP" = DEGenes$Nvs3h %>% filter(log2FoldChange > 1), "h_DOWN" = DEGenes$Nvs3h %>% filter(log2FoldChange < -1), "d_UP" = DEGenes$Nvs3d %>% filter(log2FoldChange > 1), "d_DOWN" = DEGenes$Nvs3d %>% filter(log2FoldChange < -1)) K27Genes <- read_excel("Data/K27genes_AnyCond_CDS.xlsx") RPKM <- read_excel("Data/RPKM_RNAseq.xlsx") RPKM_K27 <- read_excel("Data/RPKM_K27.xlsx") # Venn K27 Targets ---------------------------------------------------------------------------- ##All timepoints LosingK27 <- full_join(DMGenes$K27_3h_Loss, DMGenes$K27_3d_Loss, by = c("Gene", "log2FCNvs3h", "log2FCNvs3d", "Name" )) GainingK27 <- full_join(DMGenes$K27_3h_Gain, DMGenes$K27_3d_Gain, by = c("Gene", "log2FCNvs3h", "log2FCNvs3d", "Name" )) DESimp <- lapply(DE, function(x){ x %>% select(Gene, Name) }) Upregulated <- full_join(DESimp$h_UP, DESimp$d_UP, by = c("Gene", "Name")) K27Targets <- list("H3K27me3 Targets" = K27Genes$Gene, "Losing H3K27me3" = LosingK27$Gene, "Gaining H3K27me3" = GainingK27$Gene, "Upregulated" = Upregulated$Gene) ggvenn(K27Targets, fill_color = c("#749140","#cd6155", "thistle3", "skyblue"), stroke_linetype = "blank", show_percentage = FALSE, fill_alpha = 0.7) #No overrepresentation of K27 in DE genes ##3h K27Targets <- list("H3K27me3 Targets" = K27Genes$Gene, "Losing H3K27me3" = DMGenes$K27_3h_Loss$Gene, "Upregulated" = DE$h_UP$Gene) ggvenn(K27Targets, fill_color = c("#749140","#cd6155", "thistle3"), stroke_linetype = "blank", show_percentage = FALSE, fill_alpha = 0.7) #No overrepresentation of K27 in DE genes ##3d K27Targets <- list("H3K27me3 Targets" = K27Genes$Gene, "Losing H3K27me3" = DMGenes$K27_3d_Loss$Gene, "Upregulated" = DE$d_UP$Gene) ggvenn(K27Targets, fill_color = c("#749140","#cd6155", "thistle3"), stroke_linetype = "blank", show_percentage = FALSE, fill_alpha = 0.7) #Underrepresentation of K27 in DE genes, confirms Vyse 2020. # Pie chart ----------------------------------------------------------------------------------- K27Targets <- list("H3K27me3 Targets" = K27Genes$Gene, "Upregulated" = Upregulated$Gene) ggvenn(K27Targets, fill_color = c("#cd6155", "thistle3"), stroke_linetype = "blank", show_percentage = FALSE, fill_alpha = 0.7) #ggsave("Plots/K27Targets_UpGenes.tiff", units = "in", width = 3, height = 5, dpi = 300, compression = 'lzw') Pie <- data.frame(Cat = c("Losing H3K27me3", "Gaining H3K27me3", "Non differentially methylated"), Nb = c(20, 42, 488)) %>% mutate(Percentage = Nb / sum(Nb), Cat = as.factor(Cat), Label = paste(round(Percentage*100, digits = 1), "%", sep = "")) ggplot(Pie, aes(x = "", y = Percentage, fill = Cat)) + geom_bar(stat = "identity", width = 1) + scale_fill_manual(values = c("darkgoldenrod","#5a8e41", "#D1AAB8")) + coord_polar("y", start = 0) + theme_void() + theme(legend.position = "none") #ggsave("Plots/K27_DE_Pie.tiff", units = "in", width = 3, height = 3, dpi = 300, compression = 'lzw') # LogFC comparison ---------------------------------------------------------------------------- All <- list("Not differentially methylated" = inner_join(K27Genes, Upregulated, by = "Gene") %>% anti_join(GainingK27, by = "Gene") %>% anti_join(LosingK27, by = "Gene"), "Gaining H3K27me3" = inner_join(GainingK27, Upregulated, by = c("Gene", "Name")) %>% select(Gene, Name), "Losing H3K27me3" = inner_join(LosingK27, Upregulated, by = c("Gene", "Name")) %>% select(Gene, Name)) FC_Cat <- plyr::ldply(All, .id = "Category") %>% inner_join(DE_FC$h, by = "Gene") %>% inner_join(DE_FC$d, by = "Gene") Plot <- FC_Cat %>% pivot_longer(cols = c("DE_FC_3d", "DE_FC_3h"), names_to = "Timepoint", values_to = "FC") %>% mutate(Timepoint = recode(Timepoint, DE_FC_3h = "3h", DE_FC_3d = "3d"), Timepoint = as.factor(Timepoint), Timepoint = forcats::fct_relevel(Timepoint, "3h", "3d")) ggplot(Plot, aes(x = Timepoint, y = FC, color = Category, fill = Category)) + geom_boxplot(lwd = 0.6, alpha = 0.2) + ylim(0, 10) + scale_color_manual(values = c("#945068", "goldenrod4","#365527")) + scale_fill_manual(values = c("#D1AAB8", "#b8860b","#5a8e41")) + labs(y = "Gene expression (log2 fold change)", x = "") + theme_minimal() + theme(axis.text = element_text(colour = "black"), legend.position = "none") ggsave("Plots/K27_DE_LogFC.tiff", units = "in", width = 3, height = 4, dpi = 300, compression = 'lzw') compare_means(DE_FC_3d ~ Category, data = FC_Cat) # RPKM comparison ----------------------------------------------------------------------------- RPKM_Cat <- plyr::ldply(All, .id = "Category") %>% inner_join(RPKM, by = "Gene") Plot <- RPKM_Cat %>% pivot_longer(cols = c("N", "h", "d"), names_to = "Timepoint", values_to = "RPKM") %>% mutate(Timepoint = recode(Timepoint, h = "3h", d = "3d"), Timepoint = as.factor(Timepoint), Timepoint = forcats::fct_relevel(Timepoint, "N", "3h", "3d")) ggplot(Plot, aes(x = Timepoint, y = log2(RPKM), color = Category, fill = Category)) + geom_boxplot(lwd = 0.6, alpha = 0.2) + scale_color_manual(values = c("#945068", "goldenrod4","#365527")) + scale_fill_manual(values = c("#D1AAB8", "#b8860b","#5a8e41")) + labs(y = "Gene expression (log2(RPKM))", x = "") + theme_minimal() + theme(axis.text = element_text(colour = "black"), legend.position = "none") ggsave("Plots/K27_DE_RPKM.tiff", units = "in", width = 4, height = 4, dpi = 300, compression = 'lzw') compare_means(d ~ Category, data = RPKM_Cat) # RPKM K27 comparison ----------------------------------------------------------------------------- RPKM_Cat <- plyr::ldply(All, .id = "Category") %>% inner_join(RPKM_K27, by = "Gene") Plot <- RPKM_Cat %>% pivot_longer(cols = c("N", "h", "d"), names_to = "Timepoint", values_to = "RPKM") %>% mutate(Timepoint = recode(Timepoint, h = "3h", d = "3d"), Timepoint = as.factor(Timepoint), Timepoint = forcats::fct_relevel(Timepoint, "N", "3h", "3d")) ggplot(Plot, aes(x = Timepoint, y = log2(RPKM), color = Category, fill = Category)) + geom_boxplot(lwd = 0.6, alpha = 0.2) + scale_color_manual(values = c("#945068", "goldenrod4","#365527")) + scale_fill_manual(values = c("#D1AAB8", "#b8860b","#5a8e41")) + labs(y = "H3K27me3 levels (log2(RPKM))", x = "") + theme_minimal() + theme(axis.text = element_text(colour = "black"), legend.position = "none") ggsave("Plots/K27_K27_RPKM.tiff", units = "in", width = 4, height = 4, dpi = 300, compression = 'lzw') compare_means(N ~ Category, data = RPKM_Cat)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- Desarrollo Web en Entorno Servidor - Tarea 1 Programar una aplicación para mantener una lista de teléfonos en una única página web, programada en PHP. La lista almacenará únicamente dos datos: número de teléfono y nombre. No podrá haber números repetidos. Se utilizará como modelo de datos un array de pares (teléfono, nombre) En la parte superior de la página web se mostrará un título y los resultados obtenidos En la parte inferior tendremos un sencillo formulario, una casilla de texto para el teléfono y otra para el nombre. Al pulsar el botón, se ejecutará alguna de las siguientes acciones: • Si el número está vacío o no cumple el patrón de validación especificado, se mostrará una advertencia. • Si se introduce un número válido que no existe en la lista, y el nombre no está vacío, se añadirá a la lista. • Si se introduce un número válido que existe en la lista y se indica un nombre, se sustituirá el nombre anterior. • Si se introduce un número válido que existe en la lista pero sin nombre, se eliminará el teléfono de la lista • Si se introduce un nombre que exista dejando el teléfono en blanco, se visualizará una lista con todos los teléfonos asociados Como mecanismo de "persistencia" utilizaremos un array que está en el formulario como elemento oculto y se envía. Consultar y comprender el funcionamiento de métodos: explode, implode, array_search >> utilizados en el código --> <html lang="es"> <head> <meta charset="UTF-8"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>Listín telefónico</title> <!-- Preparamos el entorno gráfico para los datos --> <style type="text/css"> td, th { border: 1px solid grey; padding: 4px; } th { text-align: center; background-color: #67b4b4; } table { border: 1px solid black; } div { padding: 10px 20px } h1 { font-family: sans-serif; font-style: italic; text-transform: capitalize; color: #008000; } .bajoDch { float: right; position: absolute; margin-right: 0px; margin-bottom: 0px; bottom: 0px; right: 0px; } .altoDch1 { color: #00f; float: right; position: absolute; margin-right: 0px; margin-top: 0px; top: 0px; right: 0px; } .altoDch2 { color: #f00; float: right; position: absolute; margin-right: 0px; margin-top: 0px; top: 0px; right: 0px; } </style> </head> <body> <?php define("BR", "<br/>\n"); // Comprobamos que se han recibido los datos 'anteriores' por POST if (!empty($_POST["personas"])) { $tel = $_POST["tfno"]; $name = $_POST["nom"]; $array = explode(",", $_POST["personas"]); $pos = count($array); $txt = "<ul style='list-style: none;'>\n"; for ($i = 1; $i < $pos; $i += 2) { $txt .= "<li><strong>" . $array[$i + 1] . "</strong> = " . $array[$i]."</li>\n"; } $txt .= "<li><strong>$name</strong> = $tel</li>\n"; $txt .= "</ul>"; echo $txt; if (empty($tel)) { if (findPos($array, $name) !== false) { for ($i = 1; $i < count($array); $i += 2) { echo $array[$i] . " = " . $array[$i + 1] . BR; } } } else { if (!preg_match("/[\d]{9}/", $tel)) { echo "El campo teléfono no cumple con los requisitos, está vacio o no es un número válido" . BR; } else { $busqueda = findPos($array, $tel); if ($busqueda === false && !empty($name)) { $array[$pos++] = $tel; $array[$pos++] = $name; } else { if (!empty($name)) { $array[$busqueda + 1] = $name; } else { unset($array[$busqueda]); unset($array[$busqueda + 1]); } } } } } else { // Si no hay datos antiguos, sólo reiniciamos las variables globales $array = array(); $pos = 0; echo "<h2>NO HAY DATOS</h2>"; } //Implementar la funcionalidad solicitada // Función para comprobar si un nombre existe en el array function findPos($miArray, $dato) { $posicion = array_search($dato, $miArray, false); return $posicion; } ?> <br /> <!-- Capa inferior derecha para las preguntas --> <div class="bajoDch"> <!-- Formulario para enviar sus datos por POST a la misma página --> <form name="formulario" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post"> <table style="border: 0px;"> <tr style="background-color: #8080ff;">Introduzca los datos <!-- Número de teléfono --> <td> <fieldset> <legend>Teléfono</legend> <input name="tfno" type="text" /> </fieldset> </td> <!-- Nombre de la persona --> <td> <fieldset> <legend>Nombre</legend> <input name="nom" type="text" /> </fieldset> </td> </tr> </table> <!-- Creamos un campo oculto para enviar los datos ya recogidos con anterioridad --> <input name="personas" type="hidden" value=" <?php if (isset($array)) echo implode(",", $array); ?>" style="text-align:right;" /> <!-- Enviamos los datos del formulario --> <input type="submit" value="Aplicar cambios" /> </form> </div> </body> </html>
import { createSlice } from "@reduxjs/toolkit"; import { User } from './../../../types/user/index'; export interface AuthState { user: User | undefined, isLoggedIn: boolean; } const initialState = { user: {} as User, isLoggedIn: false } as AuthState const authSlice = createSlice({ name: "app/auth", initialState, reducers: { logOut(state): void { state.isLoggedIn = false; state.user = undefined }, handleLogin(state, action): void { state.isLoggedIn = true; state.user = action.payload } }, }) const { reducer, actions } = authSlice export const { logOut, handleLogin } = actions export default reducer;
import { AwsCallerIdentity, AwsClient, DescribeRepositoriesResponse } from "../../dist/core/aws"; import { TestAwsConfig } from "./test-lab"; export interface AwsState { ecr: Record<string, Array<object>>; } export function initialAwsState() { return { ecr: {} }; } class ErrorWithCode extends Error { constructor(message: string, public readonly Code: string) { super(message); } } export class FakeAwsClient implements AwsClient { static readonly config: TestAwsConfig = Object.freeze({ accountId: "12345678", region: "mars-2", accessKeyId: "VALIDKEY", secretAccessKey: "VALIDSECRET", sessionToken: undefined, }); readonly region: string; constructor( private readonly state: AwsState, private readonly env: Record<string, string | undefined>, ) { this.region = env["AWS_REGION"] || ""; } async getStsCallerIdentity(): Promise<AwsCallerIdentity> { this.checkEnvironment(); return { account: "12345678", }; } async createEcrRepository(options: { repositoryName: string }): Promise<void> { this.state.ecr[options.repositoryName] = []; } async describeEcrRepositories(): Promise<DescribeRepositoriesResponse> { return { nextToken: undefined, repositories: Object.keys(this.state.ecr).map(repositoryName => ({ repositoryName, })), }; } private checkEnvironment(): void { if (this.env["AWS_REGION"] === undefined) { throw new Error("Region not set"); } if (this.env["AWS_REGION"] !== FakeAwsClient.config.region) { throw new Error(`Invalid region: ${this.env["AWS_REGION"]}`); } if (this.env["AWS_SECRET_ACCESS_KEY"] != FakeAwsClient.config.secretAccessKey) { throw new ErrorWithCode("Invalid secret key", "SignatureDoesNotMatch"); } } }
import { useState } from "react"; import { CardElement } from "@stripe/react-stripe-js"; import { useSelector } from "react-redux"; // internal import useCartInfo from "@/hooks/use-cart-info"; import ErrorMsg from "../common/error-msg"; const CheckoutOrderArea = ({ checkoutData }) => { const { handleShippingCost, cartTotal = 0, stripe, isCheckoutSubmit, clientSecret, register, errors, showCard, setShowCard, shippingCost, discountAmount } = checkoutData; const { cart_products } = useSelector((state) => state.cart); const { total } = useCartInfo(); return ( <div className="tp-checkout-place white-bg"> <h3 className="tp-checkout-place-title">Your Order</h3> <div className="tp-order-info-list"> <ul> {/* header */} <li className="tp-order-info-list-header"> <h4>Product</h4> <h4>Total</h4> </li> {/* item list */} {cart_products.map((item) => ( <li key={item._id} className="tp-order-info-list-desc"> <p> {item.title} <span> x {item.orderQuantity}</span> </p> <span>${item.price.toFixed(2)}</span> </li> ))} {/* shipping */} <li className="tp-order-info-list-shipping"> <span>Shipping</span> <div className="tp-order-info-list-shipping-item d-flex flex-column align-items-end"> <span> <input {...register(`shippingOption`, { required: `Shipping Option is required!`, })} id="flat_shipping" type="radio" name="shippingOption" /> <label onClick={() => handleShippingCost(60)} htmlFor="flat_shipping" > Delivery: Today Cost :<span>$60.00</span> </label> <ErrorMsg msg={errors?.shippingOption?.message} /> </span> <span> <input {...register(`shippingOption`, { required: `Shipping Option is required!`, })} id="flat_rate" type="radio" name="shippingOption" /> <label onClick={() => handleShippingCost(20)} htmlFor="flat_rate" > Delivery: 7 Days Cost: <span>$20.00</span> </label> <ErrorMsg msg={errors?.shippingOption?.message} /> </span> </div> </li> {/* subtotal */} <li className="tp-order-info-list-subtotal"> <span>Subtotal</span> <span>${total.toFixed(2)}</span> </li> {/* shipping cost */} <li className="tp-order-info-list-subtotal"> <span>Shipping Cost</span> <span>${shippingCost.toFixed(2)}</span> </li> {/* discount */} <li className="tp-order-info-list-subtotal"> <span>Discount</span> <span>${discountAmount.toFixed(2)}</span> </li> {/* total */} <li className="tp-order-info-list-total"> <span>Total</span> <span>${parseFloat(cartTotal).toFixed(2)}</span> </li> </ul> </div> <div className="tp-checkout-payment"> <div className="tp-checkout-payment-item"> <input {...register(`payment`, { required: `Payment Option is required!`, })} type="radio" id="back_transfer" name="payment" value="Card" /> <label onClick={() => setShowCard(true)} htmlFor="back_transfer" data-bs-toggle="direct-bank-transfer"> Credit Card </label> {showCard && ( <div className="direct-bank-transfer"> <div className="payment_card"> <CardElement options={{ style: { base: { fontSize: "16px", color: "#424770", "::placeholder": { color: "#aab7c4", }, }, invalid: { color: "#9e2146", }, }, }} /> </div> </div> )} <ErrorMsg msg={errors?.payment?.message} /> </div> <div className="tp-checkout-payment-item"> <input {...register(`payment`, { required: `Payment Option is required!`, })} onClick={() => setShowCard(false)} type="radio" id="cod" name="payment" value="COD" /> <label htmlFor="cod">Cash on Delivery</label> <ErrorMsg msg={errors?.payment?.message} /> </div> </div> <div className="tp-checkout-btn-wrapper"> <button type="submit" disabled={!stripe || isCheckoutSubmit} className="tp-checkout-btn w-100" > Place Order </button> </div> </div> ); }; export default CheckoutOrderArea;
# Contributing ## Running the Extension With Visual Studio Code: - Clone this repository locally. - Run `npm install` in the cloned `codewind-node-profiler` folder. This installs all necessary npm modules in both the client and server folder - Open the clone of this repository in Visual Studio Code. - Press Ctrl+Shift+B (Cmd+Shift+B on Mac) to compile the client and server. - Switch to the Debug viewlet. - Select `Launch Client` from the drop down and press the Run icon. - If you want to debug the server as well use the launch configuration `Attach to Server`. ## Testing Setup: - Run `npm install` in the `codewind-node-profiler` folder. In Visual Studio Code: - Press Ctrl+Shift+B (Cmd+Shift+B on Mac) to compile the client and server. - Run `npm run prepare-tests` in the `vscode/client` folder. - Switch to the Debug viewlet. - Select `Language Server E2E Test` from the drop down. - Run the test config. - An additional editor will momentarily open while the tests are run. It will close automatically once they are complete. - Switch to the output view with Ctrl+Shift+U (Cmd+Shift+U on Mac) to see the results of the tests. ## Building/Installing the Extension To build a `.vsix` extension package that can then be installed/published: - Run `npm install` in the `codewind-node-profiler` folder. - Install the `vsce` package globally with `npm install -g vsce`. - Run `vsce package` in the `codewind-node-profiler` folder. - A `.vsix` file will then be generated. To install the extension: - Run `code --install-extension <name of generated vsix file>` in the `codewind-node-profiler` folder. - Restart Visual Studio Code. - The extension should appear in your list of installed extensions. For more information refer to: <https://code.visualstudio.com/api/working-with-extensions/publishing-extension> ======= ## Contributing Thank you for your interest in contributing to Codewind. We welcome your additions to this project. #### Signing the Eclipse Contributor Agreement (ECA) Before you can contribute to any Eclipse project, you need to sign the [Eclipse Contributor Agreement (ECA)](https://www.eclipse.org/legal/ECA.php). 1. To verify that you signed the ECA, sign in to [https://accounts.eclipse.org/ your Eclipse account]. 2. View your **Status** and make sure that a check mark appears with the **Eclipse Contributor Agreement**. 3. If the check mark does not appear, click the **Eclipse Contributor Agreement** in the **Status** box to go to the agreement that you need to sign. 4. Fill the form and click the **Accept** button. #### Associating your Eclipse profile with your GitHub ID 1. From your Eclipse account, select **Edit Profile**. 2. On the **Personal Information** tab, go to the **Social Media Links** section and add your GitHub user name to the **GitHub Username** field. 3. Answer the **Have you changed employers** question. 4. Enter your Eclipse password in the **Current password** field and then click **Save**. For more information about Codewind workflows, see the [Codewind GitHub Workflows wiki](https://wiki.eclipse.org/Codewind_GitHub_Workflows). #### Checking if your issue is already addressed - Search the [list of issues](https://github.com/eclipse/codewind/issues) to see if your issue has already been raised. - See the [Codewind documentation](https://www.eclipse.org/codewind/docindex.html) to see if existing documentation addresses your question or concern. #### Creating a new issue If you do not see your issue, please [select the issue type in the Codewind repository to open a new issue](https://github.com/eclipse/codewind/issues/new/choose). - **Bugs:** Complete the bug template to report problems found in Codewind. - **Enhancements:** Complete the enhancement template to suggest improvements to Codewind. - **Questions:** Complete the question template to ask a question about Codewind. ## Contact us If you have questions, please visit us on [Mattermost](https://mattermost.eclipse.org/eclipse/channels/eclipse-codewind).
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.api.security.invoker; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.util.AXIOMUtil; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.Header; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.*; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.wso2.carbon.api.security.utils.AuthConstants; import org.wso2.carbon.api.security.utils.CoreUtils; import org.wso2.carbon.utils.CarbonUtils; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import java.io.File; import java.io.IOException; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.Iterator; public class RESTInvoker { private static final Log log = LogFactory.getLog(RESTInvoker.class); private int maxTotalConnections = 100; private int maxTotalConnectionsPerRoute = 100; private int connectionTimeout = 120000; private int socketTimeout = 120000; private CloseableHttpClient client = null; private PoolingHttpClientConnectionManager connectionManager = null; public RESTInvoker() { configureHttpClient(); } private void parseConfiguration() { String carbonConfigDirPath = CarbonUtils.getCarbonConfigDirPath(); String apiFilterConfigPath = carbonConfigDirPath + File.separator + AuthConstants.AUTH_CONFIGURATION_FILE_NAME; File configFile = new File(apiFilterConfigPath); try { String configContent = FileUtils.readFileToString(configFile); OMElement configElement = AXIOMUtil.stringToOM(configContent); Iterator beans = configElement.getChildrenWithName( new QName("http://www.springframework.org/schema/beans", "bean")); while (beans.hasNext()) { OMElement bean = (OMElement) beans.next(); String beanId = bean.getAttributeValue(new QName(null, "id")); if (beanId.equals(RESTConstants.REST_CLIENT_CONFIG_ELEMENT)) { Iterator beanProps = bean.getChildrenWithName( new QName("http://www.springframework.org/schema/beans", "property")); while (beanProps.hasNext()) { OMElement beanProp = (OMElement) beanProps.next(); String beanName = beanProp.getAttributeValue(new QName(null, "name")); if (RESTConstants.REST_CLIENT_MAX_TOTAL_CONNECTIONS.equals(beanName)) { String value = beanProp.getAttributeValue(new QName(null, "value")); if (value != null && !value.trim().equals("")) { maxTotalConnections = Integer.parseInt(value); } CoreUtils.debugLog(log, "Max total http connections ", maxTotalConnections); } else if (RESTConstants.REST_CLIENT_MAX_CONNECTIONS_PER_ROUTE.equals(beanName)) { String value = beanProp.getAttributeValue(new QName(null, "value")); if (value != null && !value.trim().equals("")) { maxTotalConnectionsPerRoute = Integer.parseInt(value); } CoreUtils.debugLog(log, "Max total client connections per route ", maxTotalConnectionsPerRoute); } else if (RESTConstants.REST_CLEINT_CONNECTION_TIMEOUT.equals(beanName)) { String value = beanProp.getAttributeValue(new QName(null, "value")); if (value != null && !value.trim().equals("")) { connectionTimeout = Integer.parseInt(value); } } else if (RESTConstants.REST_CLEINT_SOCKET_TIMEOUT.equals(beanName)) { String value = beanProp.getAttributeValue(new QName(null, "value")); if (value != null && !value.trim().equals("")) { socketTimeout = Integer.parseInt(value); } } } } } } catch (XMLStreamException e) { log.error("Error in processing http connection settings, using default settings", e); } catch (IOException e) { log.error("Error in processing http connection settings, using default settings", e); } } private void configureHttpClient() { parseConfiguration(); RequestConfig defaultRequestConfig = RequestConfig.custom() .setExpectContinueEnabled(true) .setConnectTimeout(connectionTimeout) .setSocketTimeout(socketTimeout) .build(); connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setDefaultMaxPerRoute(maxTotalConnectionsPerRoute); connectionManager.setMaxTotal(maxTotalConnections); client = HttpClients.custom() .setConnectionManager(connectionManager) .setDefaultRequestConfig(defaultRequestConfig) .build(); CoreUtils.debugLog(log, "REST client initialized with ", "maxTotalConnection = ", maxTotalConnections, "maxConnectionsPerRoute = ", maxTotalConnectionsPerRoute, "connectionTimeout = ", connectionTimeout); } public void closeHttpClient() { IOUtils.closeQuietly(client); IOUtils.closeQuietly(connectionManager); } /** * Invokes the http GET method * * @param uri endpoint/service url * @param requestHeaders header list * @param username username for authentication * @param password password for authentication * @return RESTResponse of the GET request (can be the response body or the response status code) * @throws Exception */ public RESTResponse invokeGET(URI uri, BasicNameValuePair[] requestHeaders, String username, String password) throws IOException { HttpGet httpGet = null; CloseableHttpResponse response = null; Header[] headers; int httpStatus; String contentType; String output; try { httpGet = new HttpGet(uri); if (requestHeaders != null && requestHeaders.length > 0) { for (BasicNameValuePair header : requestHeaders) { httpGet.setHeader(header.getName(), header.getValue()); } } response = sendReceiveRequest(httpGet, username, password); output = IOUtils.toString(response.getEntity().getContent()); headers = response.getAllHeaders(); httpStatus = response.getStatusLine().getStatusCode(); contentType = response.getEntity().getContentType().getValue(); if (log.isTraceEnabled()) { log.trace("Invoked GET " + uri.toString() + " - Response message: " + output); } EntityUtils.consume(response.getEntity()); } finally { if (response != null) { IOUtils.closeQuietly(response); } if (httpGet != null) { httpGet.releaseConnection(); } } return new RESTResponse(contentType, output, headers, httpStatus); } public RESTResponse invokePOST(URI uri, BasicNameValuePair[] requestHeaders, String username, String password, String payload) throws IOException { HttpPost httpPost = null; CloseableHttpResponse response = null; Header[] headers; int httpStatus; String contentType; String output; try { httpPost = new HttpPost(uri); httpPost.setEntity(new StringEntity(payload)); if (requestHeaders != null && requestHeaders.length > 0) { for (BasicNameValuePair header : requestHeaders) { httpPost.setHeader(header.getName(), header.getValue()); } } response = sendReceiveRequest(httpPost, username, password); output = IOUtils.toString(response.getEntity().getContent()); headers = response.getAllHeaders(); httpStatus = response.getStatusLine().getStatusCode(); contentType = response.getEntity().getContentType().getValue(); if (log.isTraceEnabled()) { log.trace("Invoked POST " + uri.toString() + " - Input payload: " + payload + " - Response message: " + output); } EntityUtils.consume(response.getEntity()); } finally { if (response != null) { IOUtils.closeQuietly(response); } if (httpPost != null) { httpPost.releaseConnection(); } } return new RESTResponse(contentType, output, headers, httpStatus); } /** * Invokes the http PUT method * * @param uri endpoint/service url * @param requestHeaders header list * @param username username for authentication * @param password password for authentication * @param payload payload body passed * @return RESTResponse of the PUT request (can be the response body or the response status code) * @throws Exception */ public RESTResponse invokePUT(URI uri, BasicNameValuePair[] requestHeaders, String username, String password, String payload) throws IOException { HttpPut httpPut = null; CloseableHttpResponse response = null; Header[] headers; int httpStatus; String contentType; String output; try { httpPut = new HttpPut(uri); httpPut.setEntity(new StringEntity(payload)); if (requestHeaders != null && requestHeaders.length > 0) { for (BasicNameValuePair header : requestHeaders) { httpPut.setHeader(header.getName(), header.getValue()); } } response = sendReceiveRequest(httpPut, username, password); output = IOUtils.toString(response.getEntity().getContent()); headers = response.getAllHeaders(); httpStatus = response.getStatusLine().getStatusCode(); contentType = response.getEntity().getContentType().getValue(); if (log.isTraceEnabled()) { log.trace("Invoked PUT " + uri.toString() + " - Response message: " + output); } EntityUtils.consume(response.getEntity()); } finally { if (response != null) { IOUtils.closeQuietly(response); } if (httpPut != null) { httpPut.releaseConnection(); } } return new RESTResponse(contentType, output, headers, httpStatus); } /** * Invokes the http DELETE method * * @param uri endpoint/service url * @param requestHeaders header list * @param username username for authentication * @param password password for authentication * @return RESTResponse of the DELETE (can be the response status code or the response body) * @throws Exception */ public RESTResponse invokeDELETE(URI uri, BasicNameValuePair[] requestHeaders, String username, String password) throws IOException { HttpDelete httpDelete = null; CloseableHttpResponse response = null; Header[] headers; int httpStatus; String contentType; String output; try { httpDelete = new HttpDelete(uri); if (requestHeaders != null && requestHeaders.length > 0) { for (BasicNameValuePair header : requestHeaders) { httpDelete.setHeader(header.getName(), header.getValue()); } } response = sendReceiveRequest(httpDelete, username, password); output = IOUtils.toString(response.getEntity().getContent()); headers = response.getAllHeaders(); httpStatus = response.getStatusLine().getStatusCode(); contentType = response.getEntity().getContentType().getValue(); if (log.isTraceEnabled()) { log.trace("Invoked DELETE " + uri.toString() + " - Response message: " + output); } EntityUtils.consume(response.getEntity()); } finally { if (response != null) { IOUtils.closeQuietly(response); } if (httpDelete != null) { httpDelete.releaseConnection(); } } return new RESTResponse(contentType, output, headers, httpStatus); } private CloseableHttpResponse sendReceiveRequest(HttpRequestBase requestBase, String username, String password) throws IOException { CloseableHttpResponse response; if (username != null && !username.equals("") && password != null) { String combinedCredentials = username + ":" + password; byte[] encodedCredentials = Base64.encodeBase64(combinedCredentials.getBytes(StandardCharsets.UTF_8)); requestBase.addHeader("Authorization", "Basic " + new String(encodedCredentials)); response = client.execute(requestBase); } else { response = client.execute(requestBase); } return response; } }
from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Input, Dense, Flatten import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import mean_squared_error, accuracy_score import matplotlib.pyplot as plt data = pd.read_csv("mrk0.csv") x = data.drop('hospital_death', axis=1) y = data['hospital_death'] x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=42) scaler = StandardScaler() x_train = scaler.fit_transform(x_train) x_test = scaler.transform(x_test) model=Sequential() model.add(Flatten(input_shape=(106,))) model.add(Dense(128,activation='relu')) model.add(Dense(32,activation='relu')) model.add(Dense(1,activation='sigmoid')) model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy']) history = model.fit(x_train,y_train,validation_data = (x_test, y_test),batch_size=10,epochs=15) model.save('m1.h5') model.save_weights('m1_w.h5') y_pred=model.predict(x_test) y_pred[y_pred>0.5]=1 y_pred[y_pred<0.5]=0 print(accuracy_score(y_pred,y_test)) plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'val'], loc='upper left') plt.show()
import React, { useState, ChangeEvent, FormEvent, useEffect } from 'react'; import login from './api/login'; import signup from './api/signup'; interface AuthenticationProps { setLogIn: React.Dispatch<React.SetStateAction<boolean>>; } const Authentication: React.FC<AuthenticationProps> = ({ setLogIn }) => { const [visible, setVisible] = useState(false); useEffect(() => { const username = localStorage.getItem('user'); if (username) { setLogIn(true); } else { setVisible(true); } }, []); const [signupFormData, setSignupFormData] = useState({ username: '', name: '', password: '', role: 'User', }); const [loginFormData, setLoginFormData] = useState({ username: '', password: '', }); const handleSignupChange = (e: ChangeEvent<HTMLInputElement>) => { const { name, value } = e.target; setSignupFormData({ ...signupFormData, [name]: value }); }; const handleSignupChangeSelect = (e: ChangeEvent<HTMLSelectElement>) => { const { name, value } = e.target; setSignupFormData({ ...signupFormData, [name]: value }); }; const handleLoginChange = (e: ChangeEvent<HTMLInputElement>) => { const { name, value } = e.target; setLoginFormData({ ...loginFormData, [name]: value }); }; const handleSignupSubmit = async (e: FormEvent<HTMLFormElement>) => { e.preventDefault(); if ( signupFormData.name == '' || signupFormData.password == '' || signupFormData.username == '' ) { alert('Sign Up Fields cannot be empty'); return; } await signup(signupFormData); toggleLogin(); setSignupFormData({ username: '', name: '', password: '', role: 'User' }); }; const handleLoginSubmit = async (e: FormEvent<HTMLFormElement>) => { e.preventDefault(); if (loginFormData.password == '' || loginFormData.username == '') { alert('Log In Fields cannot be empty'); return; } const key = await login(loginFormData); if (key) { setLogIn(true); localStorage.setItem('user', JSON.stringify(key)); } else { alert('Invalid Login'); } setLoginFormData({ username: '', password: '' }); }; const [showLogin, setShowLogin] = useState(true); const [showSignup, setShowSignup] = useState(false); const toggleLogin = () => { setShowLogin(true); setShowSignup(false); }; const toggleSignup = () => { setShowLogin(false); setShowSignup(true); }; return ( <div className={`bg-white h-full ${visible ? '' : 'hidden'}`}> <div className="max-w-md mx-auto p-8"> <div className="flex justify-center"> <button onClick={toggleLogin} className={`py-2 px-4 mr-2 ${ showLogin ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-800' }`} > Login </button> <button onClick={toggleSignup} className={`py-2 px-4 ${ showLogin ? 'bg-gray-200 text-gray-800' : 'bg-blue-500 text-white' }`} > Sign Up </button> </div> <form onSubmit={handleSignupSubmit} className={`mt-4 ${showSignup ? '' : 'hidden'}`} > <div className="mb-4"> <label htmlFor="username" className="block mb-1"> Username: </label> <input type="text" id="username" name="username" className="border border-gray-300 rounded px-3 py-2 w-full" placeholder=" Enter Username" value={signupFormData.username} onChange={handleSignupChange} /> </div> <div className="mb-4"> <label htmlFor="name" className="block mb-1"> Name: </label> <input type="text" id="name" name="name" className="border border-gray-300 rounded px-3 py-2 w-full" placeholder=" Enter Name" value={signupFormData.name} onChange={handleSignupChange} /> </div> <div className="mb-4"> <label htmlFor="password" className="block mb-1"> Password: </label> <input type="password" id="password" name="password" placeholder=" Enter Password" className="border border-gray-300 rounded px-3 py-2 w-full" value={signupFormData.password} onChange={handleSignupChange} /> </div> <div className="mb-4"> <label htmlFor="role" className="block mb-1"> Role: </label> <select id="role" name="role" className="border border-gray-300 rounded px-3 py-2 w-full" value={signupFormData.role} onChange={handleSignupChangeSelect} > <option value="User">User</option> <option value="Admin">Admin</option> </select> </div> <button className="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded w-full" type="submit" > Signup </button> </form> <form onSubmit={handleLoginSubmit} className={`mt-4 ${showLogin ? '' : 'hidden'} `} > <div className="mb-4"> <label htmlFor="loginUsername" className="block mb-1"> Username: </label> <input type="text" id="loginUsername" name="username" className="border border-gray-300 rounded px-3 py-2 w-full" placeholder=" Enter Username" value={loginFormData.username} onChange={handleLoginChange} /> </div> <div className="mb-4"> <label htmlFor="loginPassword" className="block mb-1"> Password: </label> <input type="password" id="loginPassword" name="password" placeholder=" Enter Password" className="border border-gray-300 rounded px-3 py-2 w-full" value={loginFormData.password} onChange={handleLoginChange} /> </div> <button className="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded w-full" type="submit" > Login </button> </form> </div> </div> ); }; export default Authentication;
import React from 'react' import { Box, Card, CardMedia, Typography, Grid } from '@mui/material' import { useNavigate } from 'react-router-dom' const tools = [ { title: '人工翻译', description: '准确、快速地翻译商务文件,跨越语言障碍。支持多种语言,保证翻译的专业性和准确性。', imageUrl: require('../../pic/translation.png'), route: '/team/translation', }, { title: '专家大师课', description: '自动生成高质量的文书内容,提高工作效率。帮助您快速完成报告、论文、申请书等文档的撰写。', imageUrl: require('../../pic/master.png'), route: '/team/master', }, { title: '同行一对一', description: '快速生成精美的PPT,提升演示效果。自动化设计,让您的演示更加吸引人。', imageUrl: require('../../pic/pear.png'), route: '/team/pear', }, ] function AIPage () { const navigate = useNavigate() return ( <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}> <Grid container spacing={4} sx={{ maxWidth: 800 }}> {/* Increase the grid spacing and max width */} {tools.map((tool) => ( <Grid item xs={6} key={tool.title}> <Card sx={{ minHeight: 200, // Increase the card height display: 'flex', flexDirection: 'column', cursor: 'pointer', p: 2, // Increase the padding }} onClick={() => navigate(tool.route)} > <Typography variant="h5" component="div" sx={{ fontWeight: 'bold', textAlign: 'left', fontSize: '1.5rem', // Increase the font size mb: 1, // Add margin bottom }}> {tool.title} </Typography> <Box sx={{ display: 'flex', flexGrow: 1, alignItems: 'center', justifyContent: 'space-between' }}> <Typography variant="body2" color="text.secondary" sx={{ textAlign: 'left', flex: 1, pr: 2, // Increase the padding right }}> {tool.description} </Typography> <CardMedia component="img" sx={{ width: 80, height: 80 }} image={tool.imageUrl} alt={tool.title} /> </Box> </Card> </Grid> ))} </Grid> </Box> ) } export default AIPage
-- NOTE: Cloned from krastorio local event = require("__flib__.event") local constants = require("scripts.constants") local tesla_coil = {} function tesla_coil.init() global.tesla_coil = { --- @type table<number, BeamData> beams = {}, --- @type table<number, TowerData> turrets = {}, --- @type table<number, TowerData> towers = {}, --- @type table<number, TargetData> targets = {}, } end function tesla_coil.get_absorber_buffer_capacity() global.tesla_coil.absorber_buffer_capacity = game.equipment_prototypes["energy-absorber"].energy_source.buffer_capacity end -- TOWER -- The entity that is interacted with --- @param source_entity LuaEntity function tesla_coil.build(source_entity) local surface = source_entity.surface local unit_number = source_entity.unit_number local turret = surface.create_entity({ name = "kr-tesla-coil-turret", position = source_entity.position, force = game.forces["kr-internal-turrets"], create_build_effect_smoke = false, raise_built = true, }) if not turret or not turret.valid then game.print("Building tesla failed due to AAI Programmable Vehicles. This tesla coil will not function.") source_entity.active = false return end turret.destructible = false --- @class TowerData local data = { entities = { collision = surface.create_entity({ name = "kr-tesla-coil-collision", position = source_entity.position, force = source_entity.force, create_build_effect_smoke = false, raise_built = true, }), tower = source_entity, turret = turret, }, tower_unit_number = unit_number, turret_unit_number = turret.unit_number, } global.tesla_coil.turrets[data.turret_unit_number] = data global.tesla_coil.towers[unit_number] = data end --- @param entity LuaEntity function tesla_coil.destroy(entity) -- Beams will automatically get destroyed local unit_number = entity.unit_number local tower_data = global.tesla_coil.towers[unit_number] if tower_data then global.tesla_coil.turrets[tower_data.turret_unit_number] = nil global.tesla_coil.towers[unit_number] = nil for _, entity in pairs(tower_data.entities) do if entity and entity.valid then entity.destroy() end end end end -- TARGET -- An entity that will receive energy from a tesla coil --- @param grid LuaEquipmentGrid --- @return LuaEquipment|nil local function find_absorber_in_grid(grid) -- Find the energy absorber for _, equipment in pairs(grid.equipment) do if equipment.name == "energy-absorber" then return equipment end end end --- @param target LuaEntity --- @return GridData local function get_grid_data(target) --- @type LuaEquipmentGrid local grid if target.type == "character" then local armor_inventory = target.get_inventory(defines.inventory.character_armor) if armor_inventory and armor_inventory.valid then local armor = armor_inventory[1] if armor and armor.valid_for_read then grid = armor.grid end end else grid = target.grid end if grid then --- @class GridData local data = { absorber = find_absorber_in_grid(grid), grid = grid, } return data end end --- Updates the absorber object in a target's equipment grid --- @param grid LuaEquipmentGrid function tesla_coil.update_target_grid(grid) for _, target_data in pairs(global.tesla_coil.targets) do local grid_data = target_data.grid_data if grid_data.grid.valid and grid_data.grid == grid then grid_data.absorber = find_absorber_in_grid(grid) end end end --- @param target LuaEntity --- @param tower_data TowerData function tesla_coil.add_target(target, tower_data) local target_unit_number = target.unit_number -- Check if the tower is powered if tower_data.entities.tower.energy < constants.tesla_coil.required_energy then return end -- Check the target's equipment grid for an energy absorber local grid_data = get_grid_data(target) if grid_data and grid_data.absorber and grid_data.absorber.valid then --- @class TargetData local target_data = { connections = { --- @type table<number, ConnectionData> by_beam = {}, --- @type table<number, ConnectionData> by_tower = {}, }, entity = target, --- @type number? full_tick = nil, grid_data = grid_data, unit_number = target_unit_number, } global.tesla_coil.targets[target_unit_number] = target_data return target_data end end --- @param target_unit_number number function tesla_coil.remove_target(target_unit_number) global.tesla_coil.targets[target_unit_number] = nil end -- CONNECTION -- A connection between a tower and a target, comprising of a beam -- There can be unlimited connections per target --- @param target_data TargetData --- @param tower_data TowerData function tesla_coil.add_connection(target_data, tower_data) -- Check if the absorber has space local capacity = global.tesla_coil.absorber_buffer_capacity local absorber = target_data.grid_data.absorber if absorber and absorber.valid and absorber.energy then if absorber.energy < capacity then -- Create beam entity local beam = tower_data.entities.tower.surface.create_entity({ name = "kr-tesla-coil-electric-beam", source = tower_data.entities.tower, source_offset = { 0, -2.2 }, position = tower_data.entities.tower.position, target = target_data.entity, duration = 0, max_length = constants.tesla_coil.range, force = tower_data.entities.tower.force, raise_built = true, }) if not beam then return end local beam_number = event.register_on_entity_destroyed(beam) --- @class BeamData global.tesla_coil.beams[beam_number] = { beam = beam, beam_number = beam_number, target_data = target_data, tower_data = tower_data, } --- @class ConnectionData local connection_data = { beam = beam, beam_number = beam_number, tower_data = tower_data, } target_data.connections.by_beam[beam_number] = connection_data target_data.connections.by_tower[tower_data.tower_unit_number] = connection_data return true end else tesla_coil.remove_target(target_data.unit_number) end end --- @param target_data TargetData --- @param tower_data TowerData function tesla_coil.update_connection(target_data, tower_data) local absorber = target_data.grid_data.absorber -- Check if the tower is powered if not absorber or not absorber.valid or tower_data.entities.tower.energy < constants.tesla_coil.required_energy then tesla_coil.remove_connection(target_data, tower_data) return end local capacity = global.tesla_coil.absorber_buffer_capacity local energy = absorber.energy if energy < capacity then -- Calculate how much to add local to_add = constants.tesla_coil.charging_rate / 60 * constants.tesla_coil.cooldown local result = energy + to_add local tower = tower_data.entities.tower if result >= capacity then absorber.energy = capacity target_data.full_tick = game.tick else absorber.energy = result target_data.full_tick = nil end tower.energy = tower.energy - (to_add * constants.tesla_coil.loss_multiplier) elseif target_data.full_tick and target_data.full_tick + constants.tesla_coil.cooldown <= game.tick then tesla_coil.remove_connection(target_data, tower_data) end end --- @param target_data TargetData --- @param tower_data TowerData function tesla_coil.remove_connection(target_data, tower_data) local connection_data = target_data.connections.by_tower[tower_data.tower_unit_number] -- Destroy beam if it still exists if connection_data.beam.valid then connection_data.beam.destroy() end local beam_number = connection_data.beam_number global.tesla_coil.beams[beam_number] = nil target_data.connections.by_beam[beam_number] = nil target_data.connections.by_tower[tower_data.tower_unit_number] = nil if table_size(target_data.connections.by_beam) == 0 then tesla_coil.remove_target(target_data.unit_number) end end --- @param target LuaEntity --- @param turret LuaEntity function tesla_coil.process_turret_fire(target, turret) local tower_data = global.tesla_coil.turrets[turret.unit_number] if not tower_data then return end local target_data = global.tesla_coil.targets[target.unit_number] if not target_data then target_data = tesla_coil.add_target(target, tower_data) end if target_data then -- Just in case (#182) if not target_data.entity.valid then target_data.entity = target end local connection = target_data.connections.by_tower[tower_data.tower_unit_number] if connection or tesla_coil.add_connection(target_data, tower_data) then tesla_coil.update_connection(target_data, tower_data) end end end return tesla_coil
import { EditOutlined, EllipsisOutlined, PlusOutlined, SettingOutlined } from '@ant-design/icons'; import { Button, Tag, Image, Input, Switch, Card, Avatar } from 'antd'; import { ModalForm } from '@ant-design/pro-form'; import React from 'react'; import { PageContainer } from '@ant-design/pro-layout'; import ResoTable from '@/components/ResoTable/ResoTable'; import PostForm from '@/components/Form/b_PostForm/PostForm'; import { activationById, createPost, deletePost, updatePost, updatePostById } from '@/services/b_post'; import AsyncButton from '@/components/AsyncButton'; import moment from 'moment'; import { useHistory } from 'umi'; // import Meta from 'antd/lib/card/Meta'; const PostListPage = () => { const { Meta } = Card; const ref = React.useRef(); const [selectedRows, setSelectedRows] = React.useState([]); const [visibleadd, setVisibleadd] = React.useState(false); const [visibleadds, setVisibleadds] = React.useState(false); const rowSelection = { selectedRowKeys: selectedRows, onChange: setSelectedRows, type: 'radio', }; const delectePostHandler = () => { return deletePost(selectedRows[0]).then(() => ref.current?.reload()); }; const createHandler = async (values) => { console.log(`values`, values); let data = { ...values }; const res = await createPost(data); setVisibleadds(false); setVisibleadd(false); ref.current?.reload(); return true; }; const activationHandler = (data) => { // Promise.resolve(activationById(data.id, { ...data })).then(() => { // ref.current?.reload(); // }); Promise.resolve(updatePostById(post.id, { ...post })).then(() => { ref.current?.reload(); }); }; const history = useHistory(); return ( <PageContainer title="Danh sách bài viết"> <ResoTable search={true} actionRef={ref} scroll={{ x: 650, }} columns={[ { title: 'Tiêu đề', dataIndex: 'title', hideInTable: true, // sorter: (a, b) => a.userName > b.userName, }, { title: 'Bài viết', dataIndex: 'id', width: 240, search: false, render: (_, post) => ( <Card hoverable cover={<img src={post.cover} />} style={{ width: 350 }} actions={[ // <SettingOutlined key="setting" />, <EditOutlined key="edit" onClick={() => history.push(`/posts/${post.id}`)}/>, // <EllipsisOutlined key="ellipsis" />, ]} > <Meta avatar={<Avatar src={post.author.avatarLink} />} title={post.title} description={post.author.userName} // description={post.content} /> </Card> ), }, ]} toolBarRender={() => [ <ModalForm title="Tạo bài viết" modalProps={{ destroyOnClose: true, }} visible={visibleadd} onValuesChange={console.log} onFinishFailed={console.log} name="create-post" key="create-post" onFinish={createHandler} submitter={{ render: (props, defaultDoms) => { return [ // ...defaultDoms, <Button key="cancel" onClick={() => { setVisibleadd(false); }} > Hủy </Button>, <Button key="ok" type='primary' onClick={() => { try { props.form.validateFields().then((values) => { console.log(`values`, values); createHandler(values); props.reset(); }); } catch (error) { console.log(`error`, error); } }} > Tạo </Button>, ]; }, }} trigger={<Button icon={<PlusOutlined />} type="primary" onClick={() => history.push(`/posts/create`)} >Tạo bài viết</Button>} > <PostForm /> </ModalForm>, ]} rowKey="id" resource="posts" additionParams={{ orderBy: 'createAt-dec' }} isShowSelection={false} /> </PageContainer> ); }; export default PostListPage;
/* eslint-disable @typescript-eslint/no-explicit-any */ import { useEffect, useState } from "react"; import { action } from "../../src/services/ShareServiceAPI"; import { ShareRequest } from "../../src/interfaces/ShareRequest"; import "./ShareComponent.css"; const ShareComponent: React.FC<ShareRequest> = ({ symbol }) => { const [share, setShareData] = useState<any | null>(null); const [loading, setLoading] = useState<boolean | null>(true); const [error, setError] = useState<string | null>(null); useEffect(() => { action (symbol) .then((response) => { setShareData(response.data); setLoading(false); }) .catch((err) => { setError(err.message); setLoading(false); }); }, [symbol]); if (loading) return <div> Loading ...</div>; if (error) return <div> Error: {error}</div>; return ( <> <div className="card"> <img src={share?.logourl} alt={`${share?.shortName} Logo`} width={100} /> <h1>{share?.shortName}</h1> <p>{share?.longName}</p> <p>Simbolo: {share?.symbol}</p> <p>Moeda: {share?.currency}</p> <p>Preço: {share?.priceEarnings?.toFixed(2)}</p> <p>Lucro por ação: {share?.earningsPerShare?.toFixed(2)}</p> </div> </> ); }; export default ShareComponent;
import * as express from 'express'; import * as bookServ from '../services/book.service'; import * as reviewServ from '../services/reviews.service'; import OktaJwtVerifier = require('@okta/jwt-verifier'); export const routes = express.Router(); import * as log4js from 'log4js'; const log = log4js.getLogger("review"); const oktaJwtVerifier = new OktaJwtVerifier({ issuer: 'https://dev-88273664.okta.com/oauth2/default' // required }); // Only let the user access the route if they are authenticated. function ensureAuthenticated(req, res, next) { const authHeader = req.headers.authorization || ''; const match = authHeader.match(/Bearer (.+)/); // The expected audience passed to verifyAccessToken() is required, and can be either a string (direct match) or // an array of strings (the actual aud claim in the token must match one of the strings). const expectedAudience = 'api://default'; if (!match) { res.status(401); return next('Unauthorized'); } const accessToken = match[1]; return oktaJwtVerifier.verifyAccessToken(accessToken, expectedAudience) .then((jwt) => { req.jwt = jwt; next(); }) .catch((err) => { log.error('Authenticated failed',err); console.log(err); res.status(401).send({message:err.message}); }); } routes.get("/books",ensureAuthenticated, bookServ.allBooks); routes.get("/books/:id", ensureAuthenticated, bookServ.getBook); routes.post("/books", ensureAuthenticated, bookServ.addBook); routes.put("/books/:id", ensureAuthenticated, bookServ.updateBook); routes.delete("/books/:id", ensureAuthenticated, bookServ.deleteBook); routes.get("/books/:id/reviews", ensureAuthenticated, reviewServ.allReviews); routes.get("/books/:id/reviews/:review_id", ensureAuthenticated, reviewServ.getReview); routes.post("/books/:id/reviews", ensureAuthenticated, reviewServ.addReview); routes.put("/books/:id/reviews/:review_id", ensureAuthenticated, reviewServ.updateReview); routes.delete("/books/:id/reviews/:review_id", ensureAuthenticated, reviewServ.deleteReview);
class_name LogicGrid extends GridContainer # Tile object that will be instantiated across the grid const _tile_template = preload("res://objects/tile.tscn") ## Number of rows in the grid @export_range(0, 20) var num_rows : int = 4: set(value): if value < 1: return num_rows = value _resize() ## Number of columns in the grid @export_range(0, 20) var num_cols : int = 4: set(value): if value < 1: return num_cols = value _resize() ## Current tool instance var current_tool : Tool = preload("res://scripts/tools/tool_test.gd").new(): set(value): cancel_tool() current_tool = value # Internal array of tiles, generally do not update directly var _tiles: Array[Tile] # Grid representing the current displayed state of the tiles var _display_grid : Grid # Position of the tile the mouse is currently over var _hovered_tile : Vector2i # Whether there is currenty a tool in the process of being used var _tool_in_progress : bool # Copy of the grid from before the current tool started being used var _tool_initial_grid : Grid # Path the mouse has taken over the course of the current tool var _tool_path : Array[Vector2i] # Stack of previous grids for undo to use var _undo_history : Array[UndoState] # Called on start func _ready() -> void: # Ensure the grid exists _resize() # Save the initial state as the earliest state to undo to _undo_history = [UndoState.new(_display_grid)] _tool_initial_grid = _display_grid.copy() ## Set the grid the given grid func set_grid(grid : Grid) -> void: cancel_tool() num_rows = grid.num_rows num_cols = grid.num_cols _display_grid = grid.copy() _tool_initial_grid = _display_grid.copy() func get_grid() -> Grid: return _tool_initial_grid # Adds a position to the tool path, backtracking if we've already visited it func _add_pos_to_tool_path(pos : Vector2i) -> void: var existing_index := _tool_path.find(pos) if existing_index != -1: # We've gone backwards _tool_path.resize(existing_index + 1) else: _tool_path.append(pos) # Called when the mouse moves over a new tile func _tile_mouse_entered(pos : Vector2i) -> void: if _tool_in_progress: # Step towards pos incrementally to ensure only orthogonal movements var old_pos := _tool_path[-1] while old_pos != pos: var delta := pos - old_pos if absi(delta.x) > absi(delta.y): old_pos.x += signi(delta.x) else: old_pos.y += signi(delta.y) _add_pos_to_tool_path(old_pos) _add_pos_to_tool_path(pos) _hovered_tile = pos if current_tool.one_click: _tool_path = [_hovered_tile] # Handles mouse input for starting and finishing tools func _gui_input(event : InputEvent) -> void: if not event is InputEventMouseButton: return var mouse_event : InputEventMouseButton = event if mouse_event.button_index == MOUSE_BUTTON_LEFT: if mouse_event.pressed: # Mouse was pressed, start the tool if valid _start_tool() else: # Mouse was released, finish the tool _end_tool() elif mouse_event.button_index == MOUSE_BUTTON_RIGHT and mouse_event.pressed: # Undo on right-click _undo() func _unhandled_key_input(event: InputEvent) -> void: if not event is InputEventKey: return var key_event : InputEventKey = event if key_event.pressed: match key_event.keycode: KEY_RIGHT: current_tool.rotate() KEY_LEFT: current_tool.rotate(true) # Called every frame func _process(_delta : float) -> void: # Update tool preview if _tool_in_progress or current_tool.one_click: var preview_grid := _tool_initial_grid.copy() var success := current_tool.apply(preview_grid, _tool_path, true) if success: _display_grid = preview_grid # Actually display the states in _display_grid for i in _tiles.size(): _tiles[i].state = _display_grid.get_state(_display_grid.index_to_pos(i)) _tiles[i].highlight = _display_grid.get_highlight(_display_grid.index_to_pos(i)) # Resizes/creates the grid func _resize() -> void: columns = num_cols # Create new _display_grid var states: Array[Tile.State] = [] states.resize(num_rows * num_cols) states.fill(Tile.State.LIGHT) var new_display_grid := Grid.new(num_rows, num_cols, states) # Copy over old _display_grid if _display_grid: for row in num_rows: for col in num_cols: var pos := Vector2i(col, row) if _display_grid.valid_pos(pos): new_display_grid.set_state(pos, _display_grid.get_state(pos)) _display_grid = new_display_grid # Destroy old tiles for tile in _tiles: tile.queue_free() # Instantiate tiles _tiles = [] for i in range(num_rows * num_cols): var tile : Tile = _tile_template.instantiate() #var tile : Tile = preload("res://scripts/tile.gd").new() add_child(tile) _tiles.append(tile) tile.state = _display_grid.get_state(_display_grid.index_to_pos(i)) # Get notified when the mouse hovers over the tile, with the tile's position tile.mouse_entered.connect(_tile_mouse_entered.bind(_display_grid.index_to_pos(i))) # Start the current tool func _start_tool() -> void: if current_tool.one_click: _tool_in_progress = true _end_tool() return if not current_tool.valid_start_pos(_display_grid, _hovered_tile): return _tool_in_progress = true _tool_initial_grid = _display_grid.copy() _tool_path = [_hovered_tile] # End the current tool, committing its results if they are valid func _end_tool() -> void: if not _tool_in_progress: return var tool_final_grid := _tool_initial_grid.copy() var success := current_tool.apply(tool_final_grid, _tool_path) if success: _display_grid = tool_final_grid _undo_history.append(UndoState.new(_tool_initial_grid.copy())) _tool_initial_grid = _display_grid.copy() else: _display_grid = _tool_initial_grid _tool_in_progress = false # Cancel the current tool, always discarding the current results func cancel_tool() -> void: _display_grid = _tool_initial_grid _tool_path = [_hovered_tile] _tool_in_progress = false class UndoState: var grid : Grid func _init(g : Grid) -> void: grid = g # Undo the last successful move func _undo() -> void: # Don't allow undos midway through a tool if _tool_in_progress: return # There needs to actually be something to undo (other than the initial state) if _undo_history.size() <= 1: return # Get the last state in the history var state : UndoState = _undo_history[-1] # Remove the obtained state _undo_history.resize(_undo_history.size() - 1) # Restore the state _display_grid = state.grid _tool_initial_grid = _display_grid.copy()
from django.db.models import Q from django.http import JsonResponse from django.shortcuts import redirect from django.views.generic import ListView, DetailView from django.views.generic.base import View from movies.models import Movie, Category, Actor, Genre from .forms import ReviewForm class GengeYear: """ Жанры и года выходов фильмов """ def get_genres(self): return Genre.objects.all() def get_years(self): return Movie.objects.filter(draft=False).values('year') class MoviesView(GengeYear, ListView): """ Список фильмов """ model = Movie queryset = Movie.objects.filter(draft=False) class MovieDetailView(GengeYear, DetailView): """ Полное описание фильма""" model = Movie slug_field = 'url' class AddReview(View): """Отзывы""" def post(self, request, pk): form = ReviewForm(request.POST) movie = Movie.objects.get(id=pk) if form.is_valid(): form = form.save(commit=False) if request.POST.get('parent', None): form.parent_id = int(request.POST.get('parent')) form.movie = movie form.save() return redirect(movie.get_absolute_url()) class ActorView(GengeYear, DetailView): """ Вывод информации об Актере""" model = Actor template_name = 'movies/actor.html' slug_field = 'name' class FilterMoviesView(GengeYear, ListView): """ Фильтр фильмов """ def get_queryset(self): queryset = Movie.objects.filter( Q(year__in=self.request.GET.getlist("year")) | Q(genres__in=self.request.GET.getlist("genre")) ) return queryset class JsonFilterMoviesView(ListView): """Фильтр фильмов в json""" def get_queryset(self): queryset = Movie.objects.filter( Q(year__in=self.request.GET.getlist("year")) | Q(genres__in=self.request.GET.getlist("genre")) ).distinct().values("title", "tagline", "url", "poster") return queryset def get(self, request, *args, **kwargs): queryset = list(self.get_queryset()) return JsonResponse({"movies": queryset}, safe=False)
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', template: ` <h1>{{title}}</h1> <p>Heroes:</p> <ul> <li *ngFor="let hero of heroes"> {{ hero }} </li> </ul> <button [disabled]="isDisabled"> with interpolation </button> <button disabled={{isDisabled}}> with property </button> `, styleUrls: ['./test.component.css'], }) export class TestComponent { title = 'Tour of Heroes'; heroes = ['Windstorm', 'Bombasto', 'Magneta', 'Tornado']; myHero = this.heroes[0]; isDisabled = false; }
<?php /** * The header for our theme * * @package Gomeeki * @subpackage Test Gomeeki * @since 1.0 * @version 1.0 */ ?><!DOCTYPE html> <html <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo( 'charset' ); ?>"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="profile" href="http://gmpg.org/xfn/11"> <meta name="description" content=""> <meta name="author" content=""> <title><?php echo bloginfo('name') . (is_front_page() ? '' : ' - ' . get_the_title()); ?></title> <!-- Bootstrap Core CSS --> <link href="<?php echo get_template_directory_uri(); ?>/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Theme CSS --> <link href="<?php echo get_template_directory_uri(); ?>/style.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="<?php echo get_template_directory_uri(); ?>/vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> <!-- Navigation --> <nav class="navbar navbar-default navbar-custom navbar-fixed-top"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header page-scroll"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> Menu <i class="fa fa-bars"></i> </button> <a class="navbar-brand" href="<?php echo site_url(); ?>">Start Bootstrap</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <?php wp_nav_menu( array( 'theme_location' => 'primary', 'container_class' => 'collapse navbar-collapse', 'container_id' => 'bs-example-navbar-collapse-1', 'menu_class' => 'nav navbar-nav navbar-right', ) ); ?> <!-- /.navbar-collapse --> </div> <!-- /.container --> </nav><!-- Page Header --> <!-- Set your background image for this header on the line below. --> <header class="intro-header" style="background-image: url('<?php the_post_thumbnail_url('full'); ?>')"> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <?php if (is_front_page()) { ?> <div class="site-heading"> <h1><?php echo bloginfo('name'); ?></h1> <hr class="small"> <span class="subheading"><?php echo bloginfo('description'); ?></span> </div> <?php } elseif (is_page()) { ?> <div class="page-heading"> <h1><?php the_title(); ?></h1> <hr class="small"> <span class="subheading"><?php echo get_field('subheading'); ?></span> </div> <?php } else { if (have_posts()) { the_post(); } ?> <div class="post-heading"> <h1><?php the_title(); ?></h1> <h2 class="subheading"><?php echo get_field('subheading'); ?></h2> <span class="meta">Posted by <?php the_author_posts_link(); ?> on <?php the_date(); ?></span> </div> <?php } ?> </div> </div> </div> </header>
import useScript from "react-script-hook"; import { globalCss } from "@webstudio-is/design-system"; import { useCallback, useEffect, useRef, useState } from "react"; import { trpcClient } from "../trpc/trpc-client"; const scriptAttributes = { async: true, defer: true, importance: "low", src: "https://cdn.goentri.com/entri.js", }; // https://developers.entri.com/docs/install export type DnsRecord = { type: "CNAME" | "TXT"; host: string; value: string; ttl: number; }; // https://developers.entri.com/docs/integrate-with-dns-providers export type EntriCloseDetail = { domain: string; lastStatus: | "FINISHED_SUCCESSFULLY" | "IN_PROGRESS" | "EXISTING_RECORDS" | "LOGIN" | "MANUAL_CONFIGURATION" | "EXIT_WITH_ERROR" | "DKIM_SETUP"; provider: string; setupType: "automatic" | "manual" | "sharedLogin" | null; success: boolean; }; declare global { interface Window { // https://developers.entri.com/docs/api-reference entri?: { showEntri: (options: { applicationId: string; token: string; dnsRecords: DnsRecord[]; prefilledDomain: string; }) => void; }; } // https://developers.entri.com/docs/integrate-with-dns-providers interface WindowEventMap { onEntriClose: CustomEvent<EntriCloseDetail>; } } /** * Our FloatingPanelPopover adds pointerEvents: "none" to the body. * We open the entry dialog from the popover, so we need to allow pointer events on the entri dialog. */ export const entriGlobalStyles = globalCss({ body: { "&>#entriApp": { pointerEvents: "all", }, }, }); type UseEntriProps = { domain: string; onClose: (detail: EntriCloseDetail) => void; dnsRecords: DnsRecord[]; }; export const useEntri = ({ domain, dnsRecords, onClose }: UseEntriProps) => { const [isScriptLoading, scriptLoadingError] = useScript(scriptAttributes); const [error, setError] = useState<string | undefined>(undefined); const [isOpen, setIsOpen] = useState(false); const showDialogInternalRef = useRef< undefined | ((token: string, applicationId: string) => void) >(undefined); const { load: entriTokenLoad, data: entriTokenData, error: entriTokenSystemError, } = trpcClient.domain.getEntriToken.useQuery(); useEffect(() => { const handleOnEntriClose = (event: CustomEvent<EntriCloseDetail>) => { if (event.detail.domain !== domain) { return; } onClose(event.detail); setIsOpen(false); }; window.addEventListener("onEntriClose", handleOnEntriClose, false); return () => { window.removeEventListener("onEntriClose", handleOnEntriClose); }; }, [domain, onClose]); const showDialogInternal = useCallback( (token: string, applicationId: string) => { const entri = window.entri; if (entri === undefined) { if (isScriptLoading) { setError("Entri is not loaded, try again later"); return; } setError("Entri is not loaded"); return; } entri.showEntri({ applicationId, token, dnsRecords, prefilledDomain: domain, }); }, [dnsRecords, domain, isScriptLoading] ); showDialogInternalRef.current = showDialogInternal; const showDialog = useCallback(() => { setIsOpen(true); entriTokenLoad(undefined, (data) => { if (data.success === false) { return; } if (showDialogInternalRef.current === undefined) { return; } const { token, applicationId } = data; showDialogInternalRef.current(token, applicationId); }); }, [entriTokenLoad]); return { isOpen, showDialog, error: error ?? entriTokenSystemError ?? scriptLoadingError?.message ?? (entriTokenData?.success === false ? entriTokenData.error : undefined), }; };
import { db } from "@/lib/db"; import { auth } from "@clerk/nextjs"; import { NextResponse } from "next/server"; export async function GET() { try { const pet = await db.pet.findMany(); return NextResponse.json(pet); } catch (error) { console.log("Pet GET Error: ", error); return new NextResponse("Internal Error", { status: 500 }); } } export async function POST(req: Request) { try { const { userId } = auth(); const { name, species, age, color, favoriteFood, favoriteActivity } = await req.json(); const newPet = await db.pet.create({ data: { name, species, age: parseInt(age), color, favoriteFood, favoriteActivity, ownerId: userId, }, }); return NextResponse.json(newPet); } catch (error) { console.error("Pet POST Error: ", error); return new NextResponse("Internal Error", { status: 500 }); } } export async function PATCH(req: Request) { try { const { userId } = auth(); const { petId, ...updatedData } = await req.json(); const pet = await db.pet.findUnique({ where: { id: petId, }, }); if (!pet || pet.ownerId !== userId) { return new NextResponse("Pet not found or unauthorized", { status: 403 }); } const updatedPet = await db.pet.update({ where: { id: petId, }, data: updatedData, }); return NextResponse.json(updatedPet); } catch (error) { console.error("Pet PATCH Error: ", error); return new NextResponse("Internal Error", { status: 500 }); } } export async function DELETE(req: Request) { try { const { userId } = auth(); const { petId } = await req.json(); const pet = await db.pet.findUnique({ where: { id: petId, }, }); if (!pet || pet.ownerId !== userId) { return new NextResponse("Pet not found or unauthorized", { status: 403 }); } await db.pet.delete({ where: { id: petId, }, }); return NextResponse.json(pet); } catch (error) { console.log("Pet DELETE Error: ", error); return new NextResponse("Internal Error", { status: 500 }); } }
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { of } from 'rxjs'; import { HttpHeaders, HttpResponse } from '@angular/common/http'; import { HomeAutomationTestModule } from '../../../test.module'; import { PieceComponent } from 'app/entities/piece/piece.component'; import { PieceService } from 'app/entities/piece/piece.service'; import { Piece } from 'app/shared/model/piece.model'; describe('Component Tests', () => { describe('Piece Management Component', () => { let comp: PieceComponent; let fixture: ComponentFixture<PieceComponent>; let service: PieceService; beforeEach(() => { TestBed.configureTestingModule({ imports: [HomeAutomationTestModule], declarations: [PieceComponent] }) .overrideTemplate(PieceComponent, '') .compileComponents(); fixture = TestBed.createComponent(PieceComponent); comp = fixture.componentInstance; service = fixture.debugElement.injector.get(PieceService); }); it('Should call load all on init', () => { // GIVEN const headers = new HttpHeaders().append('link', 'link;link'); spyOn(service, 'query').and.returnValue( of( new HttpResponse({ body: [new Piece(123)], headers }) ) ); // WHEN comp.ngOnInit(); // THEN expect(service.query).toHaveBeenCalled(); expect(comp.pieces && comp.pieces[0]).toEqual(jasmine.objectContaining({ id: 123 })); }); }); });
import React, { useState, useEffect } from 'react' const Meme = () => { const [formData, setFormData] = React.useState({ topText: '', bottomText: '', randomImage: 'https://imgflip.com/s/meme/Drake-Hotline-Bling.jpg' }); const [allMemeImages, setAllMemeImages] = useState([]); useEffect(() => { fetch('https://api.imgflip.com/get_memes') .then((response) => response.json()) .then((data) => setAllMemeImages(data.data.memes)); }, []) console.log({allMemeImages}); function getMemeImage(url) { setFormData(prevImage => { return { ...prevImage, randomImage: url } }); } function handleClick () { const totalMeme = allMemeImages.length; getMemeImage(allMemeImages[Math.floor(Math.random() * totalMeme)].url); } function handleChange(event) { const { value, name } = event.target; setFormData((prevData) => { return { ...prevData, [name]: [value] } }) } return ( <main> <div className='form--container'> <input type="text" placeholder='Top Text' name='topText' onChange={handleChange} value={formData.topText} className='form--inputField' /> <input type="text" placeholder='Bottom Text' name='bottomText' onChange={handleChange} value={formData.bottomText} className='form--inputField' /> <button className='form--submitBtn' onClick={(event) => handleClick(event)}>Get a new meme image 🖼</button> <div className="meme"> <img className='form--meme-image' src={formData.randomImage} alt={formData.randomImage} /> <h2 className='meme--text top'>{formData.topText}</h2> <h2 className='meme--text bottom'>{formData.bottomText}</h2> </div> </div> </main> ) } export default Meme
import { PickType } from '@nestjs/swagger'; import { IsEmail, IsNotEmpty, IsString, IsStrongPassword, } from 'class-validator'; import { Dto } from 'src/lib/dto/Dto'; export class SignUpDto extends Dto<SignUpDto> { @IsNotEmpty() name: string; @IsEmail() @IsNotEmpty({ message: '이메일을 입력해주세요.', }) email: string; @IsString() @IsNotEmpty({ message: '비밀번호를 입력해주세요.', }) password: string; @IsNotEmpty({ message: '비밀번호 확인을 입력해주세요.', }) // @IsStrongPassword( // { // minLength: 6, // }, // { // message: // '비밀번호는 최소 6자리에 숫자, 영문 대문자, 영문 소문자, 특수문자가 포함되어야 합니다.', // }, // ) passwordConfirm: string; }
package Leetcode.LCP; import java.util.*; public class LCP_0035_ElectricCarPlan { //用一个三元组{cur,time,rest}代表从start到cur花费time的时间,还剩下rest的电量 //用优先级队列来保证每次选出一个目前距离最近的结点来尝试移动,前提是rest电量足够 public int electricCarPlan(int[][] paths, int cnt, int start, int end, int[] charge) { final int n=charge.length; List<int[]>[] map=new List[n];//map[i]是一个List,里面放的是i结点的边,{to,distance} for(int i=0;i<n;i++) map[i]=new ArrayList<>(); for(var p:paths){//p={cityA,cityB,distance} map[p[0]].add(new int[]{p[1],p[2]}); map[p[1]].add(new int[]{p[0],p[2]}); } var visit=new boolean[n][cnt+1];//visit[i][j]:是否已经从start到达过i城市,到达时有j电 var pq=new PriorityQueue<int[]>((a, b)->a[1]-b[1]);//按照第二维度time来做小根堆 pq.add(new int[]{start,0,0});//当前在start结点,时间0,还剩下0的电 while(!pq.isEmpty()){ var node=pq.poll(); int cur=node[0],time=node[1],rest=node[2]; if(visit[cur][rest]) continue; visit[cur][rest]=true; if(cur==end) return time; //上面如果没有返回,说明没到end,那么在当前结点就有两种选择,一种是充电,一种是走路 for(int i=rest+1;i<=cnt;i++){//充到i的电量才走 pq.add(new int[]{cur,time+(i-rest)*charge[cur],i}); } var nexts=map[cur];//从cur出发能到哪些结点 for(var next:nexts){//next={to,distance} int to=next[0],distance=next[1]; if(rest>=distance&&!visit[to][rest-distance]){//to没去过 且 当前剩余的电量足够开到to pq.add(new int[]{to,time+distance,rest-distance}); } } } return -1; } }
package com.example; import static org.junit.Assert.*; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.junit.After; import org.junit.Before; import org.junit.Test; public class UserCrudIntegrationTest { private UserCrud userCrud; private Connection connection; private DatabaseConnection databaseConnection; @Before public void setUp() throws SQLException { userCrud = new UserCrud(); databaseConnection = new DatabaseConnection(); connection = databaseConnection.getConnection(); } @After public void tearDown() throws SQLException { if (connection != null) { connection.close(); } } @Test public void integrationTestCreateUser() throws SQLException { User user = new User("packman", 22, "haha@gmail.com"); userCrud.createUser(user); assertTrue(userCrud.readById(user.getId())); } @Test public void integrationTestDeleteById() throws SQLException { User user = new User("packman", 22, "haha@gmail.com"); userCrud.createUser(user); userCrud.deleteById(user.getId()); assertFalse(userCrud.readById(user.getId())); } @Test public void integrationTestReadAll() throws SQLException { User user1 = new User("packman", 22, "haha@gmail.com"); userCrud.createUser(user1); User user2 = new User("mario", 21, "oink@gmail.com"); userCrud.createUser(user2); User user3 = new User("vanila", 13, "ice@gmail.com"); userCrud.createUser(user3); userCrud.readAll(); int numberOfUsers = countUsers(); assertEquals(3, numberOfUsers); } private int countUsers() throws SQLException { try (Connection connection = databaseConnection.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement("SELECT COUNT(USER_ID) FROM USER"); ResultSet resultSet = preparedStatement.executeQuery()) { if (resultSet.next()) { return resultSet.getInt(1); } } return 0; } @Test public void integrationTestReadById() throws SQLException { User user = new User("packman", 22, "haha@gmail.com"); userCrud.createUser(user); boolean userFound = userCrud.readById(user.getId()); assertTrue(userFound); } @Test public void integrationTestReadByIdNoUser() throws SQLException { boolean userNotFound = userCrud.readById(-1); assertFalse(userNotFound); } @Test public void integrationTestUpdateById() throws SQLException { User user = new User("packman", 22, "haha@gmail.com"); userCrud.createUser(user); User retrievedUser = getUserById(user.getId()); assertNotNull(retrievedUser); User updatedUser = new User(user.getId(), "packman", 24, "hahaha@gmail.com"); userCrud.updateById(updatedUser); retrievedUser = getUserById(user.getId()); assertNotNull(retrievedUser); assertEquals(updatedUser.getNickname(), retrievedUser.getNickname()); assertEquals(updatedUser.getAge(), retrievedUser.getAge()); assertEquals(updatedUser.getAddress(), retrievedUser.getAddress()); } private User getUserById(int id) throws SQLException { User user = null; try (Connection connection = databaseConnection.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(Query.readByIdQuery(id))) { try (ResultSet resultSet = preparedStatement.executeQuery()) { if (resultSet.next()) { user = new User( resultSet.getInt("USER_ID"), resultSet.getString("USER_NICKNAME"), resultSet.getInt("USER_AGE"), resultSet.getString("USER_EMAIL") ); } } } return user; } }
import React, { useState, useContext, useEffect, useRef } from 'react'; import useWebSocket, { ReadyState } from 'react-use-websocket'; import InfiniteScroll from 'react-infinite-scroll-component'; import { AuthContext } from '../contexts/AuthContext'; import { useParams } from 'react-router-dom'; import { useHotkeys } from 'react-hotkeys-hook'; import { ChatLoader } from './ChatLoader'; import { ConversationModel } from '../models/Conversation'; import { MessageModel } from '../models/Message'; import { Message } from './Message'; export function Chat() { const { chatName } = useParams(); const [welcomeMessage, setWelcomeMessage] = useState(''); const [messageHistory, setMessageHistory] = useState<MessageModel[]>([]); const [message, setMessage] = useState(''); const [page, setPage] = useState(2); const [hasMoreMessages, setHasMoreMessages] = useState(false); const [conversation, setConversation] = useState<ConversationModel | null>( null, ); const [participants, setParticipants] = useState<string[]>([]); const [userTyping, setUserTyping] = useState(false); const timeOut = useRef<any>(); const [typing, setTyping] = useState(false); const { user } = useContext(AuthContext); const updateTyping = (event: { user: string; typing: boolean }) => { if (event.user !== user!.username) { setTyping(event.typing); } }; const { readyState, sendJsonMessage } = useWebSocket( user ? `ws://127.0.0.1:8000/${chatName}/` : null, { queryParams: { token: user ? user.token : '', }, onOpen: () => { console.log('Connected!'); }, onClose: () => { console.log('Disconnected!'); }, // onMessage handler onMessage: (e) => { const data = JSON.parse(e.data); switch (data.type) { case 'welcome_message': setWelcomeMessage(data.message); break; case 'chat_message_echo': setMessageHistory((prev: any) => [data.message, ...prev]); break; case 'last_50_messages': setMessageHistory(data.messages); setHasMoreMessages(data.has_more); break; case 'user_joined': setParticipants((users: string[]) => { if (!users.includes(data.user)) { return [...users, data.user]; } return users; }); break; case 'user_left': setParticipants((users: string[]) => { const newUser = users.filter((user) => user !== data.user); return newUser; }); break; case 'online_users': setParticipants(data.users); break; case 'typing': updateTyping(data); break; default: console.error('Unknown message type!'); break; } }, }, ); const connectionStatus = { [ReadyState.CONNECTING]: 'Connecting', [ReadyState.OPEN]: 'Open', [ReadyState.CLOSING]: 'Closing', [ReadyState.CLOSED]: 'Closed', [ReadyState.UNINSTANTIATED]: 'Uninstantiated', }[readyState]; /** * The function `onType` handles user typing events and sends a JSON message indicating that the user * is typing, with a timeout to stop indicating typing after a certain period of time. */ const onType = () => { if (userTyping === false) { setUserTyping(true); sendJsonMessage({ type: 'typing', typing: true }); timeOut.current = setTimeout(timeOutFunc, 5000); // timeout after five seconds } else { clearTimeout(timeOut.current); timeOut.current = setTimeout(timeOutFunc, 5000); } }; useEffect(() => () => clearTimeout(timeOut.current), []); function handleChangeMessage(e: any) { setMessage(e.target.value); onType(); } const handleSubmit = () => { if (message.length === 0) return; if (message.length > 600) return; sendJsonMessage({ type: 'chat_message', message, }); setMessage(''); clearTimeout(timeOut.current); timeOutFunc(); }; async function fetchMessages() { const res = await fetch( `http://127.0.0.1:8000/api/messages/?conversation=${chatName}&page=${page}`, { method: 'GET', headers: { 'Content-Type': 'application/json', Authorization: `Token ${user?.token}`, Accept: 'application/json', }, }, ); if (res.status === 200) { const data: { count: number; next: string | null; // URL previous: string | null; // URL results: MessageModel[]; } = await res.json(); setHasMoreMessages(data.next != null); setPage(page + 1); setMessageHistory((prev: MessageModel[]) => prev.concat(data.results)); } } useEffect(() => { async function fetchConversations() { const res = await fetch( `http://127.0.0.1:8000/api/conversations/${chatName}/`, { method: 'GET', headers: { 'Content-Type': 'application/json', Authorization: `Token ${user?.token}`, Accept: 'application/json', }, }, ); if (res.status === 200) { const data: ConversationModel = await res.json(); setConversation(data); } } fetchConversations(); }, [conversation, user]); const inputRef: any = useHotkeys( 'enter', () => { handleSubmit(); }, { enableOnFormTags: ['INPUT'], }, ); useEffect(() => { (inputRef.current as HTMLElement).focus(); }, [inputRef]); const timeOutFunc = () => { setUserTyping(false); sendJsonMessage({ type: 'typing', typing: false }); }; return ( <div> <span>The WebSocket is currently {connectionStatus}</span> {conversation && ( <div className="py-6"> <h3 className="text-3xl font-semibold text-gray-900"> Chat with user: {conversation.other_users.username} </h3> <span className="text-sm"> {conversation.other_users.username} is currently {participants.includes(conversation.other_users.username) ? ' online' : ' offline'} </span> </div> )} <p>{welcomeMessage}</p> <div id="scrollableChatDiv" className="h-[20rem] mt-3 flex flex-col-reverse relative w-full border border-gray-200 overflow-y-auto p-6" > <div> <InfiniteScroll dataLength={messageHistory.length} next={fetchMessages} className="flex flex-col-reverse" inverse={true} hasMore={hasMoreMessages} loader={<ChatLoader />} scrollableTarget="scrollableChatDiv" > {messageHistory.map((message: MessageModel) => ( <Message key={message.id} message={message} /> ))} </InfiniteScroll> {typing && ( <p className="truncate text-sm text-gray-500">typing...</p> )} </div> </div> <hr /> <input name="message" placeholder="Message" onChange={handleChangeMessage} value={message} required ref={inputRef} maxLength={600} className="block w-full rounded bg-gray-100 p-2 outline-none focus:text-gray-700 w-96" /> <button className="ml-3 bg-gray-300 px-3 py-1 my-3 rounded w-24" onClick={handleSubmit} > Send </button> </div> ); }
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HomeComponent } from './routes/home/home.component'; import { MyProjectsComponent } from './routes/my-projects/my-projects.component'; import { BlogComponent } from './routes/blog/blog.component'; import { BlogDisplayerComponent } from './routes/blog/sub-components/blog-displayer/blog-displayer.component'; const routes: Routes = [ {path: '', component: HomeComponent, title: 'About Gabriele Gatti'}, {path: 'projects/.', component: MyProjectsComponent, title: 'My Projects'}, {path: 'blogs/.', component: BlogDisplayerComponent, title: 'My Blogs'}, {path: 'blogs/:topic/.', component: BlogDisplayerComponent, title: 'My Blogs'}, {path: 'blog/:topic/:title/.', component: BlogComponent, title: 'My Blogs'}, {path: '**', component: HomeComponent}, ]; @NgModule({ imports: [RouterModule.forRoot(routes, {scrollPositionRestoration: 'enabled'})], exports: [RouterModule] }) export class AppRoutingModule { }
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\ServiceManager\Di; use Zend\Di\Di; use Zend\ServiceManager\InitializerInterface; use Zend\ServiceManager\ServiceLocatorInterface; class DiServiceInitializer extends Di implements InitializerInterface { /** * @var Di */ protected $di = null; /** * @var DiInstanceManagerProxy */ protected $diInstanceManagerProxy = null; /** * @var ServiceLocatorInterface */ protected $serviceLocator = null; /** * Constructor * * @param \Zend\Di\Di $di * @param \Zend\ServiceManager\ServiceLocatorInterface $serviceLocator * @param null|DiInstanceManagerProxy $diImProxy */ public function __construct(Di $di, ServiceLocatorInterface $serviceLocator, DiInstanceManagerProxy $diImProxy = null) { $this->di = $di; $this->serviceLocator = $serviceLocator; $this->diInstanceManagerProxy = ($diImProxy) ?: new DiInstanceManagerProxy($di->instanceManager(), $serviceLocator); } /** * Initialize * * @param $instance * @param ServiceLocatorInterface $serviceLocator * @throws \Exception */ public function initialize($instance, ServiceLocatorInterface $serviceLocator) { $instanceManager = $this->di->instanceManager; $this->di->instanceManager = $this->diInstanceManagerProxy; try { $this->di->injectDependencies($instance); $this->di->instanceManager = $instanceManager; } catch (\Exception $e) { $this->di->instanceManager = $instanceManager; throw $e; } } }
<?php /** * MyAdmin * * Copyright (C) 2014-2018 Persian Icon Software * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @package MyAdmin CMS * @copyright Persian Icon Software * @link https://www.persianicon.com/myadmin */ defined('MA_PATH') OR exit('Restricted access'); /** * Converter Class * * @modified : 14 November 2017 * @created : 29 January 2015 * @since : version 0.4 * @author : Ali Bakhtiar (ali@persianicon.com) */ class ma_converter { public $digital_units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; /** * if int return like => 1024 * if string return like => 1024 KB * if array return (site, unit) */ public $digital_format = 'string'; // Number Format Decimals public $decimals = 2; /** * Digital Storage * * @param $input int, b,kb,mb,gb,pb... * @param $from string, b,kb,mb,gb,pb... * @param $to string, b,kb,mb,gb,pb... */ public function digital($size, $from = 'B', $to = NULL) { $size = str_replace([',', '.'], '', $size); // hatman bayad input be byte tabdil shavad, // agar $from NULL bud yani byte, agar na bayad convert shavad. $size = $this->to_bytes($size, $from); // agat $to bod yani hatman bayad be $to tabdil shavad, // dar gheyre insoorate auto hesab mishava. return $this->format_size_units( $size , $to ); } /** * Any To Bytes * * @param $input int * @param $unit string * @return int */ public function to_bytes($size, $unit) { $unit = array_search(strtoupper($unit), $this->digital_units); return ($size * pow(1024, $unit)); } /** * Digital Units * * @param int * @return string */ public function format_size_units($bytes, $unit = NULL) { if ($unit) { $unit = array_search(strtoupper($unit), $this->digital_units); } else { $unit = $bytes > 0 ? floor(log($bytes, 1024)) : 0; } $c = number_format($bytes / pow(1024, $unit), $this->decimals, '.', ','); if ($this->digital_format == 'string') { $c .= ' ' . $this->digital_units[$unit]; } else if ($this->digital_format == 'array') { $c = array($c, $this->digital_units[$unit]); } return $c; } /** * Weather! :D * * @param $temp int * @param $from string (c|celsius, f|fahrenheit) * @param $to string (c|celsius, f|fahrenheit) * @return int */ public function weather($temperatures, $from, $to) { // Celsius to Fahrenheit if (($from == 'c' || $from == 'celsius') && ($to == 'f' || $to == 'fahrenheit')) { $value = $temperatures * 9/5+32; } // Fahrenheit to Celsius else { $value = 5/9 * ($temperatures - 32); } return number_format($value, $this->decimals, '.', ','); } }
package kr.co.fastcampus.Eatgo.interfaces; import kr.co.fastcampus.Eatgo.domain.Restaurant; import kr.co.fastcampus.Eatgo.application.RestaurantService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.net.URI; import java.net.URISyntaxException; import java.util.List; @CrossOrigin//SPA 서버와 연동하기 위해서 사용되는 태그 @RestController public class RestaurantController { @Autowired public RestaurantService restaurantService; @GetMapping("/restaurants") public List<Restaurant> list(){ List<Restaurant> restaurants = restaurantService.getRestaurants(); return restaurants; } @GetMapping("/restaurant/{id}") public Restaurant detail(@PathVariable("id") Long id) { Restaurant restaurant = restaurantService.getRestaurant(id); // List<MenuItem> menuItems = menuItemRepository.findByRestaurantId(id); // restaurant.setMenuItem(menuItems); return restaurant; } @PostMapping("/restaurants") public ResponseEntity<?> create(@Valid @RequestBody Restaurant resource) throws URISyntaxException { //ResponseEntity는 http response를 핸들리 항기 위해 사용한다, String name = resource.getName(); String address = resource.getAddress(); Restaurant restaurant = new Restaurant(name, address); Restaurant created = restaurantService.addRestaurant(restaurant); URI location = new URI("/restaurants/1234"); return ResponseEntity.created(location).body("{}"); //response 코드를 201로 주기 위해서 created(location)을 사용함 .body는 바디안에 들어갈 내용 } @PatchMapping("/restaurants/{id}") public String update(@PathVariable Long id,@Valid @RequestBody Restaurant restaurant){ String name = restaurant.getName(); String address = restaurant.getAddress(); restaurantService.updateRestaurant(id, name, address); return "{}"; } }
from enum import Enum from sqlalchemy import Boolean, Column, Integer, String from sqlalchemy.sql import expression from sqlalchemy_utils.types.choice import ChoiceType from app.db import Base class UserRoleEnum(str, Enum): admin = "admin" editor = "editor" regular = "regular" class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True, index=True) role = Column(ChoiceType(UserRoleEnum), default=UserRoleEnum.regular, nullable=False) full_name = Column(String, index=True) email = Column(String, unique=True, index=True, nullable=False) hashed_password = Column(String, nullable=False) is_active = Column(Boolean(), default=False, server_default=expression.false())
import React, { useState, useEffect } from "react"; import "./root.css"; import "@fontsource/lilita-one"; import "./AccInfo.css"; import DialogBox from "./DialogBox"; // Update the path based on your folder structure function AccInfo() { const [loggedInUser, setLoggedInUser] = useState(null); const [updatedUser, setUpdatedUser] = useState({ firstname: "", lastname: "", currentPassword: "", newPassword: "", confirmPassword: "", }); const [showConfirmationDialog, setShowConfirmationDialog] = useState(false); const [showSuccessDialog, setShowSuccessDialog] = useState(false); useEffect(() => { const userID = localStorage.getItem("userID"); if (userID) { fetch(`http://localhost:8080/watataps/users/getUserById/${userID}`) .then((response) => response.json()) .then((userData) => { setLoggedInUser(userData); setUpdatedUser({ firstname: userData.user.firstname, lastname: userData.user.lastname, currentPassword: "", newPassword: "", confirmPassword: "", }); }); } }, []); const handleInputChange = (event) => { const { name, value } = event.target; setUpdatedUser((prevUser) => ({ ...prevUser, [name]: value, })); }; const handleUpdateUserInfo = () => { setShowConfirmationDialog(true); }; const confirmUpdate = async () => { const userID = localStorage.getItem("userID"); try { const response = await fetch( `http://localhost:8080/watataps/users/updateUser/${userID}`, { method: "PUT", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ firstname: updatedUser.firstname, lastname: updatedUser.lastname, }), } ); if (response.ok) { console.log("User information updated successfully"); // Fetch and update displayed user information fetch(`http://localhost:8080/watataps/users/getUserById/${userID}`) .then((response) => response.json()) .then((userData) => setLoggedInUser(userData)); setShowSuccessDialog(true); } else { console.error("Failed to update user information"); } } catch (error) { console.error("Error updating user information:", error); } finally { setShowConfirmationDialog(false); } }; const handleUpdatePassword = async () => { const userID = localStorage.getItem("userID"); try { const response = await fetch( `http://localhost:8080/watataps/users/getUserById/${userID}`, { method: "PUT", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ password: updatedUser.newPassword, }), } ); if (response.ok) { console.log("Password updated successfully"); setShowSuccessDialog(true); } else { console.error("Failed to update password"); } } catch (error) { console.error("Error updating password:", error); } }; return ( <> {loggedInUser ? ( <div className="account"> <div className="acc-info"> <h2 className="acc-info-title">ACCOUNT INFORMATION</h2> <input className="inputs-information-acc inputs-acc" type="text" placeholder="Username" value={loggedInUser.user.username} disabled ></input> <input className="inputs-information-acc inputs-acc" type="text" placeholder="Firstname" name="firstname" value={updatedUser.firstname} onChange={handleInputChange} ></input> <input className="inputs-information-acc inputs-acc" type="text" placeholder="Lastname" name="lastname" value={updatedUser.lastname} onChange={handleInputChange} ></input> <button className="btn-save save-acc" onClick={handleUpdateUserInfo} > Save Changes </button> </div> <div className="pass"> <h2 className="acc-info-title">CHANGE PASSWORD</h2> <input className="inputs-information-acc inputs-pass" type="password" placeholder="Current Password" name="currentPassword" value={updatedUser.currentPassword} onChange={handleInputChange} ></input> <input className="inputs-information-acc inputs-pass" type="password" placeholder="New Password" name="newPassword" value={updatedUser.newPassword} onChange={handleInputChange} ></input> <input className="inputs-information-acc inputs-pass" type="password" placeholder="Confirm New Password" name="confirmPassword" value={updatedUser.confirmPassword} onChange={handleInputChange} ></input> <button className="btn-save save-pass" onClick={handleUpdatePassword} > Save Changes </button> </div> </div> ) : ( <p>Please log in to view account information.</p> )} {showConfirmationDialog && ( <DialogBox title="Confirm Update" message="Are you sure you want to update your information?" imageSrc={"./images/dialog-edit.gif"} onClose={() => setShowConfirmationDialog(false)} onConfirm={confirmUpdate} onCancel={() => setShowConfirmationDialog(false)} confirmText="Yes" cancelText="No" buttons={[ { label: "Yes", className: "btn-confirm", onClick: confirmUpdate, }, { label: "No", className: "btn-cancel", onClick: () => setShowConfirmationDialog(false), }, ]} /> )} {showSuccessDialog && ( <DialogBox title="Update Successful" message="Your information has been updated successfully." imageSrc={"./images/dialog-check.gif"} onClose={() => setShowSuccessDialog(false)} confirmText="OK" buttons={[ { label: "OK", className: "btn-confirm", onClick: () => setShowSuccessDialog(false), }, ]} /> )} </> ); } export default AccInfo;
nome = "Rafael" idade = 35 lingua = "Python" pessoa = {"nome":"rafael", "idade":35, "lingua":"Python"} # Old Style com % (não é mais utilizado em Python 3, lembra um pouco como é em C) print("Meu nome é %s, tenho %d anos e estudo %s"%(nome, idade, lingua)) #format - evolução do old style print("Meu nome é {}, tenho {} anos e estudo {}.".format(nome, idade, lingua)) #preenche as variáveis na sequência da indexação passada no parâmetro, fica como no print abaixo: print("Meu nome é {0}, tenho {1} anos e estudo {2}.".format(nome, idade, lingua)) #para ordenor a posição das variáveis: print("Tenho {1} anos, meu nome é {0} e estudo {2}.".format(nome, idade, lingua)) #nessa formatação é possível reutilizar as variáveis em posições diferentes print("Meu nome é {nome}, tenho {idade} anos e estudo {lingua}.".format(nome=nome, idade=idade, lingua=lingua)) #aqui é possível trabalhar melhor de forma visual com as variáveis, mas nota-se que ao código fica mais extenso print("Meu nome é {nome}, tenho {idade} anos e estudo {lingua}.".format(**pessoa)) #Usando um dicionário # F STRING print(f"Meu nome é {nome}, tenho {idade} anos e estudo {lingua}.") #melhor forma visual e flexibildiade ## Uma desvantagem (não tão problemática) é ter que passar a variável novamente durante o texto quando se quer exibir o conteúdo mais de uma vez, o que na verdade melhora a visibilidade ## Formatação de casas decimais: pi = 3.14159 print(f"pi é {pi:.2f}") ###Formatação de casas de unidade print(f"pi é: {pi:10.2f}") # poe 11 unidades a frente da variável
"use client"; import Image, { StaticImageData } from "next/image"; import { Swiper, SwiperSlide } from "swiper/react"; import { useSwiper } from "swiper/react"; import { Navigation, Pagination, Autoplay } from "swiper/modules"; import "swiper/css/autoplay"; import "swiper/css"; import "swiper/css/navigation"; import "swiper/css/pagination"; import "swiper/css/bundle"; interface Props { images: (string | StaticImageData)[]; } const NextButton = () => { const swiper = useSwiper(); return ( <button onClick={() => swiper.slideNext()} className="next-button absolute top-1/2 right-4 z-10 bg-background/80 rounded-full p-2 shadow-md hover:bg-background/90 cursor-pointer transition-all duration-300 ease-in-out" > <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6 stroke-main-lighter" fill="none" viewBox="0 0 24 24" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" /> </svg> </button> ); }; const PrevButton = () => { const swiper = useSwiper(); return ( <button onClick={() => swiper.slidePrev()} className="absolute top-1/2 left-4 z-10 bg-background/70 rounded-full p-2 shadow-md prev-button hover:bg-background/90 cursor-pointer transition-all duration-300 ease-in-out" > <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6 stroke-main-lighter" fill="none" viewBox="0 0 24 24" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" /> </svg> </button> ); }; export default function ImageSlider({ images }: Props) { return ( <Swiper modules={[Navigation, Pagination, Autoplay]} spaceBetween={0} slidesPerView={1} navigation={{ nextEl: ".next-button", prevEl: ".prev-button", }} scrollbar={{ draggable: true }} className="flex flex-col items-center justify-center w-full" autoplay={{ delay: 2000, disableOnInteraction: false }} loop={true} pagination={{ clickable: true, }} > <NextButton /> <PrevButton /> {images?.map((curr, indx) => ( <SwiperSlide key={indx}> <Image src={curr} alt="Project Image" width={1000} height={1000} className="aspect-video w-full object-cover mt-6" /> </SwiperSlide> ))} </Swiper> ); }
import { CallHandler, ExecutionContext, HttpException, HttpStatus, Injectable, Logger, NestInterceptor, } from '@nestjs/common'; import { Observable, of, TimeoutError } from 'rxjs'; import { catchError, map, tap, timeout } from 'rxjs/operators'; import { RedisLockService } from '@exchanges/redis'; import { RPC_PAYLOAD, RPC_RESPONSE, rpcErrorMessage } from '@exchanges/common'; @Injectable() export class BalancerInterceptor implements NestInterceptor { private readonly timeoutLimit = 60000; // 1 minutes constructor(private readonly lock: RedisLockService) {} async intercept( context: ExecutionContext, next: CallHandler, ): Promise<Observable<RPC_RESPONSE<any> | null>> { const start = Date.now(); const data = context.switchToRpc().getData() as RPC_PAYLOAD<any>; const ctx = context.switchToRpc().getContext(); // Logger.info('context', ctx.args?.[0], context.getArgs()); const method = ctx.args?.[0] || 'Unknown.Method'; if (!data?.lockId?.length) { Logger.error(`No lock ID provided for ${method}`); throw new HttpException('No lockId provided', HttpStatus.BAD_REQUEST); } // try to lock resource let instanceFlag = false; let lock: any; try { lock = await this.lock.tryLockResource(data.lockId, 0, data.lockTtl); // tryLockResource can return NULL if (!lock) { const error = `Failed to lock resource ${data.lockId}`; const message = `RPC ERROR: ${ data.lockId } of ${method} with ${JSON.stringify(data)}, error: ${error}`; // Logger.error(error, message, 'BalancerInterceptor'); return of({ statusCode: HttpStatus.INTERNAL_SERVER_ERROR, error, message, }); } instanceFlag = true; } catch (err: any) { Logger.error( `Failed to lock resource ${data.lockId}: ${err.message}`, 'BalancerInterceptor', ); return of({ statusCode: HttpStatus.INTERNAL_SERVER_ERROR, error: err.message, }); } // wait for lock to be released if (!instanceFlag) { while (!lock && Date.now() - start < this.timeoutLimit) { await new Promise((resolve) => setTimeout(resolve, 50)); lock = await this.lock.tryLockResource(data.lockId, 0, data.lockTtl); } if (lock) { await this.lock.releaseLock(lock); } const duration = Date.now() - start; const message = `${data.callId} of ${method} waited for ${duration}ms`; if (duration > this.timeoutLimit) { throw new HttpException(message, HttpStatus.TEMPORARY_REDIRECT); } return of({ statusCode: HttpStatus.TEMPORARY_REDIRECT, error: message, duration, }); } return next.handle().pipe( timeout(this.timeoutLimit), catchError((err: Error) => { const error = rpcErrorMessage(err); const message = `RPC ERROR: ${ data.callId } of ${method} with ${JSON.stringify(data)} with ${error}`; Logger.error(message, 'BalancerInterceptor'); if (err instanceof TimeoutError) { return of({ statusCode: HttpStatus.REQUEST_TIMEOUT, message, error, }); } return of({ statusCode: HttpStatus.INTERNAL_SERVER_ERROR, error, message, }); }), map((value) => { return value === undefined ? null : ({ ...value, duration: Date.now() - start } as RPC_RESPONSE<any>); }), tap(async () => { // release other instances after successful processing setTimeout(async () => { if (lock) { await this.lock.releaseLock(lock); } }, 100); }), ); } }
package _2_bag_problem; import org.junit.Test; /** * ClassName: bag_problem.CoinChangeII518 * Package: PACKAGE_NAME * Description: * * @Author CBX * @Create 2024/3/31 16:59 * @Version 1.0 */ /* * You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0. You may assume that you have an infinite number of each kind of coin. The answer is guaranteed to fit into a signed 32-bit integer. Example 1: Input: amount = 5, coins = [1,2,5] Output: 4 Explanation: there are four ways to make up the amount: 5=5 5=2+2+1 5=2+1+1+1 5=1+1+1+1+1 * */ public class _19_518_CoinChangeII { @Test public void test1() { System.out.println(change(5, new int[]{1, 2, 5})); } @Test public void test2(){ System.out.println(changePermutation(4, new int[]{1, 2, 3})); } public int changePermutation(int amount, int[] coins) { //494. TargetSum 和这个类似, 只不过这个的物品不限量 //老规矩, dp五部曲 //1. dp数组的含义 //dp[j]: 背包容量为j时, 装满背包的不同的方法数 int[] dp = new int[amount + 1]; //3.初始化 //dp[0] = 1 dp[0] = 1; //2. 递推公式 //在494.TargetSum中, 用到了dp[j] += dp[j - num[i]] //这里也可以用 //4.遍历顺序 //求排列数时要外层顺序遍历背包容量, 内层顺序遍历物品 for (int j = 1; j <= amount; j++) { for (int i = 0; i < coins.length; i++) { if (j >= coins[i]) { dp[j] += dp[j - coins[i]]; } } } return dp[amount]; } public int change(int amount, int[] coins) { //494. TargetSum 和这个类似, 只不过这个的物品不限量 //老规矩, dp五部曲 //1. dp数组的含义 //dp[j]: 背包容量为j时, 装满背包的不同的方法数 int[] dp = new int[amount + 1]; //3.初始化 //dp[0] = 1 dp[0] = 1; //2. 递推公式 //在494.TargetSum中, 用到了dp[j] += dp[j - num[i]] //这里也可以用 //4.遍历顺序 //一维数组解决完全背包的通用遍历顺序 for (int i = 0; i < coins.length; i++) { for (int j = coins[i]; j <= amount; j++) { dp[j] += dp[j - coins[i]]; } } return dp[amount]; } }
import pandas as pd #read a csv file ufo = pd.read_csv('http://bit.ly/uforeports') print("Overview of UFO data reports: ") print(ufo.head()) print() #series print("Cityseries(sorted):") print(ufo.City.sort_values()) print() ufo['Location'] = ufo.City + ', ' + ufo.State print("After creating a new 'Location' Series : ") print(ufo.head()) print() print("Calculate summary statistics : ") print(ufo.describe()) print() print("Column names of ufo dataframe : ",ufo.columns) print() # rename two of the columns by using the 'rename' method ufo.rename(columns={'Colors Reported':'Colors_Reported', 'Shape Reported':'Shape_Reported'},inplace=True) print("Column name of ufo dataframe after renaming two column names : ",ufo.columns) print() # remove multiple columns at once ufo.drop(['City', 'State'], axis=1, inplace=True) print("Column name of ufo dataframe after removing two columns(city,state) : ",ufo.columns) print() # remove multiple rows at once (axis=0 refers to rows) ufo.drop([0, 1], axis=0, inplace=True) print("ufo dataframe after deleting first two rows: ") print(ufo.head()) OUTPUT Overview of UFO data reports: City Colors Reported Shape Reported State Time 0 Ithaca NaN TRIANGLE NY 6/1/1930 22:00 1 Willingboro NaN OTHER NJ 6/30/1930 20:00 2 Holyoke NaN OVAL CO 2/15/1931 14:00 3 Abilene NaN DISK KS 6/1/1931 13:00 4 New York Worlds Fair NaN LIGHT NY 4/18/1933 19:00 Cityseries(sorted): 1761 Abbeville 17809 Aberdeen 2297 Aberdeen 9404 Aberdeen 389 Aberdeen ... 12441 NaN 15767 NaN 15812 NaN 16054 NaN 16608 NaN Name: City, Length: 18241, dtype: object After creating a new 'Location' Series : City Colors Reported Shape Reported State Time \ 0 Ithaca NaN TRIANGLE NY 6/1/1930 22:00 1 Willingboro NaN OTHER NJ 6/30/1930 20:00 2 Holyoke NaN OVAL CO 2/15/1931 14:00 3 Abilene NaN DISK KS 6/1/1931 13:00 4 New York Worlds Fair NaN LIGHT NY 4/18/1933 19:00 Location 0 Ithaca, NY 1 Willingboro, NJ 2 Holyoke, CO 3 Abilene, KS 4 New York Worlds Fair, NY Calculate summary statistics : City Colors Reported Shape Reported State Time \ count 18215 2882 15597 18241 18241 unique 6475 27 27 52 16145 top Seattle RED LIGHT CA 11/16/1999 19:00 freq 187 780 2803 2529 27 Location count 18215 unique 8028 top Seattle, WA freq 187 Column names of ufo dataframe : Index(['City', 'Colors Reported', 'Shape Reported', 'State', 'Time', 'Location'], dtype='object') Column name of ufo dataframe after renaming two column names : Index(['City', 'Colors Reported', 'Shape Reported', 'State', 'Time', 'Location'], dtype='object') Column name of ufo dataframe after removing two columns(city,state) : Index(['City', 'Colors Reported', 'Shape Reported', 'State', 'Time', 'Location'], dtype='object') ufo dataframe after deleting first two rows: City Colors Reported Shape Reported State Time \ 2 Holyoke NaN OVAL CO 2/15/1931 14:00 3 Abilene NaN DISK KS 6/1/1931 13:00 4 New York Worlds Fair NaN LIGHT NY 4/18/1933 19:00 5 Valley City NaN DISK ND 9/15/1934 15:30 6 Crater Lake NaN CIRCLE CA 6/15/1935 0:00 Location 2 Holyoke, CO 3 Abilene, KS 4 New York Worlds Fair, NY 5 Valley City, ND 6 Crater Lake, CA
import { FungibleTokenDetailed, isNativeTokenAddress, useBlockNumber, useTokenConstants, } from '@masknet/web3-shared-evm' import { useAsyncRetry } from 'react-use' import { BALANCER_SWAP_TYPE } from '../../constants' import { PluginTraderRPC } from '../../messages' import { SwapResponse, TradeStrategy } from '../../types' import { TargetChainIdContext } from '../useTargetChainIdContext' export function useTrade( strategy: TradeStrategy, inputAmount: string, outputAmount: string, inputToken?: FungibleTokenDetailed, outputToken?: FungibleTokenDetailed, ) { const blockNumber = useBlockNumber() const { targetChainId } = TargetChainIdContext.useContainer() const { WNATIVE_ADDRESS } = useTokenConstants(targetChainId) return useAsyncRetry(async () => { if (!WNATIVE_ADDRESS) return null if (!inputToken || !outputToken) return null const isExactIn = strategy === TradeStrategy.ExactIn if (inputAmount === '0' && isExactIn) return null if (outputAmount === '0' && !isExactIn) return null // the WETH address is used for looking for available pools const sellToken = isNativeTokenAddress(inputToken) ? WNATIVE_ADDRESS : inputToken.address const buyToken = isNativeTokenAddress(outputToken) ? WNATIVE_ADDRESS : outputToken.address const { swaps, routes } = await PluginTraderRPC.getSwaps( sellToken, buyToken, isExactIn ? BALANCER_SWAP_TYPE.EXACT_IN : BALANCER_SWAP_TYPE.EXACT_OUT, isExactIn ? inputAmount : outputAmount, targetChainId, ) // no pool found if (!swaps[0].length) return null return { swaps, routes } as SwapResponse }, [ WNATIVE_ADDRESS, strategy, targetChainId, inputAmount, outputAmount, inputToken?.address, outputToken?.address, blockNumber, // refresh api each block ]) }
import Topbar from "./components/topbar/Topbar"; import Home from "./pages/home/Home"; import SinglePostPage from "./pages/singlePostPage/SinglePostPage"; import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; import Write from "./pages/write/Write"; import Settings from "./pages/settings/Settings"; import Login from "./pages/login/Login"; import Register from "./pages/register/Register"; import { useContext } from "react"; import { Context } from "./context/Context"; function App() { const { user } = useContext(Context); return ( <> {/* in latest react router dom we have switches as Routes and Route will be auto closing tag like <Route element={component}/> nandan1234*/} <Router> <Topbar /> <Switch> <Route exact path="/"> <Home /> </Route> <Route exact path="/register"> {user ? <Home /> : <Register />} </Route> <Route exact path="/login"> {user ? <Home /> : <Login />} </Route> <Route exact path="/write"> {user ? <Write /> : <Register />} </Route> <Route exact path="/settings"> {user ? <Settings /> : <Register />} </Route> <Route path="/post/:id"> <SinglePostPage /> </Route> </Switch> </Router> </> ); } export default App;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Vote | System</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"> <style> @import url('https://fonts.googleapis.com/css2?family=Kanit&display=swap'); *{ font-family: 'Kanit', sans-serif; } .nav li:hover:after { width: 100%; } .nav li::after { content: ''; width: 0%; height: 2px; background: #00f; /* สีฟ้า */ display: block; margin: auto; transition: width 0.5s; } .nav li:hover:after { width: 100%; } .nav li::after { content: ''; width: 0%; height: 2px; background: #00f; /* สีฟ้า */ display: block; margin: auto; transition: width 0.5s; } </style> </head> <body> @include('layouts.header') <!-- Begin page content --> <div class="container"> <div class="main-content mt-5"> <div class="card"> <div class="card-header"> <div class="row"> <div class="col-md-6"> <h4>All Parties</h4> </div> <div class="col-md-6 d-flex justify-content-end"> <a href="{{url('/parties-create')}}" class="btn btn-success mx-1">Create</a> <a href="{{route('parties.trashed')}}" class="btn btn-warning"><i class="fa fa-trash"></i></a> </div> </div> </div> <div class="card-body"> <table class="table table-striped table-bordered border-dark"> <thead style="background: #f2f2f2"> <tr> <th scope="col">#</th> <th scope="col" style="width: 10%">Image</th> <th scope="col" style="width: 10%">Number</th> <th scope="col" style="width: 20%">Name</th> <th scope="col" style="width: 20%">Leader</th> <th scope="col" style="width: 20%">Slogan</th> <th scope="col" style="width: 10%">Voter</th> <th scope="col" style="width: 10%">Publish Date</th> <th scope="col" style="width: 20%">Action</th> </tr> </thead> <tbody> @foreach ($parties as $party) <tr> <th scope="row">{{$party->id}}</th> <td> <img src="{{asset($party->image)}}" alt="" width="80"> </td> <td>{{$party->number}}</td> <td>{{$party->name}}</td> <td>{{$party->leader}}</td> <td>{{$party->slogan}}</td> <td>{{$party->voter}}</td> <td>{{date('d-m-Y', strtotime($party->created_at))}}</td> <td> <div class="d-flex"> <a href="{{route('parties.show', $party->id)}}" class="btn btn-success mx-1">Show</a> <a href="{{route('parties.edit', $party->id)}}" class="btn btn-primary mx-1">Edit</a> {{-- <a href="" class="btn btn-danger">Delete</a> --}} <form action="{{route('parties.destroy', $party->id)}}" method="POST"> @csrf @method('DELETE') <button class="btn btn-danger" type="submit">Delete</button> </form> </div> </td> </tr> @endforeach </tbody> </table> {{$parties->links()}} </div> </div> </div> </div> {{-- @include('layouts.footer') --}} <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js"></script> </body> </html>
<template> <div class="form_body"> <el-form :model="preForm1" size="mini" label-width="90px" :disabled="preFormDisabled"> <el-form-item label="患者姓名:"> <span>{{this.$store.state.inquiry.patientName}}</span> </el-form-item> <el-form-item label-position="top" label="初步诊断:">{{$store.state.inquiry.diseaseDecided}}</el-form-item> </el-form> <el-form label-position="top" :model="preForm2" size="mini" label-width="90px" :disabled="preFormDisabled"> <el-form-item label="处理意见:"> <el-row> <el-col :span="8"> <el-select v-model="preForm2.name" filterable placeholder="请选择"> <el-option v-for="item in drugs" class="input1" :key="item.label" :label="item.label" :value="item.label"> </el-option> </el-select> </el-col> <el-col :span="4"> <!-- <el-input-number v-model="preForm2.num" :min="1" :max="10" size="mini"></el-input-number>--> <el-input size="mini" class="input2" placeholder="如:1" v-model="preForm2.num"> </el-input> </el-col> <el-col :span="8"> <el-input size="mini" class="input1" placeholder="如:每日三次" v-model="preForm2.method"> </el-input> </el-col> <el-button @click="addMedicine">添加</el-button> </el-row> <el-table :data="preForm2.data"> <el-table-column fixed prop="name" width="90px" label="药品"> <!-- <template slot-scope="scope">--> <!-- <el-input type="text" v-model="editName" v-if="editIndex === scope.$index" />--> <!-- <span v-else>{{ scope.row.name }}</span>--> <!-- </template>--> </el-table-column> <el-table-column fixed prop="num" width="70px" label="数量/盒"> <!-- <template slot-scope="scope">--> <!-- <el-input-number--> <!-- v-model="editNum"--> <!-- controls-position="right"--> <!-- :min="1" :max="10"--> <!-- size="small"--> <!-- v-if="editIndex === scope.$index"></el-input-number>--> <!-- <span v-else>{{ scope.row.num }}</span>--> <!-- </template>--> <template slot-scope="scope"> <el-input type="text" v-model="editNum" v-if="editIndex === scope.$index" /> <span v-else>{{ scope.row.num }}</span> </template> </el-table-column> <el-table-column fixed prop="method" width="95px" label="用法"> <template slot-scope="scope"> <el-input type="text" v-model="editMethod" v-if="editIndex === scope.$index" /> <span v-else>{{ scope.row.method }}</span> </template> </el-table-column> <el-table-column fixed prop="action" width="153px" label="操作"> <template slot-scope="scope"> <div v-if="editIndex === scope.$index"> <el-button @click="handleSave(scope.$index)">保存</el-button> <el-button @click="editIndex = -1">取消</el-button> </div> <div v-else> <el-button @click="handleEdit(scope.row, scope.$index)">编辑</el-button> <el-button type="error" @click="remove(scope.$index)">删除</el-button> </div> </template> </el-table-column> </el-table> </el-form-item> <el-form-item> <div class="button"> <el-button size="medium" type="primary" @click="onSubmit">生成</el-button> <el-button size="medium" @click="clearAll">清空</el-button> </div> </el-form-item> </el-form> </div> </template> <script> import {postMedicineIncludedDataFun,getDrugListDataFun} from "@/service/userService"; export default { name: "prescription_form", data() { return { drugs:[], preForm1: {},//处方表 preForm2: {//处方表 name:'',//药品名输入绑定 num:'',//数量输入绑定 method:'',//用法输入绑定 data:[],//药品表信息 }, editIndex:-1,//表格编辑索引 editName:'',//编辑药名绑定 editNum:'',//编辑数量绑定 editMethod:'',//编辑用法绑定 submit:{//提交药品 name:'', num:'', method:'' }, preFormDisabled:false,//处方表禁用设置 } }, created() { this.getDrugs(); }, methods: { getDrugs(){ getDrugListDataFun( ).then(res=>{ for(let i=0;i<res.result.length;i++){ this.drugs.push({ "label":res.result[i].medicine_Name, }) } // console.log(this.drugs); }).catch(err=>{ console.log(err); }) }, postMedicineIncluded() {//上传处方表 postMedicineIncludedDataFun({ m_name:this.submit.name, p_id:this.$store.state.inquiry.preId, quantity:this.submit.num, content:this.submit.method }).then(res => { // console.log(res); }).catch(err => { // console.log(err); }) }, onSubmit() {//提交 let temp=this.preForm2; if(temp.data.length==0){ this.$message({ message: '请完整填写处方信息再提交', type: 'warning' }); }else{ for(let i=0;i<this.preForm2.data.length;i++){ this.submit.name=this.preForm2.data[i].name; this.submit.num=this.preForm2.data[i].num; this.submit.method=this.preForm2.data[i].method; // console.log(this.submit); this.postMedicineIncluded(); } this.preFormDisabled=true; // console.log('submit!'); } }, handleSelect(item){ console.log(item); }, addMedicine(){//添加药品到药品表 let _this=this; if(_this.preForm2.name!=''&&_this.preForm2.num!=''&&_this.preForm2.method!=''){ _this.preForm2.data.push({ name:_this.preForm2.name, num:_this.preForm2.num, method:_this.preForm2.method }) _this.preForm2.name=''; _this.preForm2.num=''; _this.preForm2.method=''; } }, handleEdit(row,index){//编辑药品表 // this.editName=row.name; this.editNum=row.num; this.editMethod=row.method; this.editIndex=index; }, handleSave(index){//保存编辑 // this.preForm2.data[index].name=this.editName; this.preForm2.data[index].num=this.editNum; this.preForm2.data[index].method=this.editMethod; this.editIndex=-1; }, remove(index){//删除一条药品表信息 this.preForm2.data.splice(index,1); }, clearAll(){//清空处方表 this.preForm2.data=[]; this.preForm2.num=''; this.preForm2.name=''; this.preForm2.method=''; } }, } </script> <style scoped> .input1{ width: 132px; padding-right: 5px } .input2{ width: 65px; padding-right: 2px; padding-left: 2px; } /*.form_body{*/ /* width: 99%;*/ /* height: 100%;*/ /* border: 0;*/ /* left:20px;*/ /* font-family: "微软雅黑";*/ /* overflow: auto;*/ /*}*/ /*/deep/.el-form-item{*/ /* font-size: 10px;*/ /* margin-bottom: 1px;*/ /*}*/ /*/deep/.el-form-item--mini.el-form-item{*/ /* margin-bottom: 6px;*/ /*}*/ /deep/.el-form--label-top .el-form-item__label{ padding-left: 10px; } .button{ position: relative; width: 50%; left: 33%; } </style>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="style.css"> <title>Find the precious</title> </head> <body> <nav class="navbar navbar-expand-sm navbar-dark"> <a class="navbar-brand" href="#"><img src="images/logo.png" class="logo" alt=""></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="#">Fellows</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Contact</a> </li> </ul> </div> </nav> <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img src="images/dark_vador.jpg" class="d-block w-100" alt=""> </div> <div class="carousel-item"> <img src="images/dark_vador.jpg" class="d-block w-100" alt=""> </div> <div class="carousel-item"> <img src="images/dark_vador.jpg" class="d-block w-100" alt=""> </div> <div class="carousel-text"> <p>Sauron is a very good bro,</p> <p>Please help him to find his ring ! -D.V.</p> </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div> <section class="wanted"> <h2 class="fellows"><span class="deco">ij</span><strong>Fellows wanted dead </strong><span></span>(or alive if you want to eat them later) <span class="deco">ij</span></h2> <div class="card-deck"> <div class="card position-relative"> <img src="images/gandalf.png" class="card-img-top not-dead" alt="Gandalf"> <span class="badge position-absolute"><span>Reward</span><span class="orange">100</span> golden coins</span> <h5 class="card-title">Gandalf</h5> <div class="card-body"> <p class="card-text">A very dangerous wizard, Ballrog killer...</p> </div> </div> <div class="card position-relative"> <img src="images/aragorn.png" class="card-img-top not-dead" alt="Aragorn"> <span class="badge position-absolute">Reward <span class="orange">800</span> golden coins</span> <h5 class="card-title">Aragorn</h5> <div class="card-body"> <p class="card-text">Sauron's finger says him his sword is dangerous...</p> </div> </div> <div class="card"> <img src="images/gimli.png" class="card-img-top dead" alt="Gimli"> <h5 class="card-dead">dead</h5> <h5 class="card-title">gimli</h5> <img src="images/minus.png" class="card-crossed" alt="orange-line"> <div class="card-body"> <p class="card-text">A dwarf with a beard and an axe...</p> </div> </div> </div> </section> <hr> <section class="contact-us"> <h2 class="contact-us-title"><span class="deco">ij</span>Contact us<span class="deco">ij</span></h2> <div class="container-contact-us"> <form> <div class="form-group"> <input type="text" class="form-control" id="formGroupExampleInput" placeholder="@"> </div> <div class="form-group"> <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Address"> </div> <div class="form-group"> <select class="form-control" id="exampleFormControlSelect1"> <option>I have seen one of them</option> <option>Reward</option> <option>Join our army</option> <option>Question</option> </select> </div> <div class="form-group text-area"> <textarea class="form-control" id="exampleFormControlTextarea1" rows="3">Your messageto the Master</textarea> </div> </form> <div class="map"> <img src="images/map.jpg" class="card-img-top" alt="map"> </div> </div> </section> <footer> <div class="container-fluid"> <div class="row"> <div class="col-3 text-light"> <ul> <li>About us</li> <li>Fellows</li> <li>Join our army</li> </ul> </div> <div class="col-4 text-light"> <ul> <li>FAQ</li> <li>Reward conditions</li> <li>Legal mentions</li> </ul> </div> <div class="col text-light"> <ul> <li>Sauron4Ever.com</li> <li>Follow him also on twitter</li> </ul> </div> </div> </div> </footer> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </body> </html>
--- title: 'Setup user specific mail quotas with LDAP' date: 2016-08-13 description: Setting mail quotes with OpenLDAP. tags: - Mail - LDAP - Quota --- # Intro The official [Dovecot wiki](http://wiki2.dovecot.org/Quota) should be your go to for setting up mail quotas, but here I am describing how I setup mail-user specific quotas to work with my LDAP environment. ### Setup I included a quota configuration for `user_attrs` in my `dovecot-ldap.conf.ext` consisting of the following ``` user_attrs = mailHomeDirectory=home,mailStorageDirectory=mail,mailUidNumber=uid,mailGidNumber=gid,mailQuota=quota_rule=*:bytes=%$ ``` The quota limit is in the **mailQuota** field: `mailQuota=quota_rule=*:bytes=%$` Once Dovecot has been restarted with the above quota limit, we can then add the `mailQuota` attribute with a value using a preferred metric unit. For example, a mail user record might have a quota limit of 250 MB. `mailQuota: 250MB` The above quota is user-specific so this will end up overriding the [global quota](http://wiki2.dovecot.org/Quota/Configuration). ### Verify Quota I use a lot of aliases to save time, so putting this in your user profile is recommended. `alias quota='doveadm quota get -u $1 '` ``` $ quota johndoe Quota name Type Value Limit % User quota STORAGE 0 256000 0 User quota MESSAGE 0 - 0 ``` See the [doveadm-quota wiki](http://wiki2.dovecot.org/Tools/Doveadm/Quota) for additional options.
package api import ( "database/sql" "errors" "github.com/gin-gonic/gin" "github.com/lib/pq" db "github.com/okoroemeka/simple_bank/db/sqlc" "github.com/okoroemeka/simple_bank/token" "net/http" ) type createAccountRequest struct { Currency string `json:"currency" binding:"required,currency"` } func (server *Server) createAccount(ctx *gin.Context) { var req createAccountRequest if err := ctx.ShouldBindJSON(&req); err != nil { ctx.JSON(http.StatusBadRequest, errorResponse(err)) return } authPayload := ctx.MustGet(authorizationPayloadKey).(*token.Payload) arg := db.CreateAccountParams{ Owner: authPayload.Username, Currency: req.Currency, Balance: 0, } account, err := server.store.CreateAccount(ctx, arg) if err != nil { if pqErr, ok := err.(*pq.Error); ok { switch pqErr.Code.Name() { case "foreign_key_violation", "unique_violation": ctx.JSON(http.StatusForbidden, errorResponse(err)) return } } ctx.JSON(http.StatusInternalServerError, errorResponse(err)) return } ctx.JSON(http.StatusCreated, account) } type getAccountRequest struct { ID int64 `uri:"id" binding:"required,min=1"` } func (server *Server) getAccount(ctx *gin.Context) { var req getAccountRequest if err := ctx.ShouldBindUri(&req); err != nil { ctx.JSON(http.StatusBadRequest, errorResponse(err)) return } account, err := server.store.GetAccount(ctx, req.ID) if err != nil { if err == sql.ErrNoRows { ctx.JSON(http.StatusNotFound, errorResponse(err)) return } ctx.JSON(http.StatusInternalServerError, errorResponse(err)) return } authPayload := ctx.MustGet(authorizationPayloadKey).(*token.Payload) if authPayload.Username != account.Owner { err = errors.New("account doesn't belong to the authenticated user") ctx.JSON(http.StatusUnauthorized, errorResponse(err)) return } ctx.JSON(http.StatusOK, account) } type listAccountRequest struct { Offset int32 `form:"offset" binding:"required,min=0"` Limit int32 `form:"limit" binding:"required,min=5,max=10"` } func (server *Server) listAccounts(ctx *gin.Context) { var req listAccountRequest if err := ctx.ShouldBind(&req); err != nil { ctx.JSON(http.StatusBadRequest, errorResponse(err)) return } authPayload := ctx.MustGet(authorizationPayloadKey).(*token.Payload) accounts, err := server.store.ListAccounts(ctx, db.ListAccountsParams{ Owner: authPayload.Username, Offset: req.Offset, Limit: req.Limit, }) if err != nil { if err == sql.ErrNoRows { ctx.JSON(http.StatusNotFound, errorResponse(err)) return } ctx.JSON(http.StatusInternalServerError, errorResponse(err)) return } ctx.JSON(http.StatusOK, accounts) return } // TODO: add delete and update account type accountIDQueryRequest struct { ID int64 `uri:"id" binding:"required,min=1"` } type updateAccountBodyRequest struct { Amount int64 `form:"amount" binding:"required,min=1"` } func (server *Server) updateAccount(ctx *gin.Context) { var reqQuery accountIDQueryRequest var reqBody updateAccountBodyRequest if err := ctx.ShouldBindUri(&reqQuery); err != nil { ctx.JSON(http.StatusBadRequest, errorResponse(err)) return } if err := ctx.ShouldBindJSON(&reqBody); err != nil { ctx.JSON(http.StatusBadRequest, errorResponse(err)) return } account, err := server.store.UpdateAccount(ctx, db.UpdateAccountParams{ Balance: reqBody.Amount, ID: reqQuery.ID, }) if err != nil { if err == sql.ErrNoRows { ctx.JSON(http.StatusNotFound, err) return } ctx.JSON(http.StatusInternalServerError, errorResponse(err)) } ctx.JSON(http.StatusOK, account) } func (server *Server) deleteAccount(ctx *gin.Context) { var reqQuery accountIDQueryRequest if err := ctx.ShouldBindUri(&reqQuery); err != nil { ctx.JSON(http.StatusBadRequest, errorResponse(err)) return } err := server.store.DeleteAccount(ctx, reqQuery.ID) if err != nil { ctx.JSON(http.StatusInternalServerError, errorResponse(err)) return } ctx.JSON(http.StatusOK, gin.H{"message": "Account deleted successfully"}) }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>关键帧</title> <style> /*animation: test1 500ms 400ms steps(6,end) infinite reverse;*/ /*!* 动画名 持续时间 延时 时间函数 执行次数 动画运行的方向*!*/ /*!*animation-timing-function*!*/ *{ margin: 0; padding: 0; } .box1{ width: 500px; margin: 0 auto; height: 500px; border-bottom: 2px solid black; position: relative; } .box2 { height: 50px; width: 50px; border-radius: 50%; position: absolute; background-color: brown; animation: test2 500ms infinite alternate ; } .box2:nth-child(2){ left: 50px; background-color: #6bb8fc; animation-delay: 100ms; } .box2:nth-child(3){ left: 100px; background-color:#a71d5d; animation-delay: 150ms; } .box2:nth-child(4){ left: 150px; background-color: #990055; animation-delay: 200ms; } .box2:nth-child(5){ left: 200px; background-color: #ff253a; animation-delay: 250ms; } .box2:nth-child(6){ left: 250px; background-color: #6bb8fc; animation-delay: 300ms; } @keyframes test2 { from{ top: 0; } to{ top:450px; } } </style> </head> <body> <div class="box1"> <div class="box2"></div> <div class="box2"></div> <div class="box2"></div> <div class="box2"></div> <div class="box2"></div> <div class="box2"></div> </div> </body> </html>
/**************************************************************************/ /* */ /* Copyright (c) Microsoft Corporation. All rights reserved. */ /* */ /* This software is licensed under the Microsoft Software License */ /* Terms for Microsoft Azure RTOS. Full text of the license can be */ /* found in the LICENSE file at https://aka.ms/AzureRTOS_EULA */ /* and in the root directory of this software. */ /* */ /**************************************************************************/ /**************************************************************************/ /**************************************************************************/ /** */ /** GUIX Component */ /** */ /** System Management (System) */ /** */ /**************************************************************************/ #define GX_SOURCE_CODE /* Include necessary system files. */ #include "gx_api.h" #include "gx_system.h" /* Bring in externs for caller checking code. */ GX_CALLER_CHECKING_EXTERNS /**************************************************************************/ /* */ /* FUNCTION RELEASE */ /* */ /* _gxe_system_screen_stack_push PORTABLE C */ /* 6.1 */ /* AUTHOR */ /* */ /* Kenneth Maxwell, Microsoft Corporation */ /* */ /* DESCRIPTION */ /* */ /* This function checks errors in the system screen stack push */ /* function. */ /* */ /* INPUT */ /* */ /* screen Screen pointer to push */ /* */ /* OUTPUT */ /* */ /* status Completion status */ /* */ /* CALLS */ /* */ /* _gx_system_screen_stack_push The actual system screen */ /* stack push routine */ /* */ /* CALLED BY */ /* */ /* Application Code */ /* */ /* RELEASE HISTORY */ /* */ /* DATE NAME DESCRIPTION */ /* */ /* 05-19-2020 Kenneth Maxwell Initial Version 6.0 */ /* 09-30-2020 Kenneth Maxwell Modified comment(s), */ /* resulting in version 6.1 */ /* */ /**************************************************************************/ UINT _gxe_system_screen_stack_push(GX_WIDGET *screen) { UINT status; /* Check for appropriate caller. */ GX_INIT_AND_THREADS_CALLER_CHECKING /* Check for invalid input pointers. */ if (screen == GX_NULL) { return(GX_PTR_ERROR); } /* Call actual screen stack PUSH function. */ status = _gx_system_screen_stack_push(screen); /* Return the error status from screen stack push. */ return(status); }
/* eslint-disable react-hooks/exhaustive-deps */ import { GlobalContext } from 'contexts/global'; import { useContext, useEffect } from 'react'; import { BackgroundGrass } from 'utils/background-grass'; import { Cloud } from 'utils/cloud'; import { Coin } from 'utils/coin'; import { FloorGrass } from 'utils/floor-grass'; import { Grass } from 'utils/grass'; import { Kaboom } from 'utils/kaboom'; import { Mario } from 'utils/mario'; import { Pipe } from 'utils/pipe'; import { Sound, Sounds } from 'utils/sound'; import { Sprite } from 'utils/sprites'; export enum Layers { Background = 'background', Pipe = 'pipe', Parallax = 'parallax', Game = 'game', } export enum Scenes { Game = 'game', Lose = 'lose', } export const Game: React.FC = () => { const BASE_LINE = 55; const globalApi = useContext(GlobalContext); const { state, setState } = globalApi; let { score } = state; useEffect(() => { const k = new Kaboom().createCtx(); new Sprite(k).loadSprites(); new Sound(k).loadSounds(); const music = k.play(Sounds.MusicTheme, { volume: 0.2, loop: true }); k.scene(Scenes.Game, () => { k.layers( [Layers.Background, Layers.Parallax, Layers.Pipe, Layers.Game], Layers.Game ); // setTimeout(() => { // music.pause(); // }, 500); k.onKeyPress('m', () => { if (music.isPaused()) { music.play(); } else { music.pause(); } }); new FloorGrass({ k, baseLine: BASE_LINE }); new Grass({ k, baseLine: BASE_LINE }); new Pipe({ k, baseLine: BASE_LINE }); new Coin({ k }); new BackgroundGrass({ k }); new Cloud({ k }); const mario = new Mario({ k }); mario.onCollideCoin = () => { score += 100; setState({ score }); }; const scoreLabel = k.add([ k.text(`Score: ${score}`, { size: 40 }), k.pos(24, 24), ]); k.onUpdate(() => { score++; setState({ score }); scoreLabel.text = `Score: ${score}`; }); setInterval(() => { k.get('pipe').forEach((pipe) => { if (pipe.pos.x <= -50) pipe.destroy(); }); k.get('grass').forEach((grass) => { if (grass.pos.x <= -300) grass.destroy(); }); k.get('cloud').forEach((cloud) => { if (cloud.pos.x <= -300) cloud.destroy(); }); }, 1000); }); k.scene('lose', () => { new BackgroundGrass({ k }); k.add([ k.text('Game Over'), k.pos(k.center().x, k.center().y - 50), k.origin('center'), ]); k.add([ k.text(`Score: ${score}`, { size: 45 }), k.area({ cursor: 'mouse' }), k.pos(k.center()), k.origin('center'), ]); const playAgain = k.add([ k.text('Play Again!', { size: 45 }), k.pos(k.center().x, k.center().y + 50), k.area({ cursor: 'pointer' }), k.scale(1), k.origin('center'), ]); playAgain.onClick(() => { score = 0; setState({ score }); k.go(Scenes.Game); }); }); k.go(Scenes.Game); }, []); return <></>; };
import React, {ReactElement} from "react"; import styled from "styled-components"; interface ILabelProps { label: string; } interface IIconProps { icon: string; } export interface IFirstRowProps extends ILabelProps, IIconProps {} const StyledLabel = styled.label` font-size: 0.8em; `; const StyledIcon = styled.img` height: 1.2em; margin-right: 0.4em; `; const StyledLabelRow = styled.div` display: flex; flex-direction: row; align-items: center; margin-bottom: 6px; `; const FirstRow = ({icon, label}: IFirstRowProps): ReactElement => { return ( <StyledLabelRow> <StyledIcon src={icon} /> <StyledLabel>{label}</StyledLabel> </StyledLabelRow> ); }; export default FirstRow;
import { TestBed } from '@angular/core/testing'; import { Token } from '../models/token.model'; import { HttpClient } from '@angular/common/http'; import { LogService } from './log.service'; import { AccDataService } from '../shared/services/acc-data.service'; import { of } from 'rxjs'; class TestHttp { post(url, body, options) {} } describe('LogService', () => { let service: LogService; let http: HttpClient; beforeEach(() => { TestBed.configureTestingModule({ providers: [ AccDataService, LogService, { provide: HttpClient, useClass: TestHttp } ], }); service = TestBed.inject(LogService); http = TestBed.get(HttpClient); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should return token after call postLogData()', () => { const testUser = {username: 'someUsername', password: 'somePass'}; const testToken = {token: 'abc123'}; spyOn(http, 'post').and.returnValue(of(testToken)); service.postLogData(testUser).subscribe((returnedToken: Token) => { expect(returnedToken.token).toEqual(testToken.token); }); }); });
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix, ConfusionMatrixDisplay, f1_score import matplotlib.pyplot as plt def print_metrics(modelStr, Y_test=None, Y_pred=None, display_conf_matrix=False): print(f"\n------- Metrics for {modelStr} -------\n") # Define metrics class_report = classification_report(Y_test, Y_pred) acc_score = accuracy_score(Y_test, Y_pred) f1 = f1_score(Y_test, Y_pred) conf_matrix = confusion_matrix(list(Y_test), Y_pred) # Print metrics print(class_report) print(f"Accuracy for {modelStr}: {acc_score}") print(f"F1-Score for {modelStr}: {f1}") print(f"Confusion matrix for {modelStr}: \n{conf_matrix}\n") if display_conf_matrix: # Display metrics disp = ConfusionMatrixDisplay(conf_matrix) disp.plot() plt.show() def print_avg_metrics(modelStr, preds: list[list], y_test: list): '''Assumes same test set for every prediction''' print(f"\n------- Average Metrics for {modelStr} -------\n") avg_acc = 0 avg_f1 = 0 num_runs = 0 for pred in preds: avg_acc += accuracy_score(y_test, pred) avg_f1 += f1_score(y_test, pred) num_runs += 1 avg_acc = avg_acc/num_runs avg_f1 = avg_f1/num_runs print(f"Average accuracy for {modelStr} after {num_runs} run{'s'*min(num_runs-1,1)}: {avg_acc}") print(f"Average F1-score for {modelStr} after {num_runs} run{'s'*min(num_runs-1,1)}: {avg_f1}")
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>James Lin | Web Developer</title> <!-- Bootstrap Core CSS --> <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css"> <link href="vendor/simple-line-icons/css/simple-line-icons.css" rel="stylesheet"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous"> <!-- Custom CSS --> <link href="css/stylish-portfolio.min.css" rel="stylesheet"> <link rel="stylesheet" href="css/index.css"> <link rel="icon" href="img/de86e094498e5.png"> </head> <body id="page-top"> <!-- Navigation --> <a class="menu-toggle rounded" href="#"> <i class="fas fa-bars"></i> </a> <nav id="sidebar-wrapper"> <ul class="sidebar-nav"> <li class="sidebar-brand"> <a class="js-scroll-trigger" href="#page-top">Hello</a> </li> <li class="sidebar-nav-item"> <a class="js-scroll-trigger" href="#about">About</a> </li> <li class="sidebar-nav-item"> <a class="js-scroll-trigger" href="#services">Skills</a> </li> <li class="sidebar-nav-item"> <a class="js-scroll-trigger" href="#portfolio">Projects</a> </li> <li class="sidebar-nav-item"> <a class="js-scroll-trigger" href="#contact">Contact</a> </li> </ul> </nav> <!-- Header --> <header class="masthead d-flex"> <div class="container text-center my-auto"> <h1 class="mb-1">James Lin</h1> <h3 class="mb-5"> <em>Web Developer</em> </h3> <a class="btn btn-primary btn-xl js-scroll-trigger" href="#about">Find Out More</a> </div> <div class="overlay"></div> </header> <!-- About --> <section class="content-section bg-light" id="about"> <div class="container text-center"> <div class="row"> <div class="col-lg-10 mx-auto"> <h2>Hi, I'm James. Nice to meet you.</h2> <p class="lead mb-5"></p> <a class="btn btn-dark btn-xl js-scroll-trigger" href="#services">Skills</a> </div> </div> </div> </section> <!-- Services --> <section class="content-section bg-primary text-white text-center" id="services"> <div class="container"> <div class="content-section-heading"> <h3 class="text-secondary mb-0">Skills</h3> <h2 class="mb-5">What I Offer</h2> </div> <div class="row"> <div class="col-lg-3 col-md-6 mb-5"> <span class="service-icon rounded-circle mx-auto mb-3"> <i class="icon-screen-smartphone"></i> </span> <h4> <strong>Responsive</strong> </h4> <p class="text-faded mb-0">Looks great on any screen size!</p> </div> <div class="col-lg-3 col-md-6 mb-5"> <span class="service-icon rounded-circle mx-auto mb-3"> <i class="icon-pencil"></i> </span> <h4> <strong>Front end</strong> </h4> <p class="text-faded mb-0">HTML5, CSS3, Bootstrap, JavaScript</p> </div> <div class="col-lg-3 col-md-6 mb-5"> <span class="service-icon rounded-circle mx-auto mb-3"> <i class="fab fa-js"></i> </span> <h4> <strong>Back end</strong> </h4> <p class="text-faded mb-0">Node.js, Express.js, Python </p> </div> <div class="col-lg-3 col-md-6 mb-5"> <span class="service-icon rounded-circle mx-auto mb-3"> <i class="fas fa-database"></i> </span> <h4> <strong>Database</strong> </h4> <p class="text-faded mb-0">SQL, MySQL, MySQL Workbench, PostgreSQL, Microsoft SQL Server</p> </div> <div class="col-lg-3 col-md-6 mb-5"> <span class="service-icon rounded-circle mx-auto mb-3"> <i class="fab fa-github"></i> </span> <h4> <strong>Version Control</strong> </h4> <p class="text-faded mb-0">Git, GitHub</p> </div> <div class="col-lg-3 col-md-6 mb-5"> <span class="service-icon rounded-circle mx-auto mb-3"> <i class="fab fa-cloudsmith"></i> </span> <h4> <strong>Deployment</strong> </h4> <p class="text-faded mb-0">Nginx, AWS, AWS EC2, AWS RDS, AWS S3, AWS Route 53, AWS VPC</p> </div> <div class="col-lg-3 col-md-6 mb-5"> <span class="service-icon rounded-circle mx-auto mb-3"> <i class="fab fa-wordpress"></i> </span> <h4> <strong>CMS</strong> </h4> <p class="text-faded mb-0">WordPress, Divi Theme</p> </div> <div class="col-lg-3 col-md-6 mb-5"> <span class="service-icon rounded-circle mx-auto mb-3"> <i class="fab fa-docker"></i> </span> <h4> <strong>Others</strong> </h4> <p class="text-faded mb-0">Command line, Bash, Vim, HTTPS, API, Loopback4, AJAX, FTP, SSH, SCP, Linux, Ubuntu, Docker, Excel</p> </div> </div> </div> </section> <!-- Portfolio --> <section class="content-section" id="portfolio"> <div class="container"> <div class="content-section-heading text-center"> <h3 class="text-secondary mb-0">Portfolio</h3> <h2 class="mb-5">Recent Projects</h2> </div> <div class="row no-gutters"> <div class="col-lg-6"> <a class="portfolio-item h-100p" href="https://www.mediumclone.com/"> <span class="caption"> <span class="caption-content"> <h2>www.mediumclone.com</h2> <p class="mb-0">A place to write posts.</p> </span> </span> <img class="img-fluid" src="img/mediumclone.png" alt=""> </a> </div> <div class="col-lg-6"> <a class="portfolio-item" href="https://www.post67.com/"> <span class="caption"> <span class="caption-content"> <h2>www.post67.com</h2> <p class="mb-0">A place to share thoughts.</p> </span> </span> <img class="img-fluid" src="img/post67.png" alt=""> </a> </div> <div class="col-lg-6"> <a class="portfolio-item" href="https://www.img67.com/"> <span class="caption"> <span class="caption-content"> <h2>www.img67.com</h2> <p class="mb-0">A platform to upload images.</p> </span> </span> <img class="img-fluid" src="img/img67.png" alt=""> </a> </div> <div class="col-lg-6"> <a class="portfolio-item" href="https://www.vie67.com/"> <span class="caption"> <span class="caption-content"> <h2>www.vie67.com</h2> <p class="mb-0">A tool to share videos.</p> </span> </span> <img class="img-fluid" src="img/vie67.png" alt=""> </a> </div> <!--<div class="col-lg-6">--> <!--<a class="portfolio-item" href="#">--> <!--<span class="caption">--> <!--<span class="caption-content">--> <!--<h2>Workspace</h2>--> <!--<p class="mb-0">A yellow workspace with some scissors, pencils, and other objects.</p>--> <!--</span>--> <!--</span>--> <!--<img class="img-fluid" src="img/portfolio-4.jpg" alt="">--> <!--</a>--> <!--</div>--> </div> </div> </section> <!-- Call to Action --> <!--<section class="content-section bg-primary text-white">--> <!--<div class="container text-center">--> <!--<h2 class="mb-4">The buttons below are impossible to resist...</h2>--> <!--<a href="#" class="btn btn-xl btn-light mr-4">Click Me!</a>--> <!--<a href="#" class="btn btn-xl btn-dark">Look at Me!</a>--> <!--</div>--> <!--</section>--> <!-- Map --> <!--<section id="contact" class="map">--> <!--<iframe width="100%" height="100%" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://maps.google.com/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=Twitter,+Inc.,+Market+Street,+San+Francisco,+CA&amp;aq=0&amp;oq=twitter&amp;sll=28.659344,-81.187888&amp;sspn=0.128789,0.264187&amp;ie=UTF8&amp;hq=Twitter,+Inc.,+Market+Street,+San+Francisco,+CA&amp;t=m&amp;z=15&amp;iwloc=A&amp;output=embed"></iframe>--> <!--<br />--> <!--<small>--> <!--<a href="https://maps.google.com/maps?f=q&amp;source=embed&amp;hl=en&amp;geocode=&amp;q=Twitter,+Inc.,+Market+Street,+San+Francisco,+CA&amp;aq=0&amp;oq=twitter&amp;sll=28.659344,-81.187888&amp;sspn=0.128789,0.264187&amp;ie=UTF8&amp;hq=Twitter,+Inc.,+Market+Street,+San+Francisco,+CA&amp;t=m&amp;z=15&amp;iwloc=A"></a>--> <!--</small>--> <!--</section>--> <!-- Footer --> <footer id="contact" class="footer text-center"> <div class="container"> <ul class="list-inline mb-5"> <li class="list-inline-item"> <a class="social-link rounded-circle text-white mr-3" href="https://www.linkedin.com/in/james-lin-6a879a17a/"> <i class="icon-social-linkedin"></i> </a> </li> <li class="list-inline-item"> <a class="social-link rounded-circle text-white marginr-1" href="https://github.com/jameslin12379"> <i class="icon-social-github"></i> </a> </li> <li class="list-inline-item"> <a class="social-link rounded-circle text-white mr-3" href="mailto:jameslin12379@gmail.com"> <i class="fas fa-envelope"></i> </a> </li> </ul> <p class="text-muted small mb-0">Copyright &copy; James Lin 2019</p> </div> </footer> <!-- Scroll to Top Button--> <a class="scroll-to-top rounded js-scroll-trigger" href="#page-top"> <i class="fas fa-angle-up"></i> </a> <!-- Bootstrap core JavaScript --> <script src="vendor/jquery/jquery.min.js"></script> <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Plugin JavaScript --> <script src="vendor/jquery-easing/jquery.easing.min.js"></script> <!-- Custom scripts for this template --> <script src="js/stylish-portfolio.min.js"></script> </body> </html>
import { AlertDialog, AlertDialogBody, AlertDialogContent, AlertDialogFooter, AlertDialogHeader, AlertDialogOverlay, Button, Flex, Heading, useDisclosure, useToast, } from "@chakra-ui/react"; import { useEffect, useRef, useState } from "react"; import { useNavigate, useParams } from "react-router-dom"; import supabaseType from "../resources/types"; import AddPlayerModal from "./AddPlayerModal"; import PlayerDisplayBox from "./PlayerDisplayBox"; import SessionTagRow from "./SessionTagRow"; interface EditSessionProps { supabase: supabaseType; user: any; } //does playerCount or numberOfPlayers matter here? //if there are 0 players in the game, automatically open the add player modal const EditSession = ({ supabase, user }: EditSessionProps) => { let { sessionId } = useParams(); const [session, setSession] = useState<any>({}); const [playerCount, setPlayerCount] = useState<number>(0); const [myPlayers, setMyPlayers] = useState<any>([]); const { isOpen, onOpen, onClose } = useDisclosure(); const navigate = useNavigate(); const toast = useToast(); const { isOpen: isAlertOpen, onOpen: onAlertOpen, onClose: onAlertClose, } = useDisclosure(); const cancelRef = useRef<HTMLButtonElement>(null); const { isOpen: isConfirmOpen, onOpen: onConfirmOpen, onClose: onConfirmClose, } = useDisclosure(); const confirmRef = useRef<HTMLButtonElement>(null); //fetch all results with session_id equal to this session id, map them into player boxes. //player boxes should have a QR code that says "log in to confirm your score" //tag toggling happens inside the saved player box, at this level //ultimately you'll grab all results for games you own, then grab the five most common player ids, then grab those by name //for now, just grab all player rows you own useEffect(() => { console.log("fetching my players"); const fetchMyPlayers = async () => { if (user && user.id) { try { let { data: myFetchedPlayers } = await supabase .from("players") .select("*") .eq("user_id", user.id); setMyPlayers(myFetchedPlayers); } catch (error) { console.error(error); } } }; fetchMyPlayers(); }, [supabase, user]); useEffect(() => { const fetchSessionDetails = async () => { try { let { data: sessions } = await supabase .from("sessions") .select("*, results(*, players(name)), games(id, name)") .eq("id", sessionId); if (sessions) { const fetchedSession = sessions[0]; setSession(fetchedSession); if ( fetchedSession && fetchedSession.results && fetchedSession.results.length ) { const numberOfPlayers = fetchedSession.results.length; setPlayerCount(numberOfPlayers); } } } catch (error) { console.error(error); } }; fetchSessionDetails(); }, [sessionId, supabase, session.results]); const handleDelete = async () => { try { const { data: deletedSession } = await supabase .from("sessions") .delete() .eq("id", sessionId) .select(); if (deletedSession) { onAlertClose(); navigate(`/`); toast({ title: `Game session was successfully deleted!`, status: "success", duration: 5000, position: "top", isClosable: true, }); } } catch (error) { console.error(error); toast({ title: "There was an error...", description: `${error}`, status: "error", duration: 10000, position: "top", isClosable: true, }); } }; const handleFinalize = async () => { try { const { data: updatedSession } = await supabase .from("sessions") .update({ is_finalized: true }) .eq("id", sessionId) .select(); if (updatedSession) { onConfirmClose(); navigate(`/`); toast({ title: `Game session was successfully finalized!`, status: "success", duration: 5000, position: "top", isClosable: true, }); } } catch (error) { console.error(error); toast({ title: "There was an error...", description: `${error}`, status: "error", duration: 10000, position: "top", isClosable: true, }); } }; return ( <Flex direction="column" alignItems="center"> {session && session.games && ( <> <Flex direction="column" alignItems="center" bgColor="teal.900" color="white" width="390px" padding="10px" > {!session.is_finalized && ( <Heading size="sm">Enter scores for</Heading> )} <Heading size="md">A game of {session.games.name}</Heading> <Heading size="sm">played on {session.date_played}</Heading> {/* <Flex>{JSON.stringify(session, null, 4)}</Flex> */} </Flex> <SessionTagRow user={user} supabase={supabase} finalized={session.is_finalized} gameId={session.game_id} sessionId={session.id} /> {!session.is_finalized && ( <Flex direction="row" justifyContent="center" width="375px" mt="10px" > <Button colorScheme="blue" isDisabled={session.is_finalized} onClick={onOpen} > + Add Player </Button> </Flex> )} <AddPlayerModal isOpen={isOpen} onClose={onClose} supabase={supabase} sessionId={sessionId} playerCount={playerCount} setPlayerCount={setPlayerCount} myPlayers={myPlayers} setMyPlayers={setMyPlayers} user={user} /> {session && session.results && session.results.length > 0 && session.results.map((result: any) => ( <PlayerDisplayBox key={result.id} result={result} gameId={session.games.id} finalized={session.is_finalized} supabase={supabase} user={user} playerCount={playerCount} setPlayerCount={setPlayerCount} /> ))} {session && session.results && session.results.length === 0 && ( <Heading size="md" mt="20px"> No scores yet! </Heading> )} </> )} {!session.is_finalized && ( <Flex direction="row" justifyContent="space-between" width="375px" mt="10px" mb="10px" > <Button colorScheme="green" isDisabled={playerCount < 1 || session.is_finalized} onClick={onConfirmOpen} > Save Game </Button> <Button colorScheme="red" isDisabled={session.is_finalized} onClick={onAlertOpen} > Delete Session </Button> </Flex> )} <AlertDialog isOpen={isAlertOpen} leastDestructiveRef={cancelRef} onClose={onAlertClose} > <AlertDialogOverlay> <AlertDialogContent> <AlertDialogHeader fontSize="lg" fontWeight="bold"> Delete Session </AlertDialogHeader> <AlertDialogBody> Are you sure? All scores and tags will also be deleted. This action can't be undone! </AlertDialogBody> <AlertDialogFooter> <Button ref={cancelRef} onClick={onAlertClose}> Cancel </Button> <Button colorScheme="red" onClick={handleDelete} ml={3}> Delete </Button> </AlertDialogFooter> </AlertDialogContent> </AlertDialogOverlay> </AlertDialog> <AlertDialog isOpen={isConfirmOpen} leastDestructiveRef={confirmRef} onClose={onConfirmClose} > <AlertDialogOverlay> <AlertDialogContent> <AlertDialogHeader fontSize="lg" fontWeight="bold"> Finalize Session </AlertDialogHeader> <AlertDialogBody> Once a session is finalized, it cannot be edited! You can leave a session unsaved if you think you will need to edit it later. </AlertDialogBody> <AlertDialogFooter> <Button ref={confirmRef} onClick={onConfirmClose}> Cancel </Button> <Button colorScheme="green" onClick={handleFinalize} ml={3}> Finalize </Button> </AlertDialogFooter> </AlertDialogContent> </AlertDialogOverlay> </AlertDialog> </Flex> ); }; export default EditSession;
import React from 'react'; import { Form, Input, Row, Col, DatePicker, Select, message } from 'antd'; import $http from 'api'; import { useDispatch, useSelector } from 'react-redux'; import { attendanceRule } from 'utils/rules'; import moment from 'moment'; import { mapData } from 'utils/mapData'; const AttendanceDetail = ({ _initAttendanceList }) => { const dispatch = useDispatch(); const [form] = Form.useForm(); const { attendanceDetail } = useSelector((state) => state.attendanceInfo); //- 修改 const updateVal = async (type) => { const updateVal = form.getFieldValue(type) const { code, msg } = await $http.updateAttendance({ _id: attendanceDetail._id, type, updateVal }); if (code) return message.success(msg); _initAttendanceList(); dispatch({ type: 'attendanceInfo/getAttendanceDetail', payload: { _id: attendanceDetail._id } }) } return ( <Form form={form} layout="vertical" initialValues={ { attendanceType: attendanceDetail?.attendanceType, createTime: moment(attendanceDetail?.createTime), staffName: attendanceDetail?.staffName.userName } } > { <Row justify={'space-between'}> <Col span={11} > <Form.Item label='员工姓名' name='staffName' required rules={attendanceRule['staffName']} > <Input readOnly className="border-color" /> </Form.Item> </Col> <Col span={11} > <Form.Item label='考勤类型' name='attendanceType' required rules={attendanceRule['attendanceType']} > <Select placeholder="请输入考勤类型" onChange={() => updateVal('attendanceType')}> {mapData['attendanceType'].map((val, index) => ( <Select.Option key={index} value={index}> {val} </Select.Option> ))} </Select> </Form.Item> </Col> <Col span={11} > <Form.Item label=' 考勤时间' name='createTime' required rules={attendanceRule['createTime']} > <DatePicker placeholder="请选择考勤填写时间" style={{ width: '100%' }} onChange={() => updateVal('createTime')} /> </Form.Item> </Col> </Row> } </Form> ); }; export default AttendanceDetail;
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>v-model</title> <script src="js/vue.min.js"></script> </head> <body> <!--文本框--> <div id="app"> 用户名:<input v-model="test"> {{test}}<br> <!--下拉列表框--> 前端语言: <select v-model="selected"> <option value="HTML">HTML</option> <option value="CSS">CSS</option> <option value="JavaScript">JavaScript</option> </select> <span>选择是:{{ selected }}</span> <br> <!--单选框--> 性别: <input type="radio" id="boy" value="男" v-model="picked"> <label for="boy">男</label> <input type="radio" id="girl" value="女" v-model="picked"> <label for="girl">女</label> <br> <span>选择是: {{ picked }}</span> <br> <!--复选框-->爱好: <input type="checkbox" id="one" value="羽毛球" v-model="checkedNames"> <label for="one">羽毛球</label> <input type="checkbox" id="two" value="音乐" v-model="checkedNames"> <label for="two">音乐</label> <input type="checkbox" id="three" value="乒乓球" v-model="checkedNames"> <label for="three">乒乓球</label> <br> <span>选择的爱好是: {{ checkedNames }}</span> </div> <script> new Vue({ el: '#app', data: { test: 'lb', selected:'JavaScript', picked:'女', checkedNames:['音乐','乒乓球'] } }); </script> </body> </html>
import { HttpClient } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup } from '@angular/forms'; import { LoadingController, ModalController, ToastController } from '@ionic/angular'; import { ApiServiceService } from '../../../services/api-service.service'; @Component({ selector: 'app-modal-anular-factura', templateUrl: './modal-anular-factura.page.html', styleUrls: ['./modal-anular-factura.page.scss'], }) export class ModalAnularFacturaPage implements OnInit { tema = localStorage.getItem('cambiarTema'); formFactura: FormGroup; formComentario: FormGroup; factura = {}; dataFactura = false; constructor( public formBuilder: FormBuilder, public http: HttpClient, public apiService: ApiServiceService, public modalController: ModalController, public toastController: ToastController, public loadingController: LoadingController ) { this.tema = localStorage.getItem('cambiarTema'); } ngOnInit() { this.formFactura = this.formBuilder.group({ factura: [''] }); this.formComentario = this.formBuilder.group({ comentario: [''] }) } searchKeyFactura(_event){ if(_event == 13){ this.searchFactura() } } searchFactura(){ this.http.get(this.apiService.buscarFactura + this.formFactura.value.factura).subscribe(res=>{ this.factura = res; let date = new Date(this.factura['date_creation']).toUTCString(); this.factura['auxFecha'] = date; console.log("FACTURA =>", this.factura); this.dataFactura = true; this.toast("Se ha encontrado la factura", "success") },(error)=>{ console.log("ERROR =>", error.error); if(error.error.code){ this.toast(error.error.message, "danger") }else{ this.toast("Error buscando la factura", "danger"); } this.dataFactura = false; }) } async anularFactura(){ const loading = await this.loadingController.create({ message: 'Cargando...', cssClass: 'spinner', }); loading.present(); let data = { num_factura: this.factura['num_factura'], detalle: this.formComentario.value.comentario } this.http.post(this.apiService.anularFactura, data).subscribe(res =>{ console.log("RES =>", res); this.toast("Factura anulada con exito","success"); loading.dismiss(); this.cerrarModal(); },(error)=>{ console.log("ERROR =>", error.error); this.toast("Ha ocurrido un error al intentar anular la factura", "danger"); loading.dismiss(); }) } async toast(msg, status) { const toast = await this.toastController.create({ message: msg, position: 'top', color: status, duration: 3000, cssClass: 'toastCss', }); toast.present(); } cerrarModal(){ this.modalController.dismiss(); } }
<template> <v-layout wrap> <new-edit-sheet /> <delete-dialog /> <div class="headline">Items</div> <v-spacer /> <v-btn color="primary" dark class="mb-2" @click="createEditShow()">New</v-btn> <v-flex xs12> <v-layout column> <v-flex> <v-card> <v-card-title> <v-text-field v-model="q" append-icon="search" label="Search by code, name" single-line hide-details clearable /> </v-card-title> <v-data-table :headers="headers" :items="items" :server-items-length="total" :page.sync="page" :items-per-page.sync="itemsPerPage" :sort-by.sync="sortBy" :sort-desc.sync="descending" :loading="loading" loading-text="Loading... Please wait" > <template v-slot:item.reset-window="{ item }"> <v-icon small class="mr-2" @click="reset_planning_window(item.code)">mdi-reload</v-icon> </template> <template v-slot:item.data-table-actions="{ item }"> <span class="table_action_icon"> <v-icon small class="mr-2" @click="createEditShow(item)">mdi-pencil</v-icon> <v-icon small @click="removeShow(item)">mdi-delete</v-icon> </span> </template> </v-data-table> </v-card> </v-flex> </v-layout> </v-flex> </v-layout> </template> <script> import { mapFields } from "vuex-map-fields"; import { mapActions } from "vuex"; import DeleteDialog from "@/item/DeleteDialog.vue"; import NewEditSheet from "@/item/NewEditSheet.vue"; import { mapState } from "vuex"; export default { name: "ItemTable", components: { DeleteDialog, NewEditSheet, }, data() { return { headers: [ { text: "Code", value: "code", sortable: true }, { text: "Name", value: "name", sortable: true }, { text: "Weight", value: "weight", sortable: true, align: "center", }, { text: "Volume", value: "volume", sortable: false, align: "center", }, { text: "Active", value: "is_active", sortable: false, align: "center", }, { text: "Description", value: "description", sortable: false, align: "left", }, { text: "", value: "data-table-actions", sortable: false, align: "end", }, ], }; }, computed: { ...mapFields("item", [ "table.options.q", "table.options.page", "table.options.itemsPerPage", "table.options.sortBy", "table.options.descending", "table.loading", "table.rows.items", "table.rows.total", ]), }, mounted() { this.getAll({}); this.$watch( (vm) => [vm.page], () => { this.getAll(); } ); this.$watch( (vm) => [vm.q, vm.itemsPerPage, vm.sortBy, vm.descending], () => { this.page = 1; this.getAll(); } ); }, destroyed() { this.closeCreateEdit(); }, methods: { ...mapActions("item", [ "getAll", "createEditShow", "removeShow", "closeCreateEdit", ]), }, }; </script> <style> .table_action_icon { white-space: nowrap; } </style>
import { zodResolver } from '@hookform/resolvers/zod'; import { useForm } from 'react-hook-form'; import { z } from 'zod'; import DialogButton from './DialogButton'; import axios from 'axios'; import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form'; import { Input } from '@/components/ui/input'; import { toast } from '@/components/ui/use-toast'; import { useState } from 'react'; const FormSchema = z.object({ username: z.string().min(2, { message: 'Username must be at least 2 characters.' }) }); export default function SearchInput() { const [orgLink, setOrgLink] = useState(''); // Added state for original link const form = useForm({ resolver: zodResolver(FormSchema), defaultValues: { username: '' } }); function onSubmit(data) { toast({ title: 'You submitted the following values:', description: ( <pre className="mt-2 w-[340px] rounded-md bg-slate-950 p-4"> <code className="text-white">{JSON.stringify(data, null, 2)}</code> </pre> ) }); } return ( <div className="grid h-screen place-items-center mt-[-8%]"> <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)} className="w-2/3 space-y-6"> <FormField control={form.control} name="username" render={({ field }) => ( <FormItem> <FormLabel>Paste Your Url here.</FormLabel> <FormControl> <Input placeholder="Enter Link to Shrink" {...field} value={field.value} onChange={(e) => { field.onChange(e); setOrgLink(e.target.value); // Updated to set original link state }} /> </FormControl> <FormMessage /> </FormItem> )} /> <DialogButton url={orgLink} /> // Passed orgLink to DialogButton </form> </Form> </div> ); }
import { useState, createContext } from "react"; export const UserContext = createContext(null); const ContextProvider = ({ children }) => { const [user, setUser] = useState({ name: '', token: '' }); const updateName = newName => setUser({ ...user, name: newName }); const updateToken = newToken => setUser({ ...user, token: newToken }); const passProps = { user, updateName, updateToken }; return <UserContext.Provider value={passProps}>{children}</UserContext.Provider>; }; export default ContextProvider;
import 'package:flutter/material.dart'; import 'dart:convert'; import 'package:http/http.dart' as http; import 'product.dart'; import '../models/http_exeption..dart'; class Products with ChangeNotifier { List<Product> _items = []; String? authToken; String? userId; List<Product> get items { return [..._items]; } List<Product> get favoritesItems { return _items.where((element) => element.isFavorite).toList(); } Product findById(String id) { return _items.firstWhere((element) => element.id == id); } void updateToken(String? token, String? userId) { this.authToken = token; this.userId = userId; } Future<void> fetchAndSetProducts([bool filterByUser = false]) async { String filterString = filterByUser ? 'orderBy="creatorId"&equalTo="$userId"' : ''; var url = 'https://flutter-shop-app-b01f4-default-rtdb.firebaseio.com/products.json?auth=$authToken&$filterString'; try { final response = await http.get(Uri.parse(url)); final data = json.decode(response.body) as Map<String, dynamic>; if (data == null) { return; } url = 'https://flutter-shop-app-b01f4-default-rtdb.firebaseio.com/userFavorites/$userId.json?auth=$authToken'; final favoriteResponse = await http.get(Uri.parse(url)); final favoriteData = json.decode(favoriteResponse.body); final List<Product> temp = []; data.forEach((prodId, prodData) { temp.add(Product( id: prodId, title: prodData['title'], description: prodData['description'], price: prodData['price'], imageUrl: prodData['imageUrl'], isFavorite: favoriteData == null ? false : favoriteData[prodId] ?? false)); }); _items = temp; notifyListeners(); } catch (error) { throw error; } } Future<void> addProduct(Product newproduct) async { final url = 'https://flutter-shop-app-b01f4-default-rtdb.firebaseio.com/products.json?auth=$authToken'; try { final value = await http.post(Uri.parse(url), body: json.encode({ 'title': newproduct.title, 'description': newproduct.description, 'price': newproduct.price, 'imageUrl': newproduct.imageUrl, 'creatorId': userId, })); final pro = Product( id: json.decode(value.body)['name'], title: newproduct.title, description: newproduct.description, price: newproduct.price, imageUrl: newproduct.imageUrl); _items.add(pro); notifyListeners(); } catch (error) { throw error; } } Future<void> updateProduct(Product newProduct) async { final url = 'https://flutter-shop-app-b01f4-default-rtdb.firebaseio.com/products/${newProduct.id}.json?auth=$authToken'; try { await http.patch(Uri.parse(url), body: json.encode({ 'title': newProduct.title, 'description': newProduct.description, 'price': newProduct.price, 'imageUrl': newProduct.imageUrl, })); final productIndex = _items.indexWhere((element) => element.id == newProduct.id); _items[productIndex] = newProduct; notifyListeners(); } catch (error) { throw error; } } Future<void> removeProduct(String id) async { final url = 'https://flutter-shop-app-b01f4-default-rtdb.firebaseio.com/products/$id.json?auth=$authToken'; final response = await http.delete(Uri.parse(url)); if (response.statusCode >= 400) { throw HttpException('Deleting Failed'); } _items.removeWhere((element) => element.id == id); notifyListeners(); } }
// Test -------------------------- Importing the Packages --------------------------------- import { CardContent, Typography, Collapse } from "@mui/material"; // Test -------------------------- Importing the styles / other components ---------------- // Test -------------------------- Structure of Props ---------------------------------- type CardContextExpansionProps = { heading: string; paragraph: string; isExpanded: boolean; }; // Test -------------------------- The current component ---------------------------------- const CardContextExpansion = ({ heading, paragraph, isExpanded, }: CardContextExpansionProps) => { return ( <CardContent sx={{ pt: 0 }}> <Typography variant="h6" gutterBottom> {heading.charAt(0).toUpperCase() + heading.slice(1)} </Typography> <Typography variant="body2" component="span" m={0}> {paragraph.split(".")[0]}{" "} <Collapse in={isExpanded} timeout="auto"> {paragraph.slice(paragraph.indexOf(".") + 1)} </Collapse> </Typography> </CardContent> ); }; // Test -------------------------- Exporting the current component ------------------------ export default CardContextExpansion;
# Mantendo estados dentro da classe class Camera: def __init__(self, name, filmando=False): self.name = name self.filmando = filmando def filmar(self): if self.filmando: print(f'{self.name} já está filmando...') # return print(f'{self.name} está filmando...') self.filmando = True def parar_filmar(self): if not self.filmando: print(f'{self.name} não está filmando...') # return print(f'{self.name} está parando de filmar...') self.filmando = False def fotografar(self): if self.filmando: print(f'{self.name} não pode fotografar filmando!') # return print(f'{self.name} está fotografando!') c1 = Camera('Canon') c2 = Camera('Sony') # c1.filmar() # c1.filmar() # # c1.fotografar() # c1.fotografar() # c1.parar_filmar() # c1.fotografar() # c1.parar_filmar() # c1.fotografar() # c1.fotografar() # c1.fotografar() # c1.parar_filmar() # c1.filmar() # c1.filmar() # # c1.parar_filmar() # c1.parar_filmar() # c1.fotografar() # c1.fotografar() # c1.fotografar() # c1.parar_filmar() # c1.fotografar() c2.filmar() c1.filmar() c1.fotografar() c2.fotografar() c1.parar_filmar() c1.fotografar() c1.fotografar() c1.fotografar() c1.fotografar() c2.parar_filmar() c2.parar_filmar() c2.fotografar() c2.fotografar() c2.fotografar() # print(c1.filmando) # print(c2.filmando)
function Logger(target: Function) { ///o target de DECORATORS DE CLASSES __ sempre_ será uma FUNCTION (pq é a/uma CONSTRUCTOR FUNCTION, o alvo, que é uma CLASS).... ---> você também poderia chamar esse parâmetro de 'constructor', pq ele sempre será um constructor, também.... ///este é um DECORATOR.... --> decorators são aplicadas a coisas, como CLASSES, por exemplo... (e decorators são sempre escritos com INICIAL MAIÚSCULA)... console.log('Logging...'); console.log(target); } @Logger ///////é isso que vai __''''APLICAR NOSSA DECORATION A ESSA CLASS''''... ---> você deve escrever o identificador de '@' e aí + 'nomeDeSeuDecorator', isso tudo SEM EXECUTAR esse call ( ou seja, sem parênteses).... class Person { ////decorators são 'all about classes', na verdade... name = 'Max'; constructor() { console.log('Creating person object...'); } } const person = new Person(); console.log(person); // ------> CERTO.... -----------> MAS NESSE EXEMPLO, // NÃO TEMOS NENHUM DECORATOR ENVOLVIDO.... ////adicionamos um DECORATOR LÁ NO TOPO.... ---> um decorator, no final das contas, é uma mera FUNCTION.... // --> É UMA __ FUNCTION___ QUE É APLICADA A ___ ALGO__, no caso, uma // CLASS, // de uma certa forma.... // --> o '@' // É UM __IDENTIFICADOr__ ESPECIAL // ___ NO TYPESCRIPT, QUE O TYPESCRIPT ENTENDE/RECONHECe.... // ------> É CLARO QUE DEPOIS DE '@' // vamos __ APONTAR A UMA FUNCTION/DECORATOR.... ---> basta // APONTAR, // __ SEM EXECUTAR__ ('()' ).... // ----------> CERTO.. // ---> AÍ O TYPESCRIPT NOS DÁ UMA INFO: // 'Logger accepts too few arguments to be used as a decorator here. // Did you mean to call it FIRST and write '@Logger()'? ' // --------> OK.... ---> ISSO SIGNIFICA QUE: // 1) O TYPESCRIPT__ ENTENDE/ENTENDEU QUE VAMSO QUERER O UTILIZAR COMO UM DECORATOR, EM ALGUMA CLASS... // 2) A MÁ NOTÍCIA É QUE // AINDA NÃO PASSAMOS ARGUMENTOS SUFICIENTES..... // ---------> E, DE FATO, // DECORATORS _ __ RECEBEM__ ARGUMENTOS__.... // -> QUANTOS ARGUMENTOS? // --> DEPENDE DO __ LOCAL__ EM QUE VOCê VAI QUERER UTILIZAR ESSE DECORATOR... // --> aqui, // PARA UM _ DECORATOR QUE __ ADICIONAMOS/APLICAMOS EM 1 CLASS, // VAMOS __ OBTER/EXIGIR_ SÓ 1 // PARÂMETRo/ARGUMENTO... // --> OK.... ISSO SIGNFICA QUE // NOSSA // LÓGICA // DO DECORATOR É // __EXECUTADA__ ANTEs___ DE TODO O RESTO.... (Basta ver a lógica do decorator, de print, e o print no console)...
@node Your First Board @chapter Your First Board In this chapter, we're going to walk you through creating a few very simple boards, just to give you an idea of the way the programs work and how to do the things that are common to all project. Each board will build upon techniques learned from the previous board. While this manual is not intended to cover the @code{gschem} program, we will be instructing you on the minimum you'll need to know to use @code{gschem} with @code{pcb}. Please refer to the @code{gschem} documentation for further details. The first board will be a simple LED and resistor. It will show you how to create a board, place elements, and route traces. The second board will be a simple LED blinker, which will involve creating schematics, setting up a project, and creating new symbols and footprints. The third board will be another blinker, this time with surface mount devices and four layers, which will introduce power planes, vias, and thermals. @ifnottex @menu * LED Board:: * Blinker Board:: * SMT Blinker:: @end menu @end ifnottex @include fb-led.texi @include fb-blinker.texi @include fb-smt.texi
// @ts-check import { DiscountApplicationStrategy } from "../generated/api"; // Use JSDoc annotations for type safety /** * @typedef {import("../generated/api").RunInput} RunInput * @typedef {import("../generated/api").FunctionRunResult} FunctionRunResult * @typedef {import("../generated/api").Target} Target * @typedef {import("../generated/api").ProductVariant} ProductVariant */ /** * @type {FunctionRunResult} */ const EMPTY_DISCOUNT = { discountApplicationStrategy: DiscountApplicationStrategy.First, discounts: [], }; // The configured entrypoint for the 'purchase.product-discount.run' extension target /** * @param {RunInput} input * @returns {FunctionRunResult} */ export function run(input) { console.log("🚀 ~ run ~ input:", input); const targets = input.cart.lines // Only include cart lines with a quantity of two or more // and a targetable product variant .filter( (line) => line.quantity >= 2 && line.merchandise.__typename == "ProductVariant", ) .map((line) => { const variant = /** @type {ProductVariant} */ (line.merchandise); return /** @type {Target} */ ({ // Use the variant ID to create a discount target productVariant: { id: variant.id, }, }); }); console.log("Targets", targets); if (!targets.length) { // You can use STDERR for debug logs in your function console.error("No cart lines qualify for volume discount."); return EMPTY_DISCOUNT; } // The @shopify/shopify_function package applies JSON.stringify() to your function result // and writes it to STDOUT return { discounts: [ { // Apply the discount to the collected targets targets, // Define a percentage-based discount value: { percentage: { value: "10.0", }, }, }, ], discountApplicationStrategy: DiscountApplicationStrategy.First, }; }
/* * Copyright 2021 Infosys Ltd. * Use of this source code is governed by GNU General Public License version 2 * that can be found in the LICENSE file or at * https://opensource.org/licenses/GPL-2.0 */ package com.infy.service; import com.infy.service.dto.GivenDailyLikesDTO; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.Optional; /** * Service Interface for managing {@link com.infy.domain.GivenDailyLikes}. */ public interface GivenDailyLikesService { /** * Save a givenDailyLikes. * * @param givenDailyLikesDTO the entity to save. * @return the persisted entity. */ GivenDailyLikesDTO save(GivenDailyLikesDTO givenDailyLikesDTO); /** * Get all the givenDailyLikes. * * @param pageable the pagination information. * @return the list of entities. */ Page<GivenDailyLikesDTO> findAll(Pageable pageable); /** * Get the "id" givenDailyLikes. * * @param id the id of the entity. * @return the entity. */ Optional<GivenDailyLikesDTO> findOne(Long id); /** * Delete the "id" givenDailyLikes. * * @param id the id of the entity. */ void delete(Long id); }
import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.io.IOException; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; public class WebCrawler { /**------------------------------------- Web crawling related methods ------------------------------------------------*/ /** * This method is the main method that crawls the web */ public static void WebCrawler(){ //System.setProperty("webdriver.chrome.driver", "chromedriver-win64/chromedriver.exe"); // THIS ALSO WORKS System.setProperty("webdriver.chrome.driver", ENV_vars.chromedriver); // Path to the chromedriver executable List<String> URL_List = makeListofURLs(PublicVars.BASE_URL); // Loop through the list of URLs and extract the post details using the method extractPostDetails() for (String url : URL_List) { extractPostDetails(url);//, driver); // Write the post data to a JSON file also happens in the extractPostDetails() method } closeAll(); try { JsonOps.prepareBulkApiData("web_scraped_data", "bulk_web_scraped_data"); } catch (IOException e) { throw new RuntimeException(e); } //System.out.println("\n\n\nCrawling process completed. Total posts extracted: " + posts_array.size() + "\n"); } /** * This method makes a list of URLs to crawl * @param url The BASE URL to crawl * @return A list of URLs to crawl */ private static List<String> makeListofURLs(String url) { ChromeOptions options = new ChromeOptions(); options.addArguments("--remote-allow-origins=*"); WebDriver driver = new ChromeDriver(options); driver.get(PublicVars.BASE_URL); // Wait for the cookies button to appear WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); // Locate the cookies button and wait until it's clickable, then click it WebElement cookiesButton = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("button.css-47sehv"))); cookiesButton.click(); System.out.print("Cookies button clicked\n"); // Debugging purposes // Locate the "Load More" button and click it WebElement button = driver.findElement(By.cssSelector("button.button.button--alt.feed-button")); // Scroll to the element ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", button); button.click(); System.out.print("Load More button clicked for the first time\n"); // Debugging purposes long endTime = System.currentTimeMillis() + 60000; // 10 seconds in future try { Thread.sleep(5000); } catch (InterruptedException e) { throw new RuntimeException(e); } while (System.currentTimeMillis() < endTime) { WebElement footer = driver.findElement(By.cssSelector(".p-footer-inner")); ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", footer); System.out.println("We reached the footer of the page"); // Debugging purposes try { WebDriverWait wait2 = new WebDriverWait(driver, Duration.ofSeconds(10)); WebElement loadMoreButton = wait2.until(ExpectedConditions.elementToBeClickable(By.cssSelector("button.button.button--alt.feed-button"))); ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", loadMoreButton); if (loadMoreButton.isDisplayed() == false) { System.out.println("Load More button not displayed"); // Debugging purposes } else { loadMoreButton.click(); System.out.println("Load More button clicked"); // Debugging purposes } try { Thread.sleep(1000); // Scroll every 1 second } catch (InterruptedException e) { e.printStackTrace(); } } catch (TimeoutException e) { System.out.println("Load More button not found"); // Debugging purposes } } WebElement top_of_page = driver.findElement(By.cssSelector("div.p-header-content")); ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", top_of_page); System.out.println("Scrolled to the top of the page\n"); // Debugging purposes // Get all the links on the page List<WebElement> links = driver.findElements(By.tagName("a")); List<String> postLinks = new ArrayList<>(); // Extract the URLs from the links for (WebElement link : links) { String tmpurl = link.getAttribute("href"); if (tmpurl != null && postLinks.contains(tmpurl) == false && tmpurl.contains("threads") == true && tmpurl.endsWith("/latest") == false) { postLinks.add(tmpurl); //System.out.println(tmpurl); // Debugging purposes } else if (tmpurl != null && postLinks.contains(tmpurl) == true && tmpurl.contains("threads") == true) { //System.out.println("Duplicate: " + tmpurl + "\n"); // Debugging purposes } } // The first two URLs are always repeated, so remove them postLinks.remove(0); postLinks.remove(1); // Print the URLs for Debugging purposes for (String item : postLinks) { System.out.println(item); } System.out.println("Number of links: " + postLinks.size()); // Debugging purposes kill_driver(driver); return postLinks; } /** * This method extracts the post details from a given URL * @param post_url The URL of the post */ private static void extractPostDetails(String post_url){//, WebDriver driver) { try { ChromeOptions options = new ChromeOptions(); options.addArguments("--remote-allow-origins=*"); WebDriver driver = new ChromeDriver(options); driver.get(post_url); // Add the driver to the list of drivers to ensure they are all closed at the end PublicVars.drivers_list.add(driver); System.out.println("Fetching URL: " + post_url + "\n"); String post_title; try { post_title = driver.getTitle(); if (post_title == null || post_title.isEmpty()) { // Error handling for the title not being found try{ WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(8)); WebElement contentElement = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("h1.MessageCard__thread-title"))); post_title = contentElement.getText(); } catch (NoSuchElementException e) { post_title = "NONE"; // Default value } } post_title = post_title.replaceFirst(" \\| Motorcycle Forum", ""); } catch (java.util.NoSuchElementException e) { post_title = "NONE"; // Default value } String post_content; try { //post_content = driver.findElement(By.cssSelector(".message-body.js-selectToQuote .bbWrapper")).getText(); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(8)); WebElement contentElement = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".message-body.js-selectToQuote .bbWrapper"))); post_content = contentElement.getText(); } catch (NoSuchElementException e) { post_content = "NONE"; // Default value } String post_author = driver.findElement(By.cssSelector("a.MessageCard__user-info__name")).getText(); String post_date = driver.findElement(By.cssSelector("time[qid='post-date-time']")).getAttribute("data-date-string"); String post_breadcrumbs = driver.findElement(By.cssSelector("ul.p-breadcrumbs")).getText(); ArrayList<String> post_tags = new ArrayList<String>(); List<WebElement> tags = driver.findElements(By.cssSelector("div.additional-header__tags dl.tagList dd span.js-tagList a.tagItem")); for (WebElement tag : tags) { //System.out.println(tag.getText()); // Debugging purposes post_tags.add(tag.getText()); } // Set post data PublicVars.post.setPost(post_url, post_title, post_content, post_author, post_date, post_breadcrumbs, post_tags, PublicVars.index); JsonOps.writePostToJsonFile(PublicVars.post); PublicVars.index++; //PublicVars.post.printPost(PublicVars.post); // Debugging purposes // Add the post to the Post Array PublicVars.posts_array.add(PublicVars.post); System.out.println("Extracted content from URL: " + post_url); // Debugging purposes kill_driver(driver); } catch (TimeoutException e) { System.out.println("Page did not load within 8 seconds, skipping: " + post_url); } catch (Exception e) { System.out.println("Page did not load within the expected time, skipping: " + post_url + "\n"); System.out.println("Error while extracting data: " + e.getMessage()); } } /** * This method kills the crawler * @param driver The WebDriver object */ public static void kill_driver(WebDriver driver){ driver.quit(); System.out.println("\n\nThe driver is killed\n\n"); } /** * This method closes all the drivers that have somehow stayed open */ public static void closeAll() { for (WebDriver driver : PublicVars.drivers_list) { driver.quit(); } } }
import React, { useState } from 'react' import { Link, useNavigate } from 'react-router-dom'; import { postAdminLogin } from '../../../api/Requests/adminRequests/AdminRequests'; function AdminSigninPage() { const [email, setEmail] = useState('') const [password, setPassword] = useState('') const [errorMessage, setErrorMessage] = useState('') const navigate=useNavigate() const handleSubmit = async (e) => { e.preventDefault() try { if (!email) { setErrorMessage("Email is required"); } else if (!email.match(/^[A-Za-z0-9._-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/)) { setErrorMessage("Enter a valid email"); } else if (!password) { setErrorMessage("Password is required"); } else if (password.length < 4) { setErrorMessage("Password must be atleast 4 characters"); } else if (password.length > 20) { setErrorMessage("Password must be less than 20 characters"); } else { const { data } = await postAdminLogin({ email: email, password: password }) if (data) { if (data.user) { navigate("/admindashboard"); localStorage.setItem('admin', JSON.stringify(data.admin)) localStorage.setItem('admintoken',(data.admintoken)) } else { console.log(data.msg) setErrorMessage(data.msg) } }else{ console.log(data.msg) setErrorMessage('Something went wrong') } } } catch (error) { setErrorMessage('Something went wrong') console.log(error.message); } } return ( <div> <div className='bg-gray-100'> <div className='flex justify-center align-middle backgroundimage h-[100vh]'> <form className="rounded-md bg-white m-10 shadow-xl lg:w-1/3 p-10 border mt-20 text-green-400 border-gray-100 " onSubmit={handleSubmit}> <h1 className="text-2xl text-center font-bold lg:text-4xl">PDF Gallery</h1> <p className="pb-4 text-center text-gray-500 mb-10">Admin Login</p> {errorMessage && <div className="p-2 mb-2 text-sm text-red-700 bg-red-100 rounded-lg dark:bg-red-200 dark:text-red-800" role="alert">{errorMessage}</div>} <div className="mb-6"> <label className="text-black"> Email Address </label> <input type="email" value={email} onChange={(e)=> {setEmail(e.target.value)}} className="mt-2 h-10 w-full rounded-md bg-gray-100 px-3 outline-none focus:ring" /> </div> <div className="mb-6"> <label className="text-black"> Password </label> <input type="password" value={password} onChange={(e)=>{setPassword(e.target.value)}} className="mt-2 h-10 w-full rounded-md bg-gray-100 px-3 outline-none focus:ring" /> </div> <div className='flex justify-center'> <button className="mt-2 h-12 w-3/4 rounded-full bg-green-400 p-2 text-2xl text-center font-semibold text-white outline-none focus:ring">Login</button> </div> </form> </div> </div> </div> ) } export default AdminSigninPage
import { INestApplication } from '@nestjs/common'; import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; /** * Swagger 세팅 * @param {INestApplication} app */ export function setupSwagger(app: INestApplication): void { const options = new DocumentBuilder() .setTitle('NestJS Study API Docs') .setDescription('NestJS Study API description') .setVersion('1.0.0') .addTag('swagger') .addBearerAuth({ type: 'http', scheme: 'bearer', bearerFormat: "JWT", in: "header", }, 'accessToken' ) .build(); const document = SwaggerModule.createDocument(app, options); SwaggerModule.setup('/swagger/swagger-ui', app, document, { swaggerOptions: { //bearer token 유지 - 편의성 persistAuthorization: true } }); }
syntax = "proto3"; option go_package = ".;pb"; package pb; message ArticleRequest { int64 article_id = 1; } message ArticleResponse { int64 article_id = 1; string title = 2; string content = 3; string author = 4; string created_at = 5; } message ListArticlesRequest { int32 page = 1; int32 page_size = 2; } message ListArticlesResponse { repeated ArticleResponse articles = 1; } message CreateArticleRequest { string title = 1; string content = 2; string author = 3; } message CreateArticleResponse { int64 article_id = 1; } message UpdateArticleRequest { int64 article_id = 1; string title = 2; string content = 3; } message UpdateArticleResponse { int64 article_id = 1; } message DeleteArticleRequest { int64 article_id = 1; } message DeleteArticleResponse { bool success = 1; } service ArticleService { rpc GetArticle(ArticleRequest) returns (ArticleResponse); rpc ListArticles(ListArticlesRequest) returns (ListArticlesResponse); rpc CreateArticle(CreateArticleRequest) returns (CreateArticleResponse); rpc UpdateArticle(UpdateArticleRequest) returns (UpdateArticleResponse); rpc DeleteArticle(DeleteArticleRequest) returns (DeleteArticleResponse); }
<template> <div class="experience-wrapper"> <AddExperience :isExperienceDialog="addExperienceDialog" @close="dialogClose" @success="dialogSuccess" /> <div class="experience-management-container"> <div class="experience-management-header"> <div>Experiences</div> <v-btn @click="addExperienceDialog = true" class="btn-primary" ><v-icon>mdi-plus</v-icon> Add Experience</v-btn > </div> <div class="experience-management-table-wrapper"> <v-data-table :headers="experienceManagementHeader" :items="experienceManagementItems" class="global-table fixed-header" :hide-default-footer="true" item-key="id" fixed-header disable-pagination > <template v-slot:body.prepend> <tr class="experience-management-search-input-tr global-form"> <td> <v-text-field placeholder="Search" hide-details outlined :dense="true" v-model="searchById" color="#6F717E" append-icon="mdi-magnify" ></v-text-field> </td> <td> <v-text-field placeholder="Search" hide-details outlined :dense="true" v-model="searchByName" color="#6F717E" append-icon="mdi-magnify" ></v-text-field> </td> <td> <v-text-field placeholder="Search" hide-details outlined :dense="true" append-icon="mdi-magnify" color="#6F717E" v-model="searchByLocation" ></v-text-field> </td> <td> <v-select placeholder="Select Type" outlined hide-details :items="uniqueTypes" :dense="true" v-model="searchByType" ></v-select> </td> <td></td> <td> <v-select placeholder="Select Status" outlined hide-details :items="['Active', 'Closed']" :dense="true" v-model="searchByStatus" ></v-select> </td> <td> <v-text-field placeholder="Search" hide-details outlined :dense="true" v-model="searchByInterest" color="#6F717E" append-icon="mdi-magnify" ></v-text-field> </td> </tr> </template> <template v-slot:item.id="{ item }"> <router-link :to="{ name: ' ', params: { id: item.id } }">{{ item.id }}</router-link> </template> <template v-slot:item.status="{ item }"> <span class="tag" :class="item.status">{{ item.status }}</span> </template> <template v-slot:item.interest="{ item }"> <div class="tags-container"> <span v-for="(item, index) in item.interest" :key="index" class="tag" > {{ item }} </span> </div> </template> <template v-slot:item.ratings="{ item }"> <div class="rating-container"> <span><img src="../../assets/star.svg" /></span> <span>{{ item.ratings }}</span> </div> </template> <template v-slot:item.name="{ item }"> <div class="table-name"> <img :src="item.userAvatar" /> <div style="font-weight: bold">{{ item.name }}</div> </div> </template> </v-data-table> </div> </div> </div> </template> <script> import AddExperience from "@/components/AddExperience.vue"; export default { props: ["width"], components: { AddExperience }, data() { return { seletedTab: "personalDetails", addExperienceDialog: false, experienceManagementItems: [ { id: "#PR14253", name: "Champagne: home of Dom Pérignon", location: "Marne Valley, France", type: "Hotel", ratings: "4", status: "Active", interest: [ "Music", "Hotel", "Hillside", "Historical", "Photography", "Wine Making", ], userAvatar: require("../../assets/avatar.jpeg"), }, { id: "#PR1235", name: "Rocamadour: the sacred hilltop pilgrimage", location: "Occitanie region, France", type: "Venue", ratings: "2", status: "Active", interest: ["Park", "Stone House", "Castle", "Hill", "Photography"], userAvatar: require("../../assets/avatar.jpeg"), }, { id: "#PR2658", name: "Corsica: the island of beauty", location: "Corsica, France", type: "Island", ratings: "3", status: "Closed", interest: [ "Beaches", "Sunrise", "Adventure", "Villa", "Photography", "Resort", ], userAvatar: require("../../assets/avatar.jpeg"), }, { id: "#PR2658", name: "Corsica: the island of beauty", location: "Corsica, France", type: "Island", ratings: "3", status: "Closed", interest: [ "Beaches", "Sunrise", "Adventure", "Villa", "Photography", "Resort", ], userAvatar: require("../../assets/avatar.jpeg"), }, { id: "#PR2658", name: "Corsica: the island of beauty", location: "Corsica, France", type: "Island", ratings: "3", status: "Closed", interest: [ "Beaches", "Sunrise", "Adventure", "Villa", "Photography", "Resort", ], userAvatar: require("../../assets/avatar.jpeg"), }, { id: "#PR2658", name: "Corsica: the island of beauty", location: "Corsica, France", type: "Island", ratings: "3", status: "Closed", interest: [ "Beaches", "Sunrise", "Adventure", "Villa", "Photography", "Resort", ], userAvatar: require("../../assets/avatar.jpeg"), }, { id: "#PR2658", name: "Corsica: the island of beauty", location: "Corsica, France", type: "Island", ratings: "3", status: "Closed", interest: [ "Beaches", "Sunrise", "Adventure", "Villa", "Photography", "Resort", ], userAvatar: require("../../assets/avatar.jpeg"), }, { id: "#PR2658", name: "Corsica: the island of beauty", location: "Corsica, France", type: "Island", ratings: "3", status: "Closed", interest: [ "Beaches", "Sunrise", "Adventure", "Villa", "Photography", "Resort", ], userAvatar: require("../../assets/avatar.jpeg"), }, { id: "#PR0235", name: "Auvergne: the land that time forgot", location: "Pyrenees, France", type: "Hotel", ratings: "1", status: "Active", interest: [ "hey", "Music", "Hotel", "Hillside", "Historical", "Photography", "Wine Making", ], userAvatar: require("../../assets/avatar.jpeg"), }, ], searchById: "", searchByName: "", searchByLocation: "", searchByType: "", searchByStatus: "", searchByInterest: "", }; }, methods: { dialogSuccess() { alert("Experience added"); this.addExperienceDialog = false; }, dialogClose() { console.log("closed"); this.addExperienceDialog = false; }, }, computed: { uniqueTypes() { const types = this.experienceManagementItems.map((item) => item.type); return [...new Set(types)]; }, experienceManagementHeader() { return [ { text: "ID", value: "id", align: "center", filter: (val) => { return (val + "") .toLowerCase() .includes(this.searchById.toLowerCase()); }, }, { text: "Name", value: "name", filter: (val) => { return (val + "") .toLowerCase() .includes(this.searchByName.toLowerCase()); }, }, { text: "Location", value: "location", filter: (val) => { return (val + "") .toLowerCase() .includes(this.searchByLocation.toLowerCase()); }, }, { text: "Type", value: "type", filter: (val) => { return (val + "") .toLowerCase() .includes(this.searchByType.toLowerCase()); }, }, { text: "Ratings", value: "ratings", ratings: "cneter", }, { text: "Status", value: "status", align: "center", filter: (val) => { return (val + "") .toLowerCase() .includes(this.searchByStatus.toLowerCase()); }, }, { text: "Interest", value: "interest", filter: (val) => { return (val + "") .toLowerCase() .includes(this.searchByInterest.toLowerCase()); }, }, ]; }, }, }; </script> <style scoped> .experience-wrapper { flex: 1; overflow: auto; } .experience-management-container { background: white; padding: 1.5em; border-radius: .5em; height: 100%; display: flex; flex-direction: column; } .experience-management-header { display: flex; justify-content: space-between; } .experience-management-header div { font-size: 1.25rem; font-family: "Poppins-SemiBold"; } .experience-management-table-wrapper { margin-top: 2em; flex: 1; overflow: auto; } .experience-management-search-input-tr { background: #f9f9fe !important; } .rating-container { display: flex; align-items: center; justify-content: center; gap: 0.25em; } .rating-container span { display: flex; align-items: center; } .rating-container span img { width: 1.2em; pointer-events: none; user-select: none; } .tags-container { display: flex; flex-wrap: wrap; gap: 0.5em; } .table-name { display: flex; align-items: flex-start; gap: .5em; } .table-name img { width: 2.8em; border-radius: 0.5em; } </style>
import { describe, test } from '@jest/globals' import { CannotDereferenceTypeError, InvalidMemoryAccess } from '../errors/errors' import { testProgram } from '../interpreter/cInterpreter' import { ProgramType } from '../interpreter/typings' import { FLOAT_BASE_TYPE, incrementPointerDepth, INT_BASE_TYPE, } from '../interpreter/utils/typeUtils' import { intToBinary } from '../interpreter/utils/utils' import { expectLogOutputToBe, expectThrowError, verifyProgramCompleted } from '../utils/testing' describe('pointer', () => { test('pointer arithmetic', () => { const output = testProgram( ` int main() { int a, b, c, d, e; a = 21; int* f = &a + 2; *f = 4; *(f + 1) = 5 + *(f - 2); printfLog(a, b, c, d, e, f); return 0; } `, ) verifyProgramCompleted(output) const logOutput = output.getLogOutput() const expectedLogOutput = [ { binary: intToBinary(21), type: INT_BASE_TYPE }, { binary: intToBinary(0), type: INT_BASE_TYPE }, { binary: intToBinary(4), type: INT_BASE_TYPE }, { binary: intToBinary(26), type: INT_BASE_TYPE }, // Might need to change address if structure changes { binary: intToBinary(0), type: INT_BASE_TYPE }, { binary: intToBinary(3), type: incrementPointerDepth(INT_BASE_TYPE) }, ] expectLogOutputToBe(logOutput, expectedLogOutput) }) test('pointer unary arithmetic', () => { const output = testProgram( ` int main() { int a[2], b = 2, c = 3, d = 4, e = 5; int (*f)[2] = &a; int (*g)[2] = f++; printfLog(f, g); return 0; } `, ) verifyProgramCompleted(output) const logOutput = output.getLogOutput() const intArrayType: ProgramType = [ { subtype: 'Pointer', pointerDepth: 1 }, { subtype: 'Array', size: 2 }, { subtype: 'BaseType', baseType: 'int' }, ] const expectedLogOutput = [ { binary: intToBinary(3), type: intArrayType }, { binary: intToBinary(1), type: intArrayType }, ] expectLogOutputToBe(logOutput, expectedLogOutput) }) test('nested pointers', () => { const output = testProgram( ` int main() { int a = 2, *b = &a, **c = &b, ***d = &c, ****e = &d; printfLog(a, *b, **c, ***d, ****e); a = 3; printfLog(a, *b, **c, ***d, ****e); return 0; } `, ) verifyProgramCompleted(output) const logOutput = output.getLogOutput() const expectedLogOutput = [ { binary: intToBinary(2), type: INT_BASE_TYPE }, { binary: intToBinary(2), type: INT_BASE_TYPE }, { binary: intToBinary(2), type: INT_BASE_TYPE }, { binary: intToBinary(2), type: INT_BASE_TYPE }, { binary: intToBinary(2), type: INT_BASE_TYPE }, { binary: intToBinary(3), type: INT_BASE_TYPE }, { binary: intToBinary(3), type: INT_BASE_TYPE }, { binary: intToBinary(3), type: INT_BASE_TYPE }, { binary: intToBinary(3), type: INT_BASE_TYPE }, { binary: intToBinary(3), type: INT_BASE_TYPE }, ] expectLogOutputToBe(logOutput, expectedLogOutput) }) test('unary address', () => { const output = testProgram( ` int main() { int x = -10; int* a = &x; int b = *a + 1; float c = *a + 2; printfLog(x, a, b, c); return 0; } `, ) verifyProgramCompleted(output) const logOutput = output.getLogOutput() const expectedLogOutput = [ { binary: intToBinary(-10), type: INT_BASE_TYPE }, { binary: intToBinary(1), type: incrementPointerDepth(INT_BASE_TYPE) }, // Might need to change address if structure changes { binary: intToBinary(-9), type: INT_BASE_TYPE }, { binary: -8, type: FLOAT_BASE_TYPE }, ] expectLogOutputToBe(logOutput, expectedLogOutput) }) test('unary address dereference constant', () => { const output = testProgram( ` int main() { int a = 2; int* b = 1; float c = *b; printfLog(a, b, c); return 0; } `, ) verifyProgramCompleted(output) const logOutput = output.getLogOutput() const expectedLogOutput = [ { binary: intToBinary(2), type: INT_BASE_TYPE }, { binary: intToBinary(1), type: incrementPointerDepth(INT_BASE_TYPE) }, { binary: 2, type: FLOAT_BASE_TYPE }, // Might need to change address if structure changes ] expectLogOutputToBe(logOutput, expectedLogOutput) }) test('unary address dereference invalid address', () => { const program = () => testProgram( ` int main() { int* a = 5; float c = *a; printfLog(a, c); return 0; } `, ) expectThrowError(program, InvalidMemoryAccess, `Invalid memory access to 5.`) }) test('unary address dereference literal', () => { const program = () => testProgram( ` int main() { int* a = &5; printfLog(a); return 0; } `, ) expectThrowError( program, CannotDereferenceTypeError, 'Cannot dereference non-address of type "Literal".', ) }) test('function pointer', () => { const output = testProgram( ` void fun(int a) { printfLog(a); return; } int main() { void (*a)(int) = &fun; (*a)(10); return 0; } `, ) verifyProgramCompleted(output) const logOutput = output.getLogOutput() const expectedLogOutput = [{ binary: intToBinary(10), type: INT_BASE_TYPE }] expectLogOutputToBe(logOutput, expectedLogOutput) }) })
package tpjad.tpjad.beans; import jakarta.ejb.EJB; import jakarta.enterprise.context.RequestScoped; import jakarta.faces.application.FacesMessage; import jakarta.faces.context.FacesContext; import jakarta.inject.Named; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; import tpjad.tpjad.dtos.UserDTO; import jakarta.persistence.NoResultException; import jakarta.persistence.Query; @Named @RequestScoped public class SignupBean { private String password; private String confirmPassword; private String name; private String email; private String phone; private String address; @PersistenceContext(unitName = "Store") private EntityManager entityManager; @EJB private UserServiceEJB userEJB; public String getConfirmPassword() { return confirmPassword; } public void setConfirmPassword(String confirmPassword) { this.confirmPassword = confirmPassword; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } 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 String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String register() { StringBuilder jsScript = new StringBuilder(); if (password == null || password.length() < 8) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Password is too short. It must be at least 8 characters long.", null)); } if (!password.equals(confirmPassword)) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Passwords do not match!", null)); return null; } if (emailExists(email)) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Email already registered.", null)); return null; } if (jsScript.length() > 0) { FacesContext.getCurrentInstance().getExternalContext().getRequestMap().put("jsScript", jsScript.toString()); return null; } UserDTO userDTO = new UserDTO(password, name, email, phone, address); try { userEJB.createUser(userDTO); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Registration Successful!", null)); return "signup"; } catch (Exception e) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Registration failed: " + e.getMessage(), null)); return null; } } private boolean emailExists(String email) { try { Query query = entityManager.createQuery("SELECT u FROM User u WHERE u.email = :email"); query.setParameter("email", email); query.getSingleResult(); return true; } catch (NoResultException e) { return false; } } }
package com.xiafei.rpc.server.center; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Method; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.HashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * <P>Description: . </P> * <P>CALLED BY: 齐霞飞 </P> * <P>UPDATE BY: 齐霞飞 </P> * <P>CREATE DATE: 2018/5/31</P> * <P>UPDATE DATE: 2018/5/31</P> * * @author qixiafei * @version 1.0 * @since java 1.8.0 */ public class ServerImpl implements Server { private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); /** * 服务注册池. */ private static final HashMap<String, Class> serviceRegistry = new HashMap<>(); /** * 运行状态. */ private static boolean isRunning = false; /** * 端口号. */ private static int port; public ServerImpl(int port) { this.port = port; } public void stop() { isRunning = false; executor.shutdown(); } public void start() throws IOException { ServerSocket server = new ServerSocket(); server.bind(new InetSocketAddress(port)); System.out.println("start server"); try { while (true) { // 1.监听客户端的TCP连接,接到TCP连接后将其封装成task,由线程池执行 executor.execute(new ServiceTask(server.accept())); } } finally { server.close(); } } public void register(Class serviceInterface, Class impl) { serviceRegistry.put(serviceInterface.getName(), impl); } public boolean isRunning() { return isRunning; } public int getPort() { return port; } private static class ServiceTask implements Runnable { Socket clent = null; public ServiceTask(Socket client) { this.clent = client; } public void run() { ObjectInputStream input = null; ObjectOutputStream output = null; try { // 2.将客户端发送的码流反序列化成对象,反射调用服务实现者,获取执行结果 input = new ObjectInputStream(clent.getInputStream()); final String serviceName = input.readUTF(); final String methodName = input.readUTF(); final Class<?>[] parameterTypes = (Class<?>[]) input.readObject(); final Object[] arguments = (Object[]) input.readObject(); final Class serviceClass = serviceRegistry.get(serviceName); if (serviceClass == null) { throw new ClassNotFoundException(serviceName + " not found"); } final Method method = serviceClass.getMethod(methodName, parameterTypes); final Object result = method.invoke(serviceClass.newInstance(), arguments); // 3.将执行结果反序列化,通过socket发送给客户端 output = new ObjectOutputStream(clent.getOutputStream()); output.writeObject(result); } catch (Exception e) { e.printStackTrace(); } finally { if (output != null) { try { output.close(); } catch (IOException e) { e.printStackTrace(); } } if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } if (clent != null) { try { clent.close(); } catch (IOException e) { e.printStackTrace(); } } } } } }
import { ApplicationConfig } from '@angular/core' import { provideRouter } from '@angular/router' import { routes } from './app.routes' import { provideClientHydration } from '@angular/platform-browser' import { provideHttpClient, withInterceptors } from '@angular/common/http' import { authHttpInterceptorFn, provideAuth0 } from '@auth0/auth0-angular' import { environment } from '../environment/environment' import { provideAnimationsAsync } from '@angular/platform-browser/animations/async' import { provideMarkdown } from 'ngx-markdown' import { provideToastr } from 'ngx-toastr' export const appConfig: ApplicationConfig = { providers: [ provideRouter(routes), provideClientHydration(), provideHttpClient(withInterceptors([authHttpInterceptorFn])), provideAuth0({ ...environment.auth, httpInterceptor: { ...environment.httpInterceptor } }), provideAnimationsAsync(), provideMarkdown(), provideToastr() ] }
import React from 'react' import ReactDOM from 'react-dom/client' import './index.css' import { RouterProvider, createBrowserRouter } from 'react-router-dom' import Menu from './pages/Menu/Menu.tsx' import Cart from './pages/Cart/Cart.tsx' import Home from './layout/Home/Home.tsx' import Product from './pages/Product/Product.tsx' import Auth from './layout/auth/Auth.tsx' import Login from './pages/Login/Login.tsx' import Register from './pages/Register/Register.tsx' // import axios from 'axios' // import { url } from './helpers/Api.ts' const router = createBrowserRouter([ { path:"/", element:<Home/>, children:[ { path:'/', element:<Menu/> }, { path:"/cart", element:<Cart/> }, { path:"/product/:id", element:<Product/>, // loader:async({params})=>{ // let res = await axios.get(`${url}/products/${params.id}`) // return res // } // loader:()=>{ // return 10 // } }, ] } , { path:"/auth", element:<Auth/>, children:[ { path:"login", element:<Login/> }, { path:"register", element:<Register/> } ] } ]) ReactDOM.createRoot(document.getElementById('root')!).render( <React.StrictMode> <RouterProvider router={router}/> </React.StrictMode>, )
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/wait.h> int main(int argc, char **argv) { if (argc != 2) { fprintf(stderr, "Usage: forkloop <iterations>\n"); exit(1); } int iterations = strtol(argv[1], NULL, 10); int status; for (int i = 0; i < iterations; i++) { int n = fork(); if (n < 0) { perror("fork"); exit(1); } else if (n > 0) { // Parent process printf("ppid = %d, pid = %d, i = %d\n", getppid(), getpid(), i); wait(&status); // Parent waits for child to complete break; // Parent exits the loop after child completes } else { // Child process: will potentially create another process printf("ppid = %d, pid = %d, i = %d\n", getppid(), getpid(), i); // Child does not wait, potentially continues to the next iteration of the loop } } return 0; }
import React, { useState } from 'react'; import axios from 'axios'; function Deposit() { const [asset, setAsset] = useState('SOL'); const [amount, setAmount] = useState(); const [depositAddress, setDepositAddress] = useState(null); const handleAssetChange = (event) => { setAsset(event.target.value); }; const handleAmountChange = (event) => { setAmount(event.target.value); }; const handleDeposit = async () => { if (!amount) { return alert('Please enter a deposit amount'); } // ... (Replace with your Fireblocks NCW API call to get deposit address) const response = await axios.post( 'https://your-fireblocks-api/vault/wallet/<walletId>/addresses', { asset, amount } ); setDepositAddress(response.data.address); }; return ( <div id="deposit" style={styles.container} > <h2 style={{color:'#1bf588'}}>Deposit</h2> <select value={asset} onChange={handleAssetChange} style={styles.dropDown}> <option value="SOL">SOL</option> <option value="BTC">BTC</option> </select> <div> <input type="number" id="deposit-amount" placeholder="Enter amount" value={amount} onChange={handleAmountChange} style={styles.inputfield}/> <button onClick={handleDeposit} style={styles.deposit} >Deposit</button> </div> {depositAddress && ( <p>Deposit Address: {depositAddress}</p> )} </div> ); } const styles = { container:{ backgroundColor:'#363636', width:'100%', padding:'20px', margin:'30px', height:'300px', display:'flex', flexDirection:'column', alignItems:'center', borderRadius:'20px' }, dropDown:{ margin:'20px', padding:'10px', backgroundColor: '#B3B3B3', color: 'black', border:'2px solid #B3B3B3', borderRadius:'10px', fontWeight:'bold', }, deposit:{ padding:'10px', backgroundColor: '#363636', color: '#B3B3B3', border:'2px solid #B3B3B3', borderRadius:'10px', fontWeight:'bold', cursor:'pointer', }, inputfield:{ margin:'20px' , padding:'10px', backgroundColor: '#363636', color: '#B3B3B3', border:'2px solid #B3B3B3', borderRadius:'10px' , '::placeholder': { color: 'white', } }, } export default Deposit;
%% rgb2yuv % 1. matrix: [a,b,c] = [a b c] % matrix: [a;b;c] = [a b c]' % % 2. zeros: create an array of 0 % zeros(3) = [ 0 0 0 % 0 0 0 % 0 0 0 ] % zeros(2,5) = [ 0 0 0 0 0 % 0 0 0 0 0 ] % data type of zeros() is preset "double". % To use other data type such as 'uint8' => zeros(2,5,'uint8') % show the result on command window to help yourself understand %% data type % 1. data type of RGB channel is preset "uint8", range 0-255 % assume that Y = R+G+B; if R+G+B > 255, Y will be assigned the maximum 255, % so we need to calculate in data type "double" using im2double() %% function % input---source image: I % output---image in YUV: I_yuv function I_yuv = rgb2yuv(I) % Convert from [0, 255] to [0, 1] (uint8 to double) I = im2double(I); % RGB channel R = I(:, :, 1); G = I(:, :, 2); B = I(:, :, 3); % get height, width, channel of the image [height, width, channel] = size(I); % initial the intensity array Y using zeros() Y = zeros(height, width); U = zeros(height, width); V = zeros(height, width); % weight of RGB channel matrix = [0.299 0.587 0.114; -0.169 -0.331 0.5; 0.5 -0.419 -0.081]; % The range is scaled to [0, 1], so scale 128 to 128/255 as well offset = [0 128/255 128/255]'; % implement the rgb to yuv convertion %%% your code here YUV=matrix*[reshape(R,1,[]);reshape(G,1,[]);reshape(B,1,[])]+offset; Y=reshape(YUV(1,:),[height width]); U=reshape(YUV(2,:),[height width]); V=reshape(YUV(3,:),[height width]); % save YUV to output image I_yuv(:, :, 1) = Y; I_yuv(:, :, 2) = U; I_yuv(:, :, 3) = V; end
import { useDispatch, useSelector } from "react-redux"; import Sidebar from "./Sidebar" import { Fragment, useEffect, useState } from "react" import { useParams } from "react-router-dom"; import { getProduct, updateProduct } from "../../actions/productAction"; import { clearProductUpdated } from "../../slices/productSlice"; import { toast } from 'react-toastify' import { clearError } from "../../slices/productSlice"; export default function UpdateProduct() { const [name, setName] = useState(""); const [price, setPrice] = useState(""); const [description, setDescription] = useState(""); const [category, setCategory] = useState(""); const [stock, setStock] = useState(0); const { loading, isProductUpdated, error, product=[] } = useSelector((state) => state.productState); const categories = [ 'Phone ', 'Laptops', 'Watch', 'EarPhones', 'accessories' ]; const dispatch = useDispatch(); const { id: productId } = useParams(); const submitHandler = (e) => { e.preventDefault(); const formData = new FormData(); formData.append('name', name); formData.append('price', price); formData.append('description', description); formData.append('stock', stock); formData.append('category', category); dispatch(updateProduct(productId, formData)) } useEffect(() => { if (isProductUpdated) { toast('Product Updated Successfully', { type: 'success', position: toast.POSITION.BOTTOM_CENTER, onOpen: () => dispatch(clearProductUpdated()) }); } if (error) { toast(error, { position: toast.POSITION.BOTTOM_CENTER, type: 'error', onOpen: () => { dispatch(clearError()); } }); return; } dispatch(getProduct(productId)) }, [isProductUpdated, error, dispatch, productId]); useEffect(() => { if (product._id) { setName(product.name); setPrice(product.price); setDescription(product.description); setStock(product.stock); setCategory(product.category); } }, [product]) return ( <div className="row"> <div className="col-12 col-md-2"> <Sidebar /> </div> <div className="col-12 col-md-10"> <Fragment> <div className="wrapper my-5"> <form onSubmit={submitHandler} className="shadow-lg" encType='multipart/form-data'> <h1 className="mb-4">Update Product</h1> <div className="form-group"> <label htmlFor="name_field">Name</label> <input type="text" id="name_field" className="form-control" onChange={e => setName(e.target.value)} value={name} /> </div> <div className="form-group"> <label htmlFor="price_field">Price</label> <input type="text" id="price_field" className="form-control" onChange={e => setPrice(e.target.value)} value={price} /> </div> <div className="form-group"> <label htmlFor="description_field">Description</label> <textarea className="form-control" id="description_field" rows="8" onChange={e => setDescription(e.target.value)} value={description} ></textarea> </div> <div className="form-group"> <label htmlFor="category_field">Category</label> <select value={category} onChange={e => setCategory(e.target.value)} className="form-control" id="category_field"> <option value=""> Select</option> {categories.map(category => ( <option key={category} value={category}>{category}</option> ))} </select> </div> <div className="form-group"> <label htmlFor="stock_field">Stock</label> <input type="number" id="stock_field" className="form-control" onChange={e => setStock(e.target.value)} value={stock} /> </div> <button id="login_button" type="submit" disabled={loading} className="btn btn-block py-3" > UPDATE </button> </form> </div> </Fragment> </div> </div> ) }
<template> <v-app id="inspire"> <v-navigation-drawer v-model="drawer" app clipped class="main_navigation" style="background-color: #d2d2ff" width="17%" > <v-list nav dense> <div v-for="m in modulosVisibles" :key="m.name"> <v-list-group v-if="m.childs && m.childs.length > 0"> <template v-slot:activator> <v-list-item-action> <img v-bind:src="m.icon" height="35" width="35" /> </v-list-item-action> <v-list-item-title>{{ m.title }}</v-list-item-title> </template> <v-list dense> <v-list-item v-for="(child, i) in m.childs" :key="i" @click="go(child.name)" :class=" child.name == nameRouter ? 'v-list-item--active primary--text' : '' " > <v-list-item-action> <v-icon size="12">mdi-checkbox-blank-circle</v-icon> </v-list-item-action> <v-list-item-title v-text="child.title"></v-list-item-title> </v-list-item> </v-list> </v-list-group> <v-list-item v-if="!m.childs" :key="m.name" @click="go(m.name)"> <v-list-item-action> <v-icon>{{ m.icon }}</v-icon> </v-list-item-action> <v-list-item-content> <v-list-item-title>{{ m.title }}</v-list-item-title> </v-list-item-content> </v-list-item> </div> </v-list> </v-navigation-drawer> <v-app-bar app color="primary" dark clipped-left fixed> <v-app-bar-nav-icon @click.stop="drawer = !drawer" /> <v-spacer></v-spacer> <form @submit.prevent="changeUserData()" v-if="logued" class="d-flex mt-5" > <v-autocomplete :items="sucursales" v-model="loguedUser.sucursal" item-text="nombre" :return-object="true" @change="getSalesPoint(loguedUser.sucursal)" /> <v-autocomplete :items="salesPoint" v-model="loguedUser.puntoVenta" item-text="nombre" :return-object="true" class="ml-2" /> <v-btn type="submit" class="ml-2" outlined>APLICAR</v-btn> </form> <v-spacer /> <v-menu offset-y> <template v-slot:activator="{ on }"> <a ><img src="/../../images/icons/perfil.svg" v-on="on" height="50" width="50" style="border-radius: 50% 50% 50% 50%; border: solid 2px #E7ECED;" /></a> </template> <v-card class="mx-auto" max-width="344" outlined> <v-list-item three-line> <v-list-item-content v-if="user"> <v-list-item-title class="headline mb-1">{{ user.nombre }}</v-list-item-title> <v-list-item-subtitle>{{ user.username }}</v-list-item-subtitle> <v-list-item-subtitle>{{ user.perfil.nombre }}</v-list-item-subtitle> </v-list-item-content> </v-list-item> <v-card-actions> <v-btn text @click="logout()">Cerrar sesión</v-btn> </v-card-actions> </v-card> </v-menu> </v-app-bar> <v-main> <v-container fluid class="root-container"> <Home v-if="$route.name === 'root'" /> <router-view v-if="$route.name !== 'root'" /> </v-container> </v-main> </v-app> </template> <script> import axios from "axios"; import Home from "./Home"; export default { props: { source: String, }, data: () => ({ mini: true, user: null, logued: false, tenant: "", drawer: null, token: localStorage.getItem("token"), loguedUser: {}, salesPoint: [], nameRouter: "", modulos: [ { name: "ventas", title: "Ventas", visible: false, icon: "/../images/icons/sale.svg", childs: [ { path: "/ventasfast", name: "ventasfast", title: "Ventas Rápidas", visible: false, }, { path: "/ventas", name: "ventasForm", title: "Generar Venta", visible: false, }, { path: "/ventas/list", name: "ventas", title: "Lista", visible: false, }, { path: "/ventas/presupuesto", name: "presupuesto", title: "Presupuesto", visible: false, }, { path: "/ventas/devoluciones", name: "devoluciones", title: "Devoluciones", visible: false, }, { path: "/ventas/cierrez", name: "Cierrez", title: "Cierrez", visible: false, }, { path: "/caja", name: "caja", title: "Caja", visible: false, }, ], }, { name: "productos", title: "Productos", visible: false, icon: "/../images/icons/products.svg", childs: [ { path: "/productos", name: "productos", title: "Lista", visible: false, }, { path: "/marcas", name: "marcas", title: "Marcas", visible: false, }, { path: "/rubros", name: "rubros", title: "Rubros", visible: false, }, { path: "/atributos", name: "atributos", title: "Atributos", visible: false, }, { path: "/propiedades", name: "propiedades", title: "Propiedades", visible: false, }, { path: "/depositos", name: "depositos", title: "Depositos", visible: false, }, { path: "/stock", name: "stock", title: "Stock", visible: false, }, ], }, { name: "documentos", title: "Doc. Comerciales", visible: false, icon: "/../images/icons/commercial_documents.svg", childs: [ { path: "/documentos_comerciales", name: "documentos", title: "Lista", visible: false, }, ], }, { name: "mediosPago", title: "Medios de Pago", visible: false, icon: "/../images/icons/payment_methods.svg", childs: [ { path: "/medios_de_pago", name: "mediosPago", title: "Medios de pago", visible: false, }, { path: "/planes_de_pago", name: "planesPago", title: "Planes de pago", visible: false, }, ], }, { name: "personas", title: "Personas", visible: false, icon: "/../images/icons/people.svg", childs: [ { path: "/clientes", name: "clientes", title: "Clientes", visible: false, }, { path: "/vendedores", name: "vendedores", title: "Vendedores", visible: false, }, { path: "/distribuidores", name: "distribuidores", title: "Proveedores", visible: false, }, { path: "/transportistas", name: "transportistas", title: "Transportistas", visible: false, },{ path: "/cuentascorrientes", name: "cuentascorrientes", title: "Cuentas Corrientes", visible: false, }, ], }, { name: "relaciones", title: "Relaciones", visible: false, icon: "/../images/icons/relations.svg", childs: [ { path: "/condiciones_fiscales", name: "condicionesFiscales", title: "Cond. Fiscal", visible: false, }, ], }, { name: "usuarios", title: "Usuarios", visible: false, icon: "/../images/icons/users.svg", childs: [ { path: "/usuarios", name: "usuarios", title: "Lista", visible: false, }, { path: "/perfiles", name: "perfiles", title: "Perfiles", visible: false, }, ], }, { name: "configuraciones", title: "Configuraciones", visible: false, icon: "/../images/icons/settings.svg", childs: [ { path:"/ventasfastconfiguracion", name:"ventasfastconfiguracion", title:"Ventas rapidas configuracion", visible:false }, { path: "/empresa", name: "empresas", title: "Empresa", visible: false, }, { path: "/sucursales", name: "sucursales", title: "Sucursales", visible: false, }, { path: "/puntos_venta", name: "puntosVenta", title: "Puntos de venta", visible: false, }, { path: "/modulos", name: "modulos", title: "Modulos", visible: false, }, { path: "/ivas", name: "ivas", title: "Ivas", visible: false, }, { path: "/impresora", name: "impresoras", title: "Impresoras", visible: false, }, { path: "/ventasfastconfiguracion", name: "ventasfastconfiguracion", title: "Ventas Rapidas", visible: false, }, ], }, { name: "soporte", title: "Soporte", visible: false, icon: "/../images/icons/support.svg", childs: [ { path: "/preguntas_frecuentes", name: "preguntasFrecuentes", title: "Preguntas Frecuentes", visible: false, }, { path: "/manuales", name: "manuales", title: "Manuales y contacto", visible: false, }, { path: "/mensajes", name: "mensajes", title: "Mensajes", visible: false, }, ], }, { name: "libroivaventas", title: "Libros", visible: false, icon: "/../images/icons/libro.svg", childs: [ { path: "/libroivaventas", name: "libroivaventas", title: "LibroIvaVentas", visible: false, }, ], }, { name: "calendar", title: "Calendar", visible: false, icon: "/../images/icons/calendar.svg", childs: [ { path: "/calendar", name: "calendar", title: "Calendar", visible: false, }, ], }, ], modulosVisibles: [], }), mounted() { this.tenant = this.$route.params.tenant; this.getUser(); }, components: { Home, }, methods: { go(to) { if (this.$router.currentRoute.name !== to) this.$router.push({ name: to }); this.nameRouter = to; }, logout() { localStorage.clear(); this.go(`login`); }, getUser() { axios .get( `${process.env.VUE_APP_SERVER}/${this.tenant}/api/usuarios/getLogued`, { headers: { Authorization: "Bearer " + this.token }, } ) .then((response) => { this.user = response.data; if (this.user.perfil.id == 2) { setTimeout(() => { this.loguedUser = JSON.parse(localStorage.getItem("userData")); this.sucursales = this.loguedUser.empresa.sucursales; this.logued = true; }, 1500); } this.modulos.forEach((m) => { this.user.perfil.modulos.forEach((modulo) => { if (m.name == modulo.nombre) { var mod = { name: m.name, title: m.title, childs: [], icon: m.icon, }; if (m.childs.length > 0) { m.childs.forEach((child) => { this.user.perfil.modulos.forEach((modulo2) => { if (child.name == modulo2.nombre) { mod.childs.push(child); } }); }); } this.modulosVisibles.push(mod); } }); }); }) .catch(() => { this.logout(); }); }, getSalesPoint() { this.salesPoint = this.loguedUser.sucursal.puntosVenta; }, changeUserData() { localStorage.setItem("userData", JSON.stringify(this.loguedUser)); this.$successAlert("Cambios aplicados") .then(() => { location.reload(); }) .catch((err) => { console.log(err); }); }, }, }; </script>
import React, { useState } from "react"; import { BrowserRouter as Router, Route, Routes } from "react-router-dom"; // Use Routes instead of Switch for react-router-dom v6 import OpeningScreen from "./components/OpeningScreen/OpeningScreen"; import HomeScreen from "./components/HomeScreen/HomeScreen"; import ListDetail from "./components/ListDetailScreen/ListDetail"; import GroupScreen from "./components/GroupScreen/GroupScreen"; import GroupDetails from "./components/GroupDetails/GroupDetails"; import DiscountsScreen from "./components/DiscountsScreen/DiscountsScreen"; import UserProfile from "./components/UserProfile/UserProfile"; import "./App.css"; import Deals from "./components/DealsPage/Deals"; function App() { const [isLoggedIn, setLoggedIn] = useState(false); const handleLogin = () => { setLoggedIn(true); }; const handleLogout = () => { setLoggedIn(false); }; const [lists, setLists] = useState([ // ... pre-populated lists { name: "List A", items: [ { name: "Milk", store: "Click to Add", price: "Click to Add" }, { name: "Bread", store: "Click to Add", price: "Click to Add" }, // { name: "Apples", price: "0.99" }, // { name: "Chicken", price: "5.49" }, // { name: "Rice", price: "1.89" }, // { name: "Tomatoes", price: "2.30" }, ], }, { name: "List B", items: [ { name: "Eggs", store: "Click to Add", price: "Click to Add" }, { name: "Orange Juice", store: "Click to Add", price: "Click to Add" }, { name: "Lettuce", store: "Click to Add", price: "Click to Add" }, // { name: "Pasta", price: "1.25" }, // { name: "Coffee", price: "6.99" }, // { name: "Butter", price: "3.59" }, ], }, { name: "List C", items: [ { name: "Cheese", store: "Click to Add", price: "Click to Add" }, // { name: "Potatoes", price: "3.20" }, // { name: "Carrots", price: "1.10" }, // { name: "Beef", price: "5.99" }, // { name: "Fish", price: "7.49" }, // { name: "Spinach", price: "3.00" }, ], }, ]); // Mock data for lists, replace with real data as needed const deals = [ { itemName: "Milk", deals: [ { store: "Food Basics", price: "4.20", quantity: "4L" }, { store: "Walmart", price: "4.50", quantity: "4L" }, { store: "No Frills", price: "4.60", quantity: "4L" }, { store: "Walmart", price: "2.50", quantity: "2L" }, ], }, { itemName: "Bread", deals: [ { store: "Metro", price: "2.99", quantity: "1 loaf" }, { store: "Loblaws", price: "2.79", quantity: "1 loaf" }, { store: "FreshCo", price: "1.99", quantity: "1 loaf" }, ], }, { itemName: "Apples", deals: [ { store: "Farmers Market", price: "3.00", quantity: "1lb" }, { store: "Kroger", price: "2.50", quantity: "1lb" }, { store: "Whole Foods", price: "3.50", quantity: "1lb" }, ], }, { itemName: "Chicken", deals: [ { store: "Costco", price: "10.00", quantity: "5lb" }, { store: "Safeway", price: "9.50", quantity: "5lb" }, { store: "Trader Joe's", price: "11.00", quantity: "5lb" }, ], }, { itemName: "Rice", deals: [ { store: "Asian Market", price: "15.99", quantity: "10lb" }, { store: "Walmart", price: "14.99", quantity: "10lb" }, { store: "Target", price: "16.99", quantity: "10lb" }, ], }, { itemName: "Tomatoes", deals: [ { store: "Local Farm", price: "1.50", quantity: "1lb" }, { store: "Loblaws", price: "1.75", quantity: "1lb" }, { store: "Metro", price: "1.60", quantity: "1lb" }, ], }, // ...you can add other deals if needed { itemName: "Eggs", deals: [ { store: "Food Basics", price: "2.99", quantity: "12pcs" }, { store: "Walmart", price: "2.79", quantity: "12pcs" }, { store: "Farmers Market", price: "3.50", quantity: "12pcs" }, { store: "Costco", price: "5.00", quantity: "24pcs" }, ], }, { itemName: "Orange Juice", deals: [ { store: "Trader Joe's", price: "3.99", quantity: "1L" }, { store: "Safeway", price: "4.50", quantity: "1L" }, { store: "Walmart", price: "3.50", quantity: "1L" }, { store: "Whole Foods", price: "5.00", quantity: "1L" }, ], }, { itemName: "Cheese", deals: [ { store: "Kroger", price: "4.00", quantity: "500g" }, { store: "Aldi", price: "3.75", quantity: "500g" }, { store: "Publix", price: "4.50", quantity: "500g" }, { store: "Walmart", price: "3.90", quantity: "500g" }, ], }, ]; const addItemToList = (itemName, listName, price, store) => { setLists((currentLists) => { const listIndex = currentLists.findIndex( (list) => list.name === listName ); if (listIndex > -1) { // Find the index of the item if it already exists in the list const itemIndex = currentLists[listIndex].items.findIndex( (item) => item.name === itemName ); const newLists = [...currentLists]; // Clone the current lists array for immutability let newItems = [...newLists[listIndex].items]; // Clone the items array within the selected list if (itemIndex > -1) { // If the item exists, update its price and store newItems[itemIndex] = { ...newItems[itemIndex], price, store }; } else { // If the item doesn't exist, add the new item newItems = [...newItems, { name: itemName, price, store }]; } // Update the items array for the selected list newLists[listIndex].items = newItems; return newLists; } return currentLists; }); }; const groups = [ { name: "House", members: 5, lists: [ "List A", "List B" ] }, { name: "Room B", members: 4, lists: [ "List A" ] }, { name: "Club Team", members: 10, lists: [ "List C" ] } ] return ( <Router> <div className="App"> <Routes> {" "} {/* Changed from Switch to Routes */} <Route path="/" element={ isLoggedIn ? ( <HomeScreen /> ) : ( <OpeningScreen onLogin={handleLogin} /> ) } /> <Route path="/home" element={ isLoggedIn ? ( <HomeScreen /> ) : ( <OpeningScreen onLogin={handleLogin} /> ) } /> <Route path="/list/:listName" element={ isLoggedIn ? ( <ListDetail lists={lists} /> ) : ( <OpeningScreen onLogin={handleLogin} /> ) } /> <Route path="/list/:listName/deals/:itemName" element={ isLoggedIn ? ( <Deals deals={deals} addItemToList={addItemToList} /> ) : ( <OpeningScreen onLogin={handleLogin} /> ) } /> <Route path="/groups" element={ isLoggedIn ? ( <GroupScreen groups={groups} lists={lists} /> ) : ( <OpeningScreen onLogin={handleLogin} /> ) } /> <Route path="/groupDetails/:groupName" element={ isLoggedIn ? ( <GroupDetails groups={groups} lists={lists} /> ) : ( <OpeningScreen onLogin={handleLogin} /> ) } /> <Route path="/discounts" element={ isLoggedIn ? ( <DiscountsScreen /> ) : ( <OpeningScreen onLogin={handleLogin} /> ) } /> <Route path="/user" element={ isLoggedIn ? ( <UserProfile onLogout={handleLogout} /> ) : ( <OpeningScreen onLogin={handleLogin} /> ) } /> </Routes> </div> </Router> ); } export default App;
import winston, { format } from "winston"; import config from "../config/config.js"; const customLevelsOptions = { levels: { fatal: 0, error: 1, warning: 2, info: 3, http: 4, debug: 5, }, customColors: { fatal: 'bold red', error: 'red', warning: 'yellow', info: 'green', http: 'white', debug: 'blue', } } const prodLogger = winston.createLogger({ levels: customLevelsOptions.levels, format:format.combine( format.colorize({colors:customLevelsOptions.customColors}), format.printf((info)=>`${info.level}: ${info.message}`) ), transports:[ new winston.transports.Console({level:"info"}), new winston.transports.File({ filename: './errors.log', level:"info"}) ] }) const devLogger = winston.createLogger({ levels: customLevelsOptions.levels, transports: [ new winston.transports.Console({ level: "http" , format:format.combine( format.colorize({colors:customLevelsOptions.customColors}), format.printf((info)=>`${info.level}: ${info.message}`) ), }), new winston.transports.File({ filename: './errors.log', level: 'warning' }) ] }) let logger; if (config.environment === "production") { logger = prodLogger } else { logger = devLogger } export const addLogger = (req, res, next) => { req.logger = logger; const logLevel = config.environment === 'production' ? 'http' : 'info'; req.logger.log(logLevel, `${req.method} en ${req.url} - at ${new Date().toLocaleDateString()} - ${new Date().toLocaleTimeString()}`); next(); }; export default logger
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE section PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.docbook.org/xml/4.5/docbookx.dtd" [ <!ENTITY % xinclude SYSTEM "../../docbook/xinclude.mod"> %xinclude; <!ENTITY % local.common.attrib "xml:base CDATA #IMPLIED"> ]> <section id="Terminology_datacat"> <title>Terminology</title> <para>Marks terms and optionally associates them with information, such as definitions. See <olink targetdoc="../xliff21.xml" targetptr="ITS20">[ITS]</olink> <ulink url="http://www.w3.org/TR/its20/#terminology">Terminology</ulink> for details.</para> <para>ITS Terminology information is useful during <firstterm>Translation</firstterm> and related localization processes. Thus it is beneficial when <firstterm>Extractors</firstterm> preserve the ITS Terminology information in <firstterm>XLIFF Documents</firstterm>.</para> <para>Target language terminology data and metada introduced during the <firstterm>Translation</firstterm> can be <firstterm>Merged</firstterm> back into the target language content in the original format.</para> <para> </para> <warning> <para>The <firstterm>XLIFF Core</firstterm> <olink targetdoc="../inline/inline.xml" targetptr="termAnnotation">Term Annotation</olink> does not support all aspects of the <olink targetdoc="../xliff21.xml" targetptr="ITS20" >[ITS]</olink> <ulink url="http://www.w3.org/TR/its20/#terminology">Terminology</ulink> data category. For instance, the <firstterm>XLIFF Core</firstterm> Term Annotation cannot be used to mark a span as not a term, which is needed to map ITS <code>term="no"</code>. In case lossless roundtrip of this category needs to be achieved, the Core Annotation needs to be extended as defined by the <link linkend="nonTermAnnotation">ITS Terminology Annotation</link>.</para> </warning> <section id="Terminology_Structural"> <title>Structural Elements</title> <para>Even if ITS Terminology metadata appears on structural elements in the source format, this information needs to be <firstterm>Extracted</firstterm> using the <firstterm>XLIFF Core</firstterm> <olink targetdoc="../inline/inline.xml" targetptr="annotations">Annotations</olink> mechanism. Use <code><olink targetdoc="../elements/inline/mrk.xml" targetptr="mrk" >&lt;mrk></olink></code> or an <code><olink targetdoc="../elements/inline/sm.xml" targetptr="sm">&lt;sm/></olink></code> / <code><olink targetdoc="../elements/inline/em.xml" targetptr="em">&lt;em/></olink></code> pair with <code>type="term"</code>. See <olink targetdoc="../inline/inline.xml" targetptr="termAnnotation">Term Annotation</olink>.</para> <example> <title>Extraction of Terminology from structural elements</title> <para>Original:</para> <programlisting> &lt;p its-term='yes'&gt;Term&lt;/p&gt; </programlisting> <para>Extraction:</para> <programlisting> &lt;unit id='1'&gt; &lt;segment&gt; &lt;source&gt;&lt;mrk id="m1" type="term"&gt;Term&lt;/mrk&gt;&lt;/source&gt; &lt;/segment&gt; &lt;/unit&gt; </programlisting> </example> </section> <section id="Terminology_Inline"> <title>Inline Elements</title> <para> Inline Terminology information <glossterm>may</glossterm> be <firstterm>Extracted</firstterm> using the <firstterm>XLIFF Core</firstterm> <olink targetdoc="../inline/inline.xml" targetptr="annotations">Annotations</olink> mechanism. Use <code><olink targetdoc="../elements/inline/mrk.xml" targetptr="mrk" >&lt;mrk></olink></code> or an <code><olink targetdoc="../elements/inline/sm.xml" targetptr="sm">&lt;sm/></olink></code> / <code><olink targetdoc="../elements/inline/em.xml" targetptr="em">&lt;em/></olink></code> pair with <code>type="term"</code>. See <olink targetdoc="../inline/inline.xml" targetptr="termAnnotation">Term Annotation</olink>.</para> <example> <title>Extraction of inline Terminology using Annotation markers</title> <para>Original:</para> <programlisting> &lt;p>Text with a &lt;span its-term='yes'>term&lt;/span>.&lt;/p> </programlisting> <para>Extraction:</para> <programlisting> &lt;unit id='1'> &lt;segment> &lt;source>Text with a &lt;pc id='1'&gt;&lt;mrk id="m1" type="term">term&lt;/mrk> &lt;/pc>.&lt;/source> &lt;/segment> &lt;/unit> </programlisting> </example> </section> <section id="nonTermAnnotation"> <title>ITS Terminology Annotation</title> <para>This is used to fully map to and from the <olink targetdoc="../xliff21.xml" targetptr="ITS20">[ITS]</olink> <ulink url="http://www.w3.org/TR/its20/#terminology">Terminology</ulink> data category, including the aspects that are not supported via the <firstterm>XLIFF Core</firstterm> <olink targetdoc="../inline/inline.xml" targetptr="termAnnotation">Term Annotation</olink>.</para> <para>Usage:</para> <itemizedlist spacing="compact"> <listitem> <para>The <olink targetdoc="../../attributes/id.xml" targetptr="id" ><code>id</code></olink> attribute is <glossterm>required</glossterm>.</para> </listitem> <listitem> <para>The <olink targetdoc="../../attributes/type.xml" targetptr="type" ><code>type</code></olink> attribute is <glossterm>required</glossterm> and set:</para> <itemizedlist spacing="compact"> <listitem> <para>either to <code>its:term-no</code>, which maps to and from the <olink targetdoc="../xliff21.xml" targetptr="ITS20">[ITS]</olink> defined <code>term</code> attribute set to <code>no</code>,</para> </listitem> <listitem> <para>or to <code>term</code>, which maps to and from the <olink targetdoc="../xliff21.xml" targetptr="ITS20">[ITS]</olink> defined <code>term</code> attribute set to <code>yes</code>.</para> </listitem> </itemizedlist> </listitem> <listitem> <para>Not more than one of the following two attributes <glossterm>may</glossterm> be set:</para> <itemizedlist> <listitem> <para>The <olink targetdoc="../../attributes/value.xml" targetptr="value" ><code>value</code></olink> attribute is <glossterm>optional</glossterm> and contains a short definition of the term that an <firstterm>Extractor</firstterm> obtained by dereferencing the <olink targetdoc="../xliff21.xml" targetptr="ITS20" >[ITS]</olink> defined <code>termInfoPointer</code> or added by an <firstterm>Enricher</firstterm>.</para> </listitem> <listitem> <para>The <olink targetdoc="../../attributes/ref.xml" targetptr="ref" ><code>ref</code></olink> attribute is <glossterm>optional</glossterm> and used to map to and from the <olink targetdoc="../xliff21.xml" targetptr="ITS20">[ITS]</olink> defined <code>termInfoRef</code> attribute.</para> </listitem> </itemizedlist> </listitem> <listitem> <para>The <olink targetdoc="../../attributes/translate.xml" targetptr="translate" ><code>translate</code></olink> attribute is <glossterm>optional</glossterm>.</para> </listitem> <listitem> <para>The <olink targetdoc="../../attributes/itsm/itsm_termConfidence.xml" targetptr="itsm_termConfidence"><code>its:termConfidence</code></olink> attribute is <glossterm>optional</glossterm> and used to map to and from the <olink targetdoc="../xliff21.xml" targetptr="ITS20">[ITS]</olink> defined <code>termConfidence</code> attribute.</para> </listitem> <listitem> <para> The <olink targetdoc="../../attributes/itsm/itsm_annotatorsRef.xml" targetptr="itsm_annotatorsRef"><code>its:annotatorsRef</code></olink> attribute is <glossterm>required</glossterm> if and only if the <olink targetdoc="../../attributes/itsm/itsm_termConfidence.xml" targetptr="itsm_termConfidence"><code>its:termConfidence</code></olink> attribute is present and NOT in scope of another relevant <olink targetdoc="../../attributes/itsm/itsm_annotatorsRef.xml" targetptr="itsm_annotatorsRef"><code>its:annotatorsRef</code></olink> attribute, in all other cases it is <glossterm>optional</glossterm>. </para> </listitem> </itemizedlist> <warning><para>This annotation can be syntactically in scope of a relevant <olink targetdoc="../../attributes/itsm/itsm_annotatorsRef.xml" targetptr="itsm_annotatorsRef" ><code>its:annotatorsRef</code></olink> attribute, while it still fails to resolve with the intended value. This can happen if more then one terminology providers were used. COMMENT: HARD TO UNDERSTAND THE INTENTION OF THE WARNING, NEEDS REWRITING OR SHOULD BE DROPPED.</para></warning> <example> <title>Extraction of ITS Terminology with termConfidence </title> <programlisting> &lt;div its-annotators-ref="terminology|<ulink url="http://example.org/TermService">http://example.org/TermService</ulink>"&gt; ... &lt;p&gt;Text with a &lt;span its-term='yes' its-term-info-ref='http://en.wikipedia.org/wiki/Terminology' its-term-confidence='0.9'&gt;term&lt;/span&gt;.&lt;/p&gt; ... &lt;/div> </programlisting> <para>Extracted:</para> <programlisting> &lt;unit id='1' its:annotatorsRef='terminology|http://example.com/termchecker'&gt; &lt;segment&gt; &lt;source&gt;Text with a &lt;pc id="1"&gt;&lt;mrk id="m1" type="term" ref="http://en.wikipedia.org/wiki/Terminology" its:termConfidence="0.9"&gt;term&lt;/mrk&gt;&lt;/pc&gt;.&lt;/source&gt; &lt;/segment&gt; &lt;/unit&gt; </programlisting> </example> </section> </section>
<template> <v-toolbar app dark scroll-off-screen scroll-target="#scrolling"> <v-toolbar-side-icon> <v-icon>graphic_eq</v-icon> </v-toolbar-side-icon> <v-toolbar-title> <span class="font-weight-thin">GRAPHICMS</span> </v-toolbar-title> <v-spacer></v-spacer> <v-toolbar-items> <v-btn icon v-on:click="routeHomepage"> <v-icon>home</v-icon> </v-btn> <v-btn v-if="logined" icon v-on:click="routeProjects"> <v-icon>apps</v-icon> </v-btn> <v-btn icon v-on:click="routeLogin"> <v-icon>account_circle</v-icon> </v-btn> </v-toolbar-items> </v-toolbar> </template> <script> import {mapState} from 'vuex'; export default { computed:mapState({ logined: function(state) { let localIsLogined = localStorage.getItem('isLogined'); if(localIsLogined) { this.$store.commit('login'); } return state.isLogined; }, userId: function(state) { let localUserId = localStorage.getItem('userId'); if(state.userId==""&&localUserId) { this.$store.commit('setUserId',localUserId); } return state.userId } }), methods: { routeLogin: function() { if (this.$store.state.isLogined == true) { this.$router.push("/personalInformation/" + this.userId); } else { this.$router.push("/login"); } }, routeHomepage: function() { this.$router.push("/"); }, routeProjects() { this.$router.push("/projects/" + this.userId); } } }; </script>
package com.example.simpledblp; import java.util.ArrayList; import android.content.Context; import android.content.Intent; import android.graphics.Typeface; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; public class AuthorListAdapter extends ArrayAdapter<Author> { private ArrayList<Author> authors; private Context context; public AuthorListAdapter(Context context, ArrayList<Author> authors) { super(context, R.layout.author_listing, authors); this.authors = authors; this.context = context; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = null; // assign the view we are converting to a local variable LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = inflater.inflate(R.layout.author_listing, null); TextView text = (TextView) v.findViewById(R.id.authorName); Typeface roboto=Typeface.createFromAsset(context.getAssets(),"fonts/RobotoCondensed-Light.ttf"); text.setTypeface(roboto); text.setText(authors.get(position).getName()); final String authorUrlpt = authors.get(position).getUrlpt(); text.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent myIntent = new Intent(v.getContext(), ResultsListActivity.class); myIntent.putExtra("authorUrlpt", authorUrlpt); //Optional parameters v.getContext().startActivity(myIntent); } }); return v; } }
using System; class GezginSaticiIteratif { static int[,] distanceMatrix = { {0, 10, 15, 20}, {10, 0, 35, 25}, {15, 35, 0, 30}, {20, 25, 30, 0} }; static int cities = 4; static int[] visited; // Fonksiyon, verilen yolu ziyaret etmiş mi kontrol eder static bool AllVisited() { for (int i = 0; i < cities; i++) { if (visited[i] == 0) return false; } return true; } // Hesaplanmış yolları kontrol eder static int ComputePath(int[] path) { int pathDistance = 0; for (int i = 0; i < cities - 1; i++) { pathDistance += distanceMatrix[path[i], path[i + 1]]; } pathDistance += distanceMatrix[path[cities - 1], path[0]]; // Geri dönüş yolunu ekler return pathDistance; } // Ana işlev public static void Main() { visited = new int[cities]; int[] path = new int[cities]; int minPath = int.MaxValue; for (int i = 0; i < cities; i++) { path[0] = i; // Başlangıç noktası visited[i] = 1; // Ziyaret edildi olarak işaretle int currentPath = TSP(path, 1); // Minimum yol bul visited[i] = 0; // Ziyaret işaretini geri al minPath = Math.Min(minPath, currentPath); } Console.WriteLine("Minimum Path Weight: " + minPath); } // Geri izleme algoritması static int TSP(int[] path, int level) { if (level == cities && AllVisited()) // n { return ComputePath(path); // n } int minPath = int.MaxValue; // 1 for (int i = 0; i < cities; i++) // n { if (visited[i] == 0) // 1 { visited[i] = 1; // 1 path[level] = i; // 1 minPath = Math.Min(minPath, TSP(path, level + 1)); // n! visited[i] = 0; // 1 } } return minPath; // 1 } //Sonuç= O(n!) }
/* * Copyright (c) 2006-2016, Guillaume Gimenez <guillaume@blackmilk.fr> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of G.Gimenez nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL G.Gimenez BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: * * Guillaume Gimenez <guillaume@blackmilk.fr> * */ #include "oprepair.h" #include "operatorinput.h" #include "operatoroutput.h" #include "operatorworker.h" #include "operatorparameterslider.h" class WorkerRepair : public OperatorWorker { qreal m_radius; public: WorkerRepair(qreal radius, QThread *thread, Operator *op) : OperatorWorker(thread, op), m_radius(radius) { } Photo process(const Photo &, int, int) { throw 0; } void play() { int c0 = m_inputs[0].count(); int c1 = m_inputs[1].count(); for (int i = 0 ; i < c0 ; ++i) { Photo& srcPhoto = m_inputs[0][i]; Photo& mapPhoto = m_inputs[1][i%c1]; Photo blurredPhoto(srcPhoto); Photo outputPhoto(srcPhoto); blurredPhoto.image().gaussianBlur(m_radius, m_radius); Magick::Image &srcImage = srcPhoto.image(); Magick::Image &mapImage = mapPhoto.image(); Magick::Image &blurredImage = blurredPhoto.image(); Magick::Image &outputImage = outputPhoto.image(); ResetImage(outputImage); int w = srcImage.columns(); int h = srcImage.rows(); if ( w != int(mapImage.columns()) || h != int(mapImage.rows())) { dflError(tr("Input image and pixels map differ in size")); emitFailure(); return; } std::shared_ptr<Ordinary::Pixels> srcCache(new Ordinary::Pixels(srcImage)); std::shared_ptr<Ordinary::Pixels> mapCache(new Ordinary::Pixels(mapImage)); std::shared_ptr<Ordinary::Pixels> blurredCache(new Ordinary::Pixels(blurredImage)); std::shared_ptr<Ordinary::Pixels> outputCache(new Ordinary::Pixels(outputImage)); dfl_parallel_for(y, 0, h, 4, (srcImage, mapImage, blurredImage, outputImage), { const Magick::PixelPacket *srcPixels = srcCache->getConst(0, y, w, 1); const Magick::PixelPacket *mapPixels = mapCache->getConst(0, y, w, 1); const Magick::PixelPacket *blurredPixels = blurredCache->getConst(0, y, w, 1); Magick::PixelPacket *outputPixels = outputCache->get(0, y, w, 1); for (int x = 0 ; x < w ; ++x) { if (mapPixels[x].red) { outputPixels[x] = blurredPixels[x]; } else { outputPixels[x] = srcPixels[x]; } } outputCache->sync(); }); emitProgress(i, c0, 1, 1); outputPush(0, outputPhoto); } emitSuccess(); } }; OpRepair::OpRepair(Process *parent) : Operator(OP_SECTION_COSMETIC, QT_TRANSLATE_NOOP("Operator", "Repair"), Operator::All, parent), m_radius(new OperatorParameterSlider("radius", tr("Radius"), tr("Repair radius"), Slider::Value, Slider::Linear, Slider::Real, .1, 100, 5, .1, 1000, Slider::FilterPixels, this)) { addInput(new OperatorInput(tr("Images"), OperatorInput::Set, this)); addInput(new OperatorInput(tr("Bad pixels map"), OperatorInput::Set, this)); addOutput(new OperatorOutput(tr("Images"), this)); addParameter(m_radius); } OpRepair *OpRepair::newInstance() { return new OpRepair(m_process); } OperatorWorker *OpRepair::newWorker() { return new WorkerRepair(m_radius->value(), m_thread, this); }
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User Registration</title> <link rel="stylesheet" type="text/css" href="{% static 'css/registerstyle.css' %}"> </head> <body> <div class="row"> <div id="col-1"> </div> <div id="col-2"> <div class="register-form"> <h3 class="register-heading mb-4">Sign Up</h3> {% if messages %} {% for message in messages %} <div>{{ message }}</div> {% endfor %} {% endif %} <form method="post" action="{% url 'register' %}"> {% csrf_token %} <div class="input-group"> {{ form.username }} <div class="error-message">{{ form.username.errors }}</div> </div> <div class="input-group"> {{ form.email }} <div class="error-message">{{ form.email.errors }}</div> </div> <div class="input-group"> {{ form.password1 }} <div class="error-message">{{ form.password1.errors }}</div> </div> <div class="input-group"> {{ form.password2 }} <div class="error-message">{{ form.password2.errors }}</div> </div> <button type="submit" class = btn-register>Register</button> </form> <p class="signin">Already have an account? <a href="{% url 'login' %}">Sign In</a></p> </div> </div> </div> </body> </html>
package ru.netology.diploma.api import okhttp3.MultipartBody import retrofit2.Response import retrofit2.http.Body import retrofit2.http.DELETE import retrofit2.http.GET import retrofit2.http.Header import retrofit2.http.Multipart import retrofit2.http.POST import retrofit2.http.Part import retrofit2.http.Path import retrofit2.http.Query import ru.netology.diploma.dto.Job import ru.netology.diploma.dto.Media import ru.netology.diploma.dto.Post import ru.netology.diploma.dto.PushToken import ru.netology.diploma.dto.UserResponse interface PostsApiService { @GET("posts") suspend fun getAll (@Header("Api-Key") apiKey: String) : Response<List<Post>> // импортировать нужно из retrofit2 @GET("posts/latest") suspend fun getLatest (@Query("count") count: Int) : Response<List<Post>> @GET("posts/{id}/before") suspend fun getBefore (@Path("id") id: Int, @Query("count") count: Int): Response<List<Post>> @GET("posts/{id}/after") suspend fun getAfter (@Path("id") id: Int, @Query("count") count: Int): Response<List<Post>> @POST("posts/{id}/likes") suspend fun likeById(@Path("id") id: Int, @Header("Api-Key") apiKey: String): Response<Post> @DELETE("posts/{id}/likes") suspend fun dislikeById(@Path("id") id: Int, @Header("Api-Key") apiKey: String): Response<Post> @POST("posts") suspend fun save(@Body post: Post, @Header("Api-Key") apiKey: String): Response<Post> @DELETE("posts/{id}") suspend fun removeById(@Path("id") id: Int, @Header("Api-Key") apiKey: String): Response<Unit> @Multipart @POST("media") suspend fun saveMedia(@Part media: MultipartBody.Part, @Header("Api-Key") apiKey: String): Response<Media> @GET("users/{id}") suspend fun getUserById (@Path("id") id: Int, @Header("Api-Key") apiKey: String): Response<UserResponse> @GET("users") suspend fun getAllUsers (@Header("Api-Key") apiKey: String): Response<List<UserResponse>> @GET("{authorId}/wall") suspend fun getWall (@Path("authorId") id: Int, @Header("Api-Key") apiKey: String): Response<List<Post>> @GET("{userId}/jobs") suspend fun getJobs (@Path("userId") id: Int, @Header("Api-Key") apiKey: String): Response<List<Job>> @GET("my/jobs") suspend fun getMyJobs (@Header("Api-Key") apiKey: String): Response<List<Job>> @POST("my/jobs") suspend fun createJob(@Body job: Job, @Header("Api-Key") apiKey: String): Response<Job> @DELETE("my/jobs/{id}") suspend fun removeJobById(@Path("id") id: Int, @Header("Api-Key") apiKey: String): Response<Unit> }