text
stringlengths
184
4.48M
<?php namespace App\Http\Controllers; use App\Http\Requests\AuthRequest; use App\Services\Auth\AuthService; use App\Services\User\UserService; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use Symfony\Component\HttpFoundation\Response as RESPONSE; class AuthController extends AbstractApiController { private $userService; private $authService; public function __construct(UserService $userService, AuthService $authService) { $this->userService = $userService; $this->authService = $authService; } /** * Login method. * * @param \App\Http\Requests\AuthRequest $request * @return \Illuminate\Http\Response */ public function login(AuthRequest $request) { $payload = $request->validated(); $user = $this->userService->findByEmail($payload['email']); if (!$user || !Hash::check($payload['password'], $user->password)) { $errorResponse = [ 'status' => false, 'message' => 'Email or Password did not match !', ]; return $this->apiErrorResponse($errorResponse, RESPONSE::HTTP_UNAUTHORIZED); } $loginResult = $this->authService->createUserToken($user); return $this->apiSuccessResponse($loginResult, RESPONSE::HTTP_OK); } /** * Remove the specified resource from storage. * * * @return \Illuminate\Http\Response */ public function logout(Request $request) { $request->user()->currentAccessToken()->delete(); $response = [ 'success' => true, 'data' => null, ]; return $this->apiSuccessResponse($response, RESPONSE::HTTP_NO_CONTENT); } /** * Refresh the access & refresh token with old refresh token * * * @return \Illuminate\Http\Response */ public function refresh(Request $request) { $refreshToken = $request->header('RefreshToken'); $userToken = $this->authService->reGenerateUserToken($refreshToken); if (is_null($userToken)) { $errorResponse = [ 'status' => false, 'message' => 'Token not found', ]; return $this->apiErrorResponse($errorResponse, RESPONSE::HTTP_UNAUTHORIZED); } return $userToken; } /** * Remove the specified resource from storage. * * * @return \Illuminate\Http\Response */ public function user(Request $request) { $response = [ 'success' => true, 'data' => $request->user(), ]; return $this->apiSuccessResponse($response, RESPONSE::HTTP_OK); } }
// Copyright 2023 RisingWave Labs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use ::jsonbb::{ArrayRef, ObjectRef, Value, ValueRef}; use ::serde_json::Number; impl super::Json for Value { type Borrowed<'a> = ValueRef<'a>; fn as_ref(&self) -> Self::Borrowed<'_> { self.as_ref() } fn null() -> Self { Value::null() } fn bool(b: bool) -> Self { Value::from(b) } fn from_u64(v: u64) -> Self { Value::from(v) } fn from_i64(v: i64) -> Self { Value::from(v) } fn from_f64(v: f64) -> Self { Value::from(v) } fn from_number(n: Number) -> Self { Value::from(n) } fn from_string(s: &str) -> Self { Value::from(s) } fn object<'a, I: IntoIterator<Item = (&'a str, Self)>>(iter: I) -> Self { let kvs: Vec<_> = iter.into_iter().collect(); Value::object(kvs.iter().map(|(k, v)| (*k, v.as_ref()))) } } impl<'a> super::JsonRef<'a> for ValueRef<'a> { type Owned = Value; type Array = ArrayRef<'a>; type Object = ObjectRef<'a>; fn to_owned(self) -> Self::Owned { self.to_owned() } fn null() -> Self { Self::Null } fn is_null(self) -> bool { self.is_null() } fn as_bool(self) -> Option<bool> { self.as_bool() } fn as_number(self) -> Option<Number> { self.as_number().map(|n| n.to_number()) } fn as_str(self) -> Option<&'a str> { self.as_str() } fn as_array(self) -> Option<ArrayRef<'a>> { self.as_array() } fn as_object(self) -> Option<ObjectRef<'a>> { self.as_object() } fn is_number(self) -> bool { self.is_number() } fn is_string(self) -> bool { self.is_string() } fn is_array(self) -> bool { self.is_array() } fn is_object(self) -> bool { self.is_object() } } impl<'a> super::ArrayRef<'a> for ArrayRef<'a> { type JsonRef = ValueRef<'a>; fn len(self) -> usize { self.len() } fn get(self, index: usize) -> Option<Self::JsonRef> { self.get(index) } fn list(self) -> Vec<Self::JsonRef> { self.iter().collect() } } impl<'a> super::ObjectRef<'a> for ObjectRef<'a> { type JsonRef = ValueRef<'a>; fn len(self) -> usize { self.len() } fn get(self, key: &str) -> Option<Self::JsonRef> { self.get(key) } fn list(self) -> Vec<(&'a str, Self::JsonRef)> { self.iter().collect() } fn list_value(self) -> Vec<Self::JsonRef> { self.values().collect() } }
/* * Author: * Philip Van Hoof <pvanhoof@gnome.org> * * Copyright 1999, 2007 Philip Van Hoof * * This program is free software; you can redistribute it and/or * modify it under the terms of version 2 of the GNU Lesser General Public * License as published by the Free Software Foundation. * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "camel-stream-gzip.h" static CamelObjectClass *parent_class = NULL; #define CSZ_CLASS(so) CAMEL_STREAM_GZIP_CLASS(CAMEL_OBJECT_GET_CLASS(so)) static ssize_t z_stream_read (CamelStream *stream, char *buffer, size_t n) { ssize_t haveread = 0, retval = 0; CamelStreamGZip *self = (CamelStreamGZip *) stream; z_stream c_stream = * (self->r_stream); if (self->read_mode == CAMEL_STREAM_GZIP_ZIP) { char *mem = g_malloc0 (n); c_stream.next_out = (Bytef *) buffer; c_stream.avail_out = n; haveread = camel_stream_read (self->real, mem, n); c_stream.next_in = (Bytef *) mem; c_stream.avail_in = haveread; deflate (&c_stream, Z_FINISH); retval = n - c_stream.avail_out; g_free (mem); } else { int block_size = (n < 1000) ? (n < 10 ? 2 : 10) : n / 100; char *mem = g_malloc0 (block_size); haveread = block_size; c_stream.next_out = (Bytef *) buffer; c_stream.avail_out = n; while (haveread == block_size && c_stream.avail_out > 0) { haveread = camel_stream_read (self->real, mem, block_size); c_stream.next_in = (Bytef *) mem; c_stream.avail_in = haveread; inflate (&c_stream, Z_NO_FLUSH); } retval = n - c_stream.avail_out; g_free (mem); } return retval; } static ssize_t z_stream_write (CamelStream *stream, const char *buffer, size_t n) { CamelStreamGZip *self = (CamelStreamGZip *) stream; z_stream c_stream = * (self->w_stream); ssize_t retval = 0; if (self->write_mode == CAMEL_STREAM_GZIP_ZIP) { char *mem = g_malloc0 (n); c_stream.next_in = (Bytef *) buffer; c_stream.avail_in = n; c_stream.next_out = (Bytef *) mem; c_stream.avail_out = n; deflate (&c_stream, Z_FINISH); camel_stream_write (self->real, mem, n - c_stream.avail_out); retval = n; g_free (mem); } else { char *mem = g_malloc0 (n); c_stream.next_in = (Bytef *) buffer; c_stream.avail_in = n; c_stream.next_out = (Bytef *) mem; c_stream.avail_out = n; while (c_stream.avail_in > 0) { inflate (&c_stream, Z_NO_FLUSH); camel_stream_write (self->real, mem, n - c_stream.avail_out); retval += n - c_stream.avail_out; c_stream.next_out = (Bytef *) mem; c_stream.avail_out = n; } g_free (mem); } return retval; } static int z_stream_flush (CamelStream *stream) { CamelStreamGZip *self = (CamelStreamGZip *) stream; return camel_stream_flush (self->real); } static int z_stream_close (CamelStream *stream) { CamelStreamGZip *self = (CamelStreamGZip *) stream; z_stream_flush (stream); return camel_stream_close (self->real); } static gboolean z_stream_eos (CamelStream *stream) { CamelStreamGZip *self = (CamelStreamGZip *) stream; return camel_stream_eos (self->real); } static int z_stream_reset (CamelStream *stream) { CamelStreamGZip *self = (CamelStreamGZip *) stream; if (self->read_mode == CAMEL_STREAM_GZIP_ZIP) deflateReset (self->r_stream); else inflateReset (self->r_stream); if (self->write_mode == CAMEL_STREAM_GZIP_ZIP) deflateReset (self->w_stream); else inflateReset (self->w_stream); return 0; } static void camel_stream_gzip_class_init (CamelStreamClass *camel_stream_gzip_class) { CamelStreamClass *camel_stream_class = (CamelStreamClass *)camel_stream_gzip_class; parent_class = camel_type_get_global_classfuncs( CAMEL_OBJECT_TYPE ); /* virtual method definition */ camel_stream_class->read = z_stream_read; camel_stream_class->write = z_stream_write; camel_stream_class->close = z_stream_close; camel_stream_class->flush = z_stream_flush; camel_stream_class->eos = z_stream_eos; camel_stream_class->reset = z_stream_reset; } static void camel_stream_gzip_finalize (CamelObject *object) { CamelStreamGZip *self = (CamelStreamGZip *) object; camel_object_unref (CAMEL_OBJECT (self->real)); if (self->read_mode == CAMEL_STREAM_GZIP_ZIP) deflateEnd (self->r_stream); else inflateEnd (self->r_stream); if (self->write_mode == CAMEL_STREAM_GZIP_ZIP) deflateEnd (self->w_stream); else inflateEnd (self->w_stream); g_free (self->r_stream); g_free (self->w_stream); return; } CamelType camel_stream_gzip_get_type (void) { static CamelType camel_stream_gzip_type = CAMEL_INVALID_TYPE; if (camel_stream_gzip_type == CAMEL_INVALID_TYPE) { camel_stream_gzip_type = camel_type_register( camel_stream_get_type(), "CamelStreamGZip", sizeof( CamelStreamGZip ), sizeof( CamelStreamGZipClass ), (CamelObjectClassInitFunc) camel_stream_gzip_class_init, NULL, NULL, (CamelObjectFinalizeFunc) camel_stream_gzip_finalize ); } return camel_stream_gzip_type; } static int set_mode (z_stream *stream, int level, int mode) { int retval; if (mode == CAMEL_STREAM_GZIP_ZIP) retval = deflateInit2 (stream, level, Z_DEFLATED, -MAX_WBITS, MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY); else retval = inflateInit2 (stream, -MAX_WBITS); return retval; } CamelStream * camel_stream_gzip_new (CamelStream *real, int level, int read_mode, int write_mode) { CamelStreamGZip *self = (CamelStreamGZip *) camel_object_new (camel_stream_gzip_get_type ()); int retval; camel_object_ref (CAMEL_OBJECT (real)); self->real = real; self->r_stream = g_new0 (z_stream, 1); self->w_stream = g_new0 (z_stream, 1); self->level = level; self->read_mode = read_mode; self->write_mode = write_mode; retval = set_mode (self->r_stream, level, read_mode); if (retval != Z_OK) { camel_object_unref (self); return NULL; } retval = set_mode (self->w_stream, level, write_mode); if (retval != Z_OK) { camel_object_unref (self); return NULL; } return CAMEL_STREAM (self); }
{% extends 'base.html' %} {% load static %} {% block extra_head %} <link rel="stylesheet" type="text/css" href="{% static 'css/home.css' %}"> {% endblock extra_head %} {% block title %}Profile{% endblock title %} {% block content %} <div class="profile-page"> <h2>Profile Details</h2> <img src="{{ profile.get_avatar_url }}" class="responsive-image" alt="Avatar"/> {% include 'fragments/_category_info.html' with category='Email' data=profile.user.email %} {% include 'fragments/_category_info.html' with category='First Name' data=profile.first_name %} {% include 'fragments/_category_info.html' with category='Last Name' data=profile.last_name %} {% include 'fragments/_category_info.html' with category='Bio' data=profile.bio %} {% include 'fragments/_category_info.html' with category='Birth Date' data=profile.birth_date %} {% if user == profile.user %} <div> <a href="{% url 'profile_edit' %}" class="profile-link">Edit</a> <a href="{% url 'profile_delete' %}" class="profile-link">Delete</a> </div> {% endif %} </div> <hr> <div> <h2>Posts</h2> <div class="profile-posts"> {% for post in posts %} <div class="card-or-remove"> <a href="{% url 'post_detail' post.id %}"> {% include 'posts/post_card.html' %} </a> {% if user == profile.user %} <a href="{% url 'post_delete' post.id %}" class="delete-button"><i class="fas fa-trash fa-2x"></i></a> {% endif %} </div> {% endfor %} </div> </div> {% endblock content %}
import { OrderStatusEnum, STATUS_CODES } from '../../constants.js'; import { OrderRepository, VendorRepository } from '../../database/index.js'; import ApiError from '../../utils/ApiErrors.js'; import ApiResponse from '../../utils/ApiResponse.js'; class VendorOrderController { constructor() { this.vendorDb = new VendorRepository(); this.orderDb = new OrderRepository(); } async GetOrders(req, res, next) { try { const { page = 1, limit = 25, status = '', vendorId } = req.query; let vendorOrders; if (status) { vendorOrders = await this.orderDb.FindOrderByVendorIdWithStatus( vendorId, status, page, limit ); } else { vendorOrders = await this.orderDb.FindOrderByVendorId( vendorId, page, limit ); } if (!vendorOrders) { throw new ApiError(STATUS_CODES.NOT_FOUND, 'Vendor Order Not Found'); } return res .status(STATUS_CODES.OK) .json( new ApiResponse( STATUS_CODES.OK, vendorOrders, 'Vendor orders fetched successfully' ) ); } catch (error) { return next(error); } } async GetOrder(req, res, next) { try { const vendor = await this.orderDb.DeleteOrderById(req.params.orderId); return res .status(STATUS_CODES.OK) .json( new ApiResponse( STATUS_CODES.OK, vendor, 'Vendor order fetched successfully' ) ); } catch (error) { return next(error); } } async UpdateOrderVendorStatuses(req, res, next) { try { let vendor = await this.orderDb.FindOrderById(req.params.orderId); const { status } = req.body; if (!vendor) { throw new ApiError(STATUS_CODES.NOT_FOUND, 'Order not found'); } if ( OrderStatusEnum.CANCELLED === vendor.dataValues.status || OrderStatusEnum.DELIVERED === vendor.dataValues.status ) { throw new ApiError( STATUS_CODES.BAD_REQUEST, 'The order status cannot be updated once it has been canceled or delivered' ); } if ( status === OrderStatusEnum.CANCELLED || status === OrderStatusEnum.DELIVERED ) { throw new ApiError( STATUS_CODES.BAD_REQUEST, 'The order status cannot be updated to canceled or delivered' ); } vendor = await this.orderDb.UpdateOrder( { id: req.params.orderId }, { status } ); return res .status(STATUS_CODES.OK) .json( new ApiResponse( STATUS_CODES.OK, vendor, 'Vendor order fetched successfully' ) ); } catch (error) { return next(error); } } async UpdateOrderComplete(req, res, next) { try { let vendor = await this.orderDb.FindOrderById(req.params.orderId); if (!vendor) { throw new ApiError(STATUS_CODES.NOT_FOUND, 'Order not found'); } if ( OrderStatusEnum.CANCELLED === vendor.dataValues.status || OrderStatusEnum.DELIVERED === vendor.dataValues.status ) { throw new ApiError( STATUS_CODES.BAD_REQUEST, 'The order status cannot be updated once it has been canceled or delivered' ); } vendor = await this.orderDb.UpdateOrder( { id: req.params.orderId }, { status: OrderStatusEnum.DELIVERED, completedAt: new Date(), } ); return res .status(STATUS_CODES.OK) .json( new ApiResponse( STATUS_CODES.OK, vendor, 'Vendor order fetched successfully' ) ); } catch (error) { return next(error); } } async UpdateOrderCancel(req, res, next) { try { let vendor = await this.orderDb.FindOrderById(req.params.orderId); if (!vendor) { throw new ApiError(STATUS_CODES.NOT_FOUND, 'Order not found'); } if ( OrderStatusEnum.CANCELLED === vendor.dataValues.status || OrderStatusEnum.DELIVERED === vendor.dataValues.status ) { throw new ApiError( STATUS_CODES.BAD_REQUEST, 'The order status cannot be updated once it has been canceled or delivered' ); } vendor = await this.orderDb.UpdateOrder( { id: req.params.orderId }, { status: OrderStatusEnum.CANCELLED, cancelledAt: new Date(), } ); return res .status(STATUS_CODES.OK) .json( new ApiResponse( STATUS_CODES.OK, vendor, 'Vendor order fetched successfully' ) ); } catch (error) { return next(error); } } } export default VendorOrderController;
import { useEffect, useState } from 'react'; import { getData, rxjsState, triggerRxjsSubject, } from '@utility-app/utility-project'; import './style.css'; export default function Root(props) { const [data, setData] = useState(''); const [rxjsData, setRxjsData] = useState<string[]>([]); useEffect(() => { getData('/123').then((response) => { setData(response.data); }); triggerRxjsSubject(); const subscription = rxjsState.subscribe((data) => { if (data) { setRxjsData((rxjsData) => [...rxjsData, data.message]); } }); return () => { subscription.unsubscribe(); }; }, []); return ( <section> <h1>Content</h1> <p>Externals data: {data}</p> {!!rxjsData.length && ( <> <p>Rxjs data:</p> <ul> {rxjsData.map((data, index) => ( <li key={index + data}>{data}</li> ))} </ul> </> )} </section> ); }
import Principal "mo:base/Principal"; import Text "mo:base/Text"; import Debug "mo:base/Debug"; //Contract for NFT actor class NFT(name : Text, owner : Principal, content : [Nat8]) = this { private let itemName = name; private var nftOwner = owner; private let imageBytes = content; public query func getName() : async Text { return itemName; }; public query func getOwner() : async Principal { return nftOwner; }; public query func getContent() : async [Nat8] { return imageBytes; }; public query func getCanisterId() : async Principal { return Principal.fromActor(this); }; public shared (msg) func transferOwnership(newOwnerId : Principal) : async Text { if (msg.caller == nftOwner) { nftOwner := newOwnerId; return "Transferred Successfully"; } else { return "Error: This NFT belongs to someone else"; }; }; };
import cv2 from cvzone.HandTrackingModule import HandDetector from time import sleep import cvzone import pyautogui import os cap = cv2.VideoCapture(0) cap.set(3, 1920) cap.set(4, 1200) detector = HandDetector(detectionCon=1) keys = [["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"], ["A", "S", "D", "F", "G", "H", "J", "K", "L", ";"], ["Z", "X", "C", "V", "B", "N", "M", ",", ".", "/"]] def drawAll(img, buttonList): for button in buttonList: x, y = button.pos w, h = button.size cvzone.cornerRect(img, (button.pos[0], button.pos[1], button.size[0], button.size[1]), 20, rt=0) cv2.rectangle(img, button.pos, (x + w, y + h), (0, 255, 0), cv2.FILLED) cv2.putText(img, button.text, (x + 20, y + 65), cv2.FONT_HERSHEY_PLAIN, 4, (255, 255, 255), 4) cv2.rectangle(img, (450, 0), (452, 720), (0, 255, 0), cv2.FILLED) cv2.rectangle(img, (798, 0), (800, 720), (0, 255, 0), cv2.FILLED) cv2.rectangle(img, (0, 498), (1280, 500), (0, 255, 0), cv2.FILLED) cv2.rectangle(img, (0, 260), (1280, 262), (0, 255, 0), cv2.FILLED) return img class Button(): def __init__(self, pos, text, size=[80, 80]): self.pos = pos self.size = size self.text = text buttonList = [] for i in range(len(keys)): for j, key in enumerate(keys[i]): buttonList.append(Button([100 * j + 150, 100 * i + 100], key)) buttonList.append(Button([300, 400], 'Space', [500, 80])) buttonList.append(Button([810, 400], 'BS', [95, 85])) while True: success, img = cap.read() img = cv2.flip(img, 1) img = detector.findHands(img) lmList, bboxInfo = detector.findPosition(img) img = drawAll(img, buttonList) if lmList: fingers=[] for i in 8, 12, 16, 20: if lmList[i][1]>lmList[i-3][1]: fingers.append(0) if lmList[i][1]<lmList[i-3][1]: fingers.append(1) totalFingers = fingers.count(1) if totalFingers==3: if lmList[8][0]>800: pyautogui.press('Right') sleep(0.15) if lmList[8][0]<450: pyautogui.press('Left') sleep(0.15) if lmList[8][1]>500: pyautogui.press('Down') sleep(0.15) if lmList[8][1]<260: pyautogui.press('Up') sleep(0.15) if totalFingers==0: pyautogui.press('Enter') sleep(0.15) if totalFingers==2: for button in buttonList: x, y = button.pos w, h = button.size if x < lmList[8][0] < x + w and y < lmList[8][1] < y + h: cv2.rectangle(img, (x - 5, y - 5), (x + w + 5, y + h + 5), (175, 0, 175), cv2.FILLED) cv2.putText(img, button.text, (x + 20, y + 65), cv2.FONT_HERSHEY_PLAIN, 4, (255, 255, 255), 4) l, _, _ = detector.findDistance(8, 12, img) if l < 35 : if button.text=='Space': pyautogui.press('Space') elif button.text=='BS': pyautogui.press('backspace') else: pyautogui.press(button.text) cv2.rectangle(img, button.pos, (x + w, y + h), (255, 0, 0), cv2.FILLED) cv2.putText(img, button.text, (x + 20, y + 65), cv2.FONT_HERSHEY_PLAIN, 4, (255, 255, 255), 4) sleep(0.15) key = cv2.waitKey(1) cv2.imshow("Image", img) cv2.waitKey(1) if key == ord("q"): cv2.destroyAllWindows() break
# Exercício 5: Imagine que você tem a implementação de uma classe capaz # renderizar imagens através de uma interface que utiliza o método draw. # Porém, no momento ela só suporta formato PNG e você também precisa ser # capaz de renderizar imagens em SVG. Altere o código sem modificar a classe # SvgImage , para que isso seja possível. # Dica: Se você garantir que a imagem SVG seja renderizada utilizando a mesma # interface que a imagem PNG, a imagem se tornará compatível. """ from abc import ABC, abstractmethod class PngInterface(ABC): @abstractmethod def draw(self): raise NotImplementedError class PngImage(PngInterface): def __init__(self, png_path): self.png_path = png_path self.format = "raster" def draw(self): print(f"Drawing PNG {self.png_path} with {self.format}") class SvgImage: def __init__(self, svg_path): self.svg_path = svg_path self.format = "vector" def get_image(self): return f"SVG {self.svg_path} with {self.format}" """ from abc import ABC, abstractmethod class PngInterface(ABC): @abstractmethod def draw(self): raise NotImplementedError class PngImage(PngInterface): def __init__(self, png_path): self.png_path = png_path self.format = "raster" def draw(self): print(f"Drawing PNG {self.png_path} with {self.format}") class SvgImage: def __init__(self, svg_path): self.svg_path = svg_path self.format = "vector" def get_image(self): return f"SVG {self.png_path} with {self.format}" class SvgAdapter(PngInterface): def __init__(self, svg): self.svg = svg def draw(self): print(f"Drawing {self.svg.get_image()}")
package greasepaint import "github.com/LordOfTrident/ansi-go" var ( Black = NewColor256(ansi.Black) Red = NewColor256(ansi.Red) Green = NewColor256(ansi.Green) Yellow = NewColor256(ansi.Yellow) Blue = NewColor256(ansi.Blue) Magenta = NewColor256(ansi.Magenta) Cyan = NewColor256(ansi.Cyan) White = NewColor256(ansi.White) LightBlack = NewColor256(ansi.LightBlack) LightRed = NewColor256(ansi.LightRed) LightGreen = NewColor256(ansi.LightGreen) LightYellow = NewColor256(ansi.LightYellow) LightBlue = NewColor256(ansi.LightBlue) LightMagenta = NewColor256(ansi.LightMagenta) LightCyan = NewColor256(ansi.LightCyan) LightWhite = NewColor256(ansi.LightWhite) ) type Color interface { AnsiFg() string AnsiBg() string } type ColorDefault struct {} type Color256 struct {Value uint8} type ColorRGB struct {R, G, B uint8} type ColorHex struct {Value string} func NewColor256(value uint8) Color256 {return Color256{Value: value}} func NewColorRGB(r, g, b uint8) ColorRGB {return ColorRGB{R: r, G: g, B: b}} func NewColorHex(value string) ColorHex {return ColorHex{Value: value}} func (c ColorDefault) AnsiFg() string {return ""} func (c ColorDefault) AnsiBg() string {return ""} func (c Color256) AnsiFg() string {return ansi.Fg(c.Value)} func (c Color256) AnsiBg() string {return ansi.Bg(c.Value)} func (c ColorRGB) AnsiFg() string {return ansi.FgRGB(c.R, c.G, c.B)} func (c ColorRGB) AnsiBg() string {return ansi.BgRGB(c.R, c.G, c.B)} func (c ColorHex) AnsiFg() string {return ansi.FgHex(c.Value)} func (c ColorHex) AnsiBg() string {return ansi.BgHex(c.Value)}
# selenium小进阶+案例 ## 关于验证码 验证码处理: 1. 直接把浏览器里面的cookie拿出来直接用. 2. 手动编写验证码识别的功能(深度学习) 3. 第三方打码平台(收费), 超级鹰, 图鉴 上一节, 我们聊过关于验证码的问题. 本节继续. 图鉴-好东西http://www.ttshitu.com/ ![image-20210720170234915](image-20210720170234915.png) 这个东西. 既便宜. 有好用. 比超级鹰爽. 注册个账号. 如果不想注册. 直接用我的也OK 然后就可以用了. 官方示例: ```python import base64 import json import requests # 一、图片文字类型(默认 3 数英混合): # 1 : 纯数字 # 1001:纯数字2 # 2 : 纯英文 # 1002:纯英文2 # 3 : 数英混合 # 1003:数英混合2 # 4 : 闪动GIF # 7 : 无感学习(独家) # 11 : 计算题 # 1005: 快速计算题 # 16 : 汉字 # 32 : 通用文字识别(证件、单据) # 66: 问答题 # 49 :recaptcha图片识别 参考 https://shimo.im/docs/RPGcTpxdVgkkdQdY # 二、图片旋转角度类型: # 29 : 旋转类型 # # 三、图片坐标点选类型: # 19 : 1个坐标 # 20 : 3个坐标 # 21 : 3 ~ 5个坐标 # 22 : 5 ~ 8个坐标 # 27 : 1 ~ 4个坐标 # 48 : 轨迹类型 # # 四、缺口识别 # 18 : 缺口识别(需要2张图 一张目标图一张缺口图) # 33 : 单缺口识别(返回X轴坐标 只需要1张图) # 五、拼图识别 # 53:拼图识别 def base64_api(uname, pwd, img, typeid): with open(img, 'rb') as f: base64_data = base64.b64encode(f.read()) b64 = base64_data.decode() data = {"username": uname, "password": pwd, "typeid": typeid, "image": b64} result = json.loads(requests.post("http://api.ttshitu.com/predict", json=data).text) if result['success']: return result["data"]["result"] else: return result["message"] return "" if __name__ == "__main__": img_path = "xxxx.jpg" result = base64_api(uname='q6035945', pwd='q6035945', img=img_path, typeid=3) print(result) ``` 非常的简单. 老规矩. 我要用图鉴干图鉴, selenium那个上节课讲过了. 这节课我们讲requests ```python def base64_api(uname, pwd, b64_img, typeid): data = {"username": uname, "password": pwd, "typeid": typeid, "image": b64_img} result = json.loads(requests.post("http://api.ttshitu.com/predict", json=data).text) if result['success']: return result["data"]["result"] else: return result["message"] def login(): session = requests.session() url = "http://www.ttshitu.com/login.html?spm=null" resp = session.get(url) tree = etree.HTML(resp.text) # 先处理验证码 # captchaImg data_href = tree.xpath("//img[@id='captchaImg']/@data-href")[0] resp = session.get(data_href) js = resp.json() result = base64_api("q6035945","q6035945", js['img'], '1003') data = { "captcha": result, "developerFlag": False, "imgId": js['imgId'], "needCheck": True, "password": "q6035945", "userName": "q6035945", } headers={ 'Content-Type': 'application/json; charset=UTF-8', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36', } print(data) login_url = "http://admin.ttshitu.com/common/api/login/user" resp = session.post(login_url, data=json.dumps(data), headers=headers) print(resp.text) if __name__ == '__main__': login() ``` ## 关于等待 在selenium中有三种等待方案 1. time.sleep() 这个没啥说的. 就是干等. 不论元素是否加载出来. 都要等 2. web.implicitly_wait() 这个比上面那个人性化很多. 如果元素加载出来了. 就继续. 如果没加载出来. 此时会等待一段时间. 注意, 此设置是全局设置. 一次设置后. 后面的加载过程都按照这个来. (爬虫用的会多一些) 3. WebDriverWait 这个比较狠. 单独等一个xxxx元素. 如果出现了. 就过, 如果不出现. 超时后, 直接报错. ```python ele = WebDriverWait(web, 10, 0.5).until( EC.presence_of_element_located((By.XPATH, "/html/body/div[5]/div[2]/div[1]/div/div")) ) ``` ## selenium搞定BOSS直聘 Boss新版验证极其恶心. 几乎每隔1-2个页面就会出现checkPage的过程. ![image-20210720164819242](image-20210720164819242.png) 就是这个破玩意. 我们可以用selenium来获取页面源代码. 这样就简单多了. 但是为了防止在抓取的过程中出现其他异常. 可以先考虑登录一下. 登录完成之后. 用selenium尝试疯狂输出一把. 看看能不能把我们想要的数据抓取到. 先处理登录(也可以不登录, 自愿) ```PYTHON class VerifyCode(): def __init__(self, username="q6035945", password='q6035945'): self.username = username self.password = password def verify_quekou(self, img, img_back): typeid = 18 with open(img, 'rb') as f: base64_front_data = base64.b64encode(f.read()) b64_front = base64_front_data.decode() with open(img_back, 'rb') as f: base64_bg_data = base64.b64encode(f.read()) b64_bg = base64_bg_data.decode() data = {"username": self.username, "password": self.password, "typeid": typeid, "image": b64_front, "imageback": b64_bg} result = json.loads(requests.post("http://api.ttshitu.com/predict", json=data).text) if result['success']: return result["data"]["result"] else: return result["message"] def verify_quekou_dan(self, img): typeid = 33 with open(img, 'rb') as f: base64_front_data = base64.b64encode(f.read()) base64_img = base64_front_data.decode() data = {"username": self.username, "password": self.password, "typeid": typeid, "image": base64_img} result = json.loads(requests.post("http://api.ttshitu.com/predict", json=data).text) if result['success']: return result["data"]["result"] else: return result["message"] def verify_dian(self, img): typeid = 27 with open(img, 'rb') as f: base64_front_data = base64.b64encode(f.read()) base64_img = base64_front_data.decode() data = {"username": self.username, "password": self.password, "typeid": typeid, "image": base64_img} result = json.loads(requests.post("http://api.ttshitu.com/predict", json=data).text) if result['success']: return result["data"]["result"] else: return result["message"] def login(username="xxxx", password="xxxx"): # 1. 完成登录 login_url = "https://login.zhipin.com/?ka=header-login" web = Chrome() time.sleep(3) web.get(login_url) web.find_element_by_xpath('//*[@id="wrap"]/div[2]/div[1]/div[2]/div[1]/form/div[3]/span[2]/input').send_keys(username) web.find_element_by_xpath('//*[@id="wrap"]/div[2]/div[1]/div[2]/div[1]/form/div[4]/span/input').send_keys(password) web.find_element_by_xpath('//*[@id="pwdVerrifyCode"]/div').click() ele = WebDriverWait(web, 10, 0.5).until( EC.presence_of_element_located((By.XPATH, "/html/body/div[5]/div[2]/div[1]/div/div")) ) ele.screenshot("tu.png") # 验证码点选, 独家秘方 result = VerifyCode().verify_dian("tu.png") points = result.split("|") for point in points: ps = point.split(",") x = int(ps[0]) y = int(ps[1]) ActionChains(web).move_to_element_with_offset(ele, x, y).click().perform() time.sleep(1) web.find_element_by_xpath('/html/body/div[5]/div[2]/div[1]/div/div/div[3]/a/div').click() time.sleep(2) web.find_element_by_xpath('//*[@id="wrap"]/div[2]/div[1]/div[2]/div[1]/form/div[6]/button').click() time.sleep(3) ``` ```python def get_page_source(url): # 登录不登录? login() web.get(url) # 等待有东西就过. ele = WebDriverWait(web, 10).until( EC.presence_of_element_located((By.XPATH, "//div[@class='job-primary']")) ) return web.page_source if __name__ == '__main__': web = Chrome() for i in range(1, 10): url = f"https://www.zhipin.com/c101010100/?query=python&page={i}&ka=page-{i}" print(url) content = get_page_source(url) tree = etree.HTML(content) job_names = tree.xpath("//div[@class='job-primary']//span[@class='job-name']/a/text()") print(job_names) print(f"正在抓取第{i}页") ``` ## 利用selenium登录12306 首先, 我们通过selenium打开12306的登录页面. 并进入到账号登录模块 ```python web = Chrome() web.get("https://kyfw.12306.cn/otn/resources/login.html") time.sleep(1) web.find_element_by_xpath('/html/body/div[2]/div[2]/ul/li[2]/a').click() time.sleep(1) ``` 找到验证码位置, 并截图, 对验证码进行解析. ```python verify_img = web.find_element_by_xpath('//*[@id="J-loginImg"]') result = chaojiying.PostPic(verify_img.screenshot_as_png, 9004) ``` 在验证码区域模拟用户点击 ```python points_str_lst = result['pic_str'].split("|") for p in points_str_lst: p_temp = p.split(",") p_x = int(p_temp[0]) p_y = int(p_temp[1]) ActionChains(web).move_to_element_with_offset(verify_img, p_x, p_y).click().perform() ``` 然后输入用户名和密码, 并点击登录按钮 ```python time.sleep(1) web.find_element_by_xpath('//*[@id="J-userName"]').send_keys("homexue@126.com") web.find_element_by_xpath('//*[@id="J-password"]').send_keys('错误') time.sleep(1) web.find_element_by_xpath('//*[@id="J-login"]').click() ``` 最后一步, 进入滑块环节, 这里其实看似容易, 操作起来就恶心了. 因为这里才是本节真正要讲的. 12306会在这里进行浏览器验证, 验证你是否是通过自动化工具启动的浏览器. 而且, 这个问题非常恶心, 常规的浏览器检测处理方案都是没用的. <img src="image-20210206161410482.png" alt="image-20210206161410482" style="zoom:25%;" /> 注意, 此时我们要了解一下这个插件的工作机制. 它是在整个页面加载的时候就开始对浏览器参数进行读取. 所以我们常规的对Chrome设置是无效的. 此时, 需要添加以下一段代码来规避检测. ``` # 亲测, 88版本以后可以用. option = Options() # option.add_experimental_option('excludeSwitches', ['enable-automation']) option.add_argument('--disable-blink-features=AutomationControlled') web = Chrome(options=option) # 亲测, 88版本之前可以用. # web = Chrome() # # web.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", { # "source": """ # navigator.webdriver = undefined # Object.defineProperty(navigator, 'webdriver', { # get: () => undefined # }) # """ # }) ``` 最后给出完整代码 ```python from selenium.webdriver import Chrome from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.action_chains import ActionChains from chaojiying import Chaojiying_Client import time chaojiying = Chaojiying_Client('xxxxxxx', 'xxxxxx', 'xxxx') # result = chaojiying.PostPic(png_code_img, 9004) # 亲测, 88版本以后可以用. option = Options() # option.add_experimental_option('excludeSwitches', ['enable-automation']) option.add_argument('--disable-blink-features=AutomationControlled') web = Chrome(options=option) # 亲测, 88版本之前可以用. # web = Chrome() # # web.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", { # "source": """ # navigator.webdriver = undefined # Object.defineProperty(navigator, 'webdriver', { # get: () => undefined # }) # """ # }) web.get("https://kyfw.12306.cn/otn/resources/login.html") time.sleep(1) web.find_element_by_xpath('/html/body/div[2]/div[2]/ul/li[2]/a').click() time.sleep(1) verify_img = web.find_element_by_xpath('//*[@id="J-loginImg"]') result = chaojiying.PostPic(verify_img.screenshot_as_png, 9004) points_str_lst = result['pic_str'].split("|") for p in points_str_lst: p_temp = p.split(",") p_x = int(p_temp[0]) p_y = int(p_temp[1]) ActionChains(web).move_to_element_with_offset(verify_img, p_x, p_y).click().perform() time.sleep(1) web.find_element_by_xpath('//*[@id="J-userName"]').send_keys("xxxxxxx@126.com") web.find_element_by_xpath('//*[@id="J-password"]').send_keys('xxxxxxx') time.sleep(1) web.find_element_by_xpath('//*[@id="J-login"]').click() time.sleep(3) btn = web.find_element_by_xpath('//*[@id="nc_1_n1z"]') ActionChains(web).drag_and_drop_by_offset(btn, 300, 0).perform() ``` 总结, selenium的使用方案一般是: 1. 涉及登录. 验证码不想搞. 可以考虑用selenium完成登录. 然后提取cookie. 最后用requests发送真正的请求. 2. 涉及频繁的校验验证(例如boss). 直接用selenium提取页面源代码. 叫给lxml处理.
package pt.up.fe.comp2023.visitors; import pt.up.fe.comp.jmm.analysis.table.Symbol; import pt.up.fe.comp.jmm.ast.AJmmVisitor; import pt.up.fe.comp.jmm.ast.JmmNode; import pt.up.fe.comp2023.SymbolTable; import pt.up.fe.comp2023.node.information.Method; import pt.up.fe.comp2023.utils.ExpressionVisitorInformation; import pt.up.fe.comp2023.utils.SymbolInfo; import pt.up.fe.comp2023.utils.SymbolPosition; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class ExpressionVisitor extends AJmmVisitor<String, ExpressionVisitorInformation> { private final SymbolTable symbolTable; private Integer currentAuxVariable; private Integer usedAuxVariables; public ExpressionVisitor(SymbolTable symbolTable, Integer startingAuxVariable) { this.symbolTable = symbolTable; this.currentAuxVariable = startingAuxVariable; this.usedAuxVariables = 0; } // Utility methods private String getNewAuxVariable() { String ret = "aux" + this.currentAuxVariable; this.currentAuxVariable++; this.usedAuxVariables++; return ret; } private String getCurrentAuxVar() { return "aux" + (this.currentAuxVariable-1); } private ExpressionVisitorInformation visitExpressionAndStoreInfo(ExpressionVisitorInformation storage, JmmNode toVisit, String methodName) { ExpressionVisitorInformation exprNodeInfo = visit(toVisit, methodName); storage.addAuxLines(exprNodeInfo.getAuxLines()); return exprNodeInfo; } private String getImportedMethodReturnType(JmmNode methodCallNode, String outerMethodName) { JmmNode parent = methodCallNode.getJmmParent(); Optional<Method> optMethod = this.symbolTable.getMethodTry(outerMethodName); if (optMethod.isEmpty()) { System.err.println("Tried to find outer method '" + outerMethodName + "' in symbol table but it couldn't be found!"); return "getImportedMethodReturnType error: outer method \"" + outerMethodName + "\" not found"; } switch (parent.getKind()) { case "SimpleStatement" -> { return "V"; } case "ClassFieldAssignment" -> { String fieldName = parent.getJmmChild(0).get("varName"); for (var field : symbolTable.getFields()) { if (field.getName().equals(fieldName)) return OllirGenerator.jmmTypeToOllirType(field.getType(), symbolTable.getClassName()); } return "BIGERROR"; } case "Assignment" -> { String varName = parent.get("varName"); SymbolInfo symbolInfo = symbolTable.getMostSpecificSymbol(outerMethodName, varName); return OllirGenerator.jmmTypeToOllirType(symbolInfo.getSymbol().getType(), symbolTable.getClassName()); } case "ArrayAssignment" -> { String varName = parent.get("varName"); SymbolInfo symbolInfo = symbolTable.getMostSpecificSymbol(outerMethodName, varName); return OllirGenerator.getArrayOllirType(symbolInfo.getSymbol().getType(), symbolTable.getClassName()); } case "MethodCall" -> { return getImportedMethodRootType(methodCallNode, outerMethodName); } case "ArrayAccess", "ArrayInstantiation" -> { return "i32"; } default -> { return "HUGEERROR"; } } } public String getImportedMethodRootType(JmmNode exprStatement, String methodName) { JmmNode current = exprStatement; while (true) { JmmNode leftChild = current.getJmmChild(0); if (leftChild.getKind().equals("Identifier")) { Optional<SymbolInfo> symbolInfo = symbolTable.getMostSpecificSymbolTry(methodName, leftChild.get("value")); return symbolInfo.map(info -> OllirGenerator.jmmTypeToOllirType(info.getSymbol().getType(), "errorInGetImportedMethodRootType")).orElseGet(() -> leftChild.get("value")); } current = leftChild; } } /** * Given an Expression#MethodCall or Expression#ThisMethodCall, gets its children parameter nodes * and appends their name and type to line, comma separated. Starts off with a comma if at least one element is to * be appended. * * @param node The JmmNode that has the parameter children. Should be an * Expression#MethodCall or Expression#ThisMethodCall * @param parentMethodName The method in which this node is in * @param ret The callee's return variable, should be of type ExpressionVisitorInformation * @param line The StringBuilder line to which the parameters will be appended to */ private void getAndAppendParamsCommaSep(JmmNode node, String parentMethodName, ExpressionVisitorInformation ret, StringBuilder line) { int startingIndex = node.getKind().equals("MethodCall") ? 1 : 0; List<JmmNode> parameterExpressions = (node.getChildren().size() >= startingIndex) ? node.getChildren().subList(startingIndex, node.getChildren().size()) : new ArrayList<>(); for (JmmNode childNode : parameterExpressions) { ExpressionVisitorInformation paramExprInfo = visit(childNode, parentMethodName); ret.addAuxLines(paramExprInfo.getAuxLines()); line.append(", ").append(paramExprInfo.getResultNameAndType()); } } private boolean isDeclaredClassInstance(ExpressionVisitorInformation calledMethodsObj, String parentMethodName) { Optional<SymbolInfo> symbolInfoOpt = symbolTable.getMostSpecificSymbolTry(parentMethodName, calledMethodsObj.getResultName()); if (symbolInfoOpt.isEmpty()) { return false; } SymbolInfo symbolInfo = symbolInfoOpt.get(); return symbolInfo.getSymbol().getType().getName().equals(symbolTable.getClassName()); } private boolean isImportedClass(ExpressionVisitorInformation calledMethodsObj) { return symbolTable.getImportedClasses().contains(calledMethodsObj.getResultName()); } private boolean parentNodeIsSimpleStatement(JmmNode currentNode) { return currentNode.getJmmParent().getKind().equals("SimpleStatement"); } // End Utility methods @Override protected void buildVisitor() { addVisit("MethodCall", this::dealWithGenericMethodCall); addVisit("ThisMethodCall", this::dealWithThisMethodCall); addVisit("ArrayLength", this::dealWithArrayLength); addVisit("ArrayAccess", this::dealWithArrayAccess); addVisit("Parenthesis", this::dealWithParenthesis); addVisit("UnaryBinaryOp", this::dealWithUnaryBoolOp); addVisit("ArithmeticBinaryOp", this::dealWithArithmeticBinaryOp); addVisit("BoolBinaryOp", this::dealWithBoolBinaryOp); addVisit("ArrayInstantiation", this::dealWithArrayInstantiation); addVisit("Instantiation", this::dealWithInstantiation); addVisit("Integer", this::dealWithInteger); addVisit("Boolean", this::dealWithBool); addVisit("Identifier", this::dealWithID); addVisit("ClassAccess", this::dealWithClassAccess); } private void dealWithDeclaredClassStaticMethodCall(JmmNode methodCallNode, ExpressionVisitorInformation calledMethodsObj, ExpressionVisitorInformation parentRet, String parentMethodName) { String calledMethodName = methodCallNode.get("methodName"); // Errors in this phase are NOT handled, should have been caught by semantic analysis Method calledMethod = symbolTable.getMethodOrWarn(calledMethodName, "dealWithThisMethodCall"); String methodType = OllirGenerator.jmmTypeToOllirType(calledMethod.getRetType(), symbolTable.getClassName()); if (methodType.equals("V") || parentNodeIsSimpleStatement(methodCallNode)) { StringBuilder returnLine = new StringBuilder(); returnLine.append("invokestatic(this").append(", \"").append(calledMethod).append("\""); getAndAppendParamsCommaSep(methodCallNode, parentMethodName, parentRet, returnLine); returnLine.append(")"); parentRet.setResultName(returnLine.toString()); parentRet.setOllirType(methodType); return; } String methodCallHolderName = getNewAuxVariable(); StringBuilder storeCallValueLine = new StringBuilder(); storeCallValueLine.append(methodCallHolderName).append(".").append(methodType) .append(" :=.").append(methodType) .append(" invokestatic(this").append(", \"").append(calledMethod).append("\""); getAndAppendParamsCommaSep(methodCallNode, parentMethodName, parentRet, storeCallValueLine); storeCallValueLine.append(").").append(methodType).append(";"); parentRet.addAuxLine(storeCallValueLine.toString()); parentRet.setResultName(methodCallHolderName); parentRet.setOllirType(methodType); } // Will use invokevirtual(name.retType, "funcName"); private void dealWithDeclaredClassInstanceMethodCall(JmmNode methodCallNode, ExpressionVisitorInformation calledMethodsObj, ExpressionVisitorInformation parentRet, String parentMethodName) { String calledMethodName = methodCallNode.get("methodName"); // Errors in this phase are NOT handled, should have been caught by semantic analysis Method calledMethod = symbolTable.getMethodOrWarn(calledMethodName, "dealWithThisMethodCall"); String methodType = OllirGenerator.jmmTypeToOllirType(calledMethod.getRetType(), symbolTable.getClassName()); if (methodType.equals("V") || parentNodeIsSimpleStatement(methodCallNode)) { StringBuilder returnLine = new StringBuilder(); returnLine.append("invokevirtual(").append(calledMethodsObj.getResultNameAndType()).append(", \"").append(calledMethodName).append("\""); getAndAppendParamsCommaSep(methodCallNode, parentMethodName, parentRet, returnLine); returnLine.append(")"); parentRet.setResultName(returnLine.toString()); parentRet.setOllirType(methodType); return; } String methodCallHolderName = getNewAuxVariable(); StringBuilder storeCallValueLine = new StringBuilder(); storeCallValueLine.append(methodCallHolderName).append(".").append(methodType) .append(" :=.").append(methodType) .append(" invokevirtual(").append(calledMethodsObj.getResultNameAndType()).append(", \"").append(calledMethodName).append("\""); getAndAppendParamsCommaSep(methodCallNode, parentMethodName, parentRet, storeCallValueLine); storeCallValueLine.append(").").append(methodType).append(";"); parentRet.addAuxLine(storeCallValueLine.toString()); parentRet.setResultName(methodCallHolderName); parentRet.setOllirType(methodType); } private void dealWithImportedClassInstanceMethodCall(JmmNode methodCallNode, ExpressionVisitorInformation calledMethodsObj, ExpressionVisitorInformation parentRet, String parentMethodName) { String calledMethodName = methodCallNode.get("methodName"); String methodType = getImportedMethodReturnType(methodCallNode, parentMethodName); if (methodType.equals("V") || parentNodeIsSimpleStatement(methodCallNode)) { StringBuilder returnLine = new StringBuilder(); returnLine.append("invokevirtual(").append(calledMethodsObj.getResultNameAndType()).append(", \"").append(calledMethodName).append("\""); getAndAppendParamsCommaSep(methodCallNode, parentMethodName, parentRet, returnLine); returnLine.append(")"); parentRet.setResultName(returnLine.toString()); parentRet.setOllirType(methodType); return; } StringBuilder params = new StringBuilder(); getAndAppendParamsCommaSep(methodCallNode, parentMethodName, parentRet, params); String methodCallHolderName = getNewAuxVariable(); String storeCallValueLine = methodCallHolderName + "." + methodType + " :=." + methodType + " invokevirtual(" + calledMethodsObj.getResultNameAndType() + ", \"" + calledMethodName + "\"" + params + ")." + methodType + ";"; parentRet.addAuxLine(storeCallValueLine); parentRet.setResultName(methodCallHolderName); parentRet.setOllirType(methodType); } private void dealWithImportedClassStaticMethodCall(JmmNode methodCallNode, ExpressionVisitorInformation calledMethodsObj, ExpressionVisitorInformation parentRet, String parentMethodName) { String calledMethodName = methodCallNode.get("methodName"); String methodType = getImportedMethodReturnType(methodCallNode, parentMethodName); if (methodType.equals("V") || parentNodeIsSimpleStatement(methodCallNode)) { StringBuilder returnLine = new StringBuilder(); returnLine.append("invokestatic(").append(calledMethodsObj.getResultName()).append(", \"").append(calledMethodName).append("\""); getAndAppendParamsCommaSep(methodCallNode, parentMethodName, parentRet, returnLine); returnLine.append(")"); parentRet.setResultName(returnLine.toString()); parentRet.setOllirType(methodType); return; } String methodCallHolderName = getNewAuxVariable(); StringBuilder storeCallValueLine = new StringBuilder(); storeCallValueLine.append(methodCallHolderName).append(".").append(methodType) .append(" :=.").append(methodType) .append(" invokestatic(").append(calledMethodsObj.getResultName()).append(", \"").append(calledMethodName).append("\""); getAndAppendParamsCommaSep(methodCallNode, parentMethodName, parentRet, storeCallValueLine); storeCallValueLine.append(").").append(methodType).append(";"); parentRet.addAuxLine(storeCallValueLine.toString()); parentRet.setResultName(methodCallHolderName); parentRet.setOllirType(methodType); } private ExpressionVisitorInformation dealWithGenericMethodCall(JmmNode methodCallNode, String parentMethodName) { ExpressionVisitorInformation evInfoRet = new ExpressionVisitorInformation(); JmmNode calledMethodsObjNode = methodCallNode.getJmmChild(0); ExpressionVisitorInformation calledMethodsObj = visitExpressionAndStoreInfo(evInfoRet, calledMethodsObjNode, parentMethodName); if (calledMethodsObj.getResultName().equals(symbolTable.getClassName())) { dealWithDeclaredClassStaticMethodCall(methodCallNode, calledMethodsObj, evInfoRet, parentMethodName); } else if (isDeclaredClassInstance(calledMethodsObj, parentMethodName)) { dealWithDeclaredClassInstanceMethodCall(methodCallNode, calledMethodsObj, evInfoRet, parentMethodName); } else if (isImportedClass(calledMethodsObj)) { dealWithImportedClassStaticMethodCall(methodCallNode, calledMethodsObj, evInfoRet, parentMethodName); } else if (symbolTable.symbolIsDeclared(parentMethodName, calledMethodsObj.getResultName(), getCurrentAuxVar())) { dealWithImportedClassInstanceMethodCall(methodCallNode, calledMethodsObj, evInfoRet, parentMethodName); } else { System.err.println("dealWithGenericMethodCall could not determine which kind of method call this is."); } return evInfoRet; } private ExpressionVisitorInformation dealWithThisMethodCall(JmmNode methodCallNode, String parentMethodName) { ExpressionVisitorInformation retInfo = new ExpressionVisitorInformation(); String calledMethodName = methodCallNode.get("methodName"); // Errors in this phase are NOT handled, should have been caught by semantic analysis Method calledMethod = symbolTable.getMethodOrWarn(calledMethodName, "dealWithThisMethodCall"); String methodType = OllirGenerator.jmmTypeToOllirType(calledMethod.getRetType(), symbolTable.getClassName()); StringBuilder params = new StringBuilder(); getAndAppendParamsCommaSep(methodCallNode, parentMethodName, retInfo, params); String methodCallHolderName = getNewAuxVariable(); StringBuilder storeCallValueLine = new StringBuilder(); storeCallValueLine.append(methodCallHolderName).append(".").append(methodType) .append(" :=.").append(methodType) .append(" invokevirtual(").append("this").append(", \"").append(calledMethod.getName()).append("\""); storeCallValueLine.append(params); storeCallValueLine.append(").").append(methodType).append(";"); retInfo.addAuxLine(storeCallValueLine.toString()); retInfo.setResultName(methodCallHolderName); retInfo.setOllirType(methodType); return retInfo; } private Boolean isNonStaticMethod() { return true; } /* arraylength($1.A.array.i32).i32 ---- arraylength( -- ExprName.Type -- ) .i32 */ private ExpressionVisitorInformation dealWithArrayLength(JmmNode node, String methodName) { String newAuxVar = getNewAuxVariable(); StringBuilder lastAuxLine = new StringBuilder(newAuxVar).append(".i32 :=.i32 arraylength("); //-- variable inside parenthesis ExpressionVisitorInformation ret = new ExpressionVisitorInformation(); JmmNode exprNode = node.getObject("array", JmmNode.class); var exprNodeInfo = visitExpressionAndStoreInfo(ret, exprNode, methodName); lastAuxLine.append(exprNodeInfo.getResultNameAndType()).append(").i32;"); ret.addAuxLine(lastAuxLine.toString()); //-- return type ret.setResultName(newAuxVar); ret.setOllirType("i32"); return ret; } /* $1.A[i.i32].i32; ---- ExprName -- [ -- ExprName.Type -- ] -- . Type */ private ExpressionVisitorInformation dealWithArrayAccess(JmmNode node, String methodName) { StringBuilder retName = new StringBuilder(); ExpressionVisitorInformation ret = new ExpressionVisitorInformation(); JmmNode arrayNode = node.getJmmChild(0); JmmNode indexNode = node.getJmmChild(1); ExpressionVisitorInformation arrayExprInfo = visitExpressionAndStoreInfo(ret, arrayNode, methodName); ExpressionVisitorInformation indexExprInfo = visitExpressionAndStoreInfo(ret, indexNode, methodName); if (node.getJmmChild(0).getKind().equals("Identifier")) { String arrayName = node.getJmmChild(0).get("value"); SymbolInfo arrayVarInfo = symbolTable.getMostSpecificSymbol(methodName, arrayExprInfo.getResultName()); if (arrayVarInfo != null && arrayVarInfo.getSymbolPosition().equals(SymbolPosition.FIELD)) { String newAuxVar = getNewAuxVariable(); StringBuilder getFieldAuxLine = new StringBuilder(newAuxVar); String arrayOllirType = OllirGenerator.jmmTypeToOllirType(arrayVarInfo.getSymbol().getType(), symbolTable.getClassName()); getFieldAuxLine.append(".").append(arrayOllirType).append(" :=.").append(arrayOllirType).append(" getfield(").append("this").append(", ").append(arrayName).append(".").append(arrayOllirType).append(").").append(arrayOllirType).append(";"); ret.addAuxLine(getFieldAuxLine.toString()); retName.append(newAuxVar); } else { retName.append(arrayExprInfo.getResultName()); } } else { retName.append(arrayExprInfo.getResultName()); } //-- [ ExprName.Type ] String lastAuxVar = getNewAuxVariable(); StringBuilder lastAuxLine = new StringBuilder(lastAuxVar); String arrayOllirType = arrayExprInfo.getOllirType(); if (arrayOllirType.contains("array.")) { arrayOllirType = arrayOllirType.substring(arrayOllirType.indexOf("array.") + 6); } lastAuxLine.append(".").append(arrayOllirType).append(" :=.").append(arrayOllirType).append(" ").append(retName).append("[").append(indexExprInfo.getResultNameAndType()).append("].").append(arrayOllirType).append(";"); ret.addAuxLine(lastAuxLine.toString()); //-- ret.setResultName(lastAuxVar); ret.setOllirType(arrayOllirType); return ret; } private ExpressionVisitorInformation dealWithParenthesis(JmmNode node, String methodName) { JmmNode innerExprNode = node.getJmmChild(0); return visit(innerExprNode, methodName); } private ExpressionVisitorInformation dealWithUnaryBoolOp(JmmNode node, String methodName) { ExpressionVisitorInformation ret = new ExpressionVisitorInformation(true); JmmNode expressionNode = node.getObject("bool", JmmNode.class); ExpressionVisitorInformation exprInfo = visitExpressionAndStoreInfo(ret, expressionNode, methodName); String newAuxVar = getNewAuxVariable(); String lastAuxLine = newAuxVar + ".bool :=.bool !.bool " + exprInfo.getResultNameAndType() + ";"; ret.addAuxLine(lastAuxLine); ret.setResultName(newAuxVar); ret.setOllirType("bool"); return ret; } private ExpressionVisitorInformation dealWithArithmeticBinaryOp(JmmNode node, String methodName) { ExpressionVisitorInformation ret = new ExpressionVisitorInformation(); JmmNode arg1Node = node.getJmmChild(0); JmmNode arg2Node = node.getJmmChild(1); String opAndType = node.get("op") + ".i32 "; ExpressionVisitorInformation arg1Info = visitExpressionAndStoreInfo(ret, arg1Node, methodName); ExpressionVisitorInformation arg2Info = visitExpressionAndStoreInfo(ret, arg2Node, methodName); String lastAuxVar = getNewAuxVariable(); String type = "i32"; String lastAuxLine = lastAuxVar + "." + type + " :=." + type + " " + arg1Info.getResultNameAndType() + " " + opAndType + arg2Info.getResultNameAndType() + ";"; ret.addAuxLine(lastAuxLine); ret.setResultName(lastAuxVar); ret.setOllirType(type); return ret; } private ExpressionVisitorInformation dealWithBoolBinaryOp(JmmNode node, String methodName) { ExpressionVisitorInformation ret = new ExpressionVisitorInformation(); JmmNode arg1Node = node.getJmmChild(0); JmmNode arg2Node = node.getJmmChild(1); String opAndType = node.get("op") + ".bool "; ExpressionVisitorInformation arg1Info = visitExpressionAndStoreInfo(ret, arg1Node, methodName); ExpressionVisitorInformation arg2Info = visitExpressionAndStoreInfo(ret, arg2Node, methodName); String lastAuxVar = getNewAuxVariable(); String type = "bool"; String lastAuxLine = lastAuxVar + "." + type + " :=." + type + " " + arg1Info.getResultNameAndType() + " " + opAndType + arg2Info.getResultNameAndType() + ";"; System.out.println("lastAuxLine: " + lastAuxLine); ret.addAuxLine(lastAuxLine); ret.setResultName(lastAuxVar); ret.setOllirType(type); return ret; } /* new int[A.length] -> new(array, t1.i32).array.i32 new(array, expr.type).array.type; */ private ExpressionVisitorInformation dealWithArrayInstantiation(JmmNode node, String methodName) { StringBuilder retName = new StringBuilder("new(array, "); ExpressionVisitorInformation ret = new ExpressionVisitorInformation(); String ollirTypeName = OllirGenerator.jmmTypeToOllirType(node.get("typeName"), symbolTable.getClassName(), true); JmmNode sizeExpression = node.getObject("size", JmmNode.class); ExpressionVisitorInformation sizeInfo = visitExpressionAndStoreInfo(ret, sizeExpression, methodName); String newAuxVar = getNewAuxVariable(); StringBuilder lastAuxLine = new StringBuilder(newAuxVar); lastAuxLine.append(".array.").append(ollirTypeName).append(" :=.array.").append(ollirTypeName) .append(" new(array, ").append(sizeInfo.getResultNameAndType()).append(").array.").append(ollirTypeName).append(";"); ret.addAuxLine(lastAuxLine.toString()); ret.setResultName(newAuxVar); ret.setOllirType("array." + ollirTypeName); return ret; } private ExpressionVisitorInformation dealWithInstantiation(JmmNode node, String methodName) { StringBuilder retName = new StringBuilder("new("); ExpressionVisitorInformation ret = new ExpressionVisitorInformation(); String ollirTypeName = OllirGenerator.jmmTypeToOllirType(node.get("name"), symbolTable.getClassName(), false); retName.append(ollirTypeName).append(")"); ret.setResultName(retName.toString()); ret.setOllirType(ollirTypeName); return ret; } private ExpressionVisitorInformation dealWithInteger(JmmNode node, String methodName) { ExpressionVisitorInformation ret = new ExpressionVisitorInformation(); String value = node.get("value"); ret.setResultName(value); ret.setOllirType("i32"); return ret; } private ExpressionVisitorInformation dealWithBool(JmmNode node, String methodName) { ExpressionVisitorInformation ret = new ExpressionVisitorInformation(); String value = node.get("value"); ret.setResultName(value); ret.setOllirType("bool"); return ret; } private ExpressionVisitorInformation dealWithID(JmmNode node, String methodName) { ExpressionVisitorInformation ret = new ExpressionVisitorInformation(); String value = node.get("value"); Optional<Method> optMethod = this.symbolTable.getMethodTry(methodName); if (optMethod.isEmpty()) { System.err.println("Tried to search for method '" + methodName + "' but it wasn't found."); return ret; } Method method = optMethod.get(); Optional<SymbolInfo> symbolInfoOpt = this.symbolTable.getMostSpecificSymbolTry(methodName, value); if (symbolInfoOpt.isEmpty()) { ret.setResultName(value); ret.setOllirType(value); return ret; } SymbolInfo symbolInfo = symbolInfoOpt.get(); switch (symbolInfo.getSymbolPosition()) { case LOCAL -> { ret.setResultName(symbolInfo.getSymbol().getName()); ret.setOllirType(OllirGenerator.jmmTypeToOllirType(symbolInfo.getSymbol().getType(), symbolTable.getClassName())); } case PARAM -> { for (int i = 0; i < method.getArguments().size(); i++) { Symbol param = method.getArguments().get(i); if (param.getName().equals(value)) { // removed $i.jmmVarName because apparently it's optional ret.setResultName(value); ret.setOllirType(OllirGenerator.jmmTypeToOllirType(param.getType(), symbolTable.getClassName())); } } } case FIELD -> { for (Symbol field : symbolTable.getFields()) { if (field.getName().equals(value)) { String varAux = getNewAuxVariable(); String fieldType = OllirGenerator.jmmTypeToOllirType(symbolInfo.getSymbol().getType(), symbolTable.getClassName()); String auxLine = varAux + "." + fieldType + " :=." + fieldType + " getfield(this, " + field.getName() + "." + fieldType + ")." + fieldType + ";"; ret.addAuxLine(auxLine); ret.setResultName(varAux); ret.setOllirType(fieldType); } } } } return ret; } private ExpressionVisitorInformation dealWithClassAccess(JmmNode node, String methodName) { ExpressionVisitorInformation ret = new ExpressionVisitorInformation(); ret.setResultName("this"); String type = symbolTable.getClassName(); ret.setOllirType(type); return ret; } public Integer getUsedAuxVariables() { return usedAuxVariables; } }
//{ Driver Code Starts import java.io.*; import java.lang.*; import java.util.*; class Job { int id, profit, deadline; Job(int x, int y, int z){ this.id = x; this.deadline = y; this.profit = z; } } class GfG { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //testcases int t = Integer.parseInt(br.readLine().trim()); while(t-->0){ String inputLine[] = br.readLine().trim().split(" "); //size of array int n = Integer.parseInt(inputLine[0]); Job[] arr = new Job[n]; inputLine = br.readLine().trim().split(" "); //adding id, deadline, profit for(int i=0, k=0; i<n; i++){ arr[i] = new Job(Integer.parseInt(inputLine[k++]), Integer.parseInt(inputLine[k++]), Integer.parseInt(inputLine[k++])); } Solution ob = new Solution(); //function call int[] res = ob.JobScheduling(arr, n); System.out.println (res[0] + " " + res[1]); } } } // } Driver Code Ends class Solution { //Function to find the maximum profit and the number of jobs done. int[] JobScheduling(Job arr[], int n) { Arrays.sort(arr,(a,b) -> b.profit - a.profit); // sort the array in decending order . . . int maxi = 0; for(int i=0;i<arr.length;i++){ maxi = Math.max(maxi , arr[i].deadline); } int[] deadlineArr = new int[maxi + 1]; Arrays.fill(deadlineArr,-1); int noOfJobs = 0 , maxProfit = 0; for(int i=0;i<arr.length;++i){ for(int j=arr[i].deadline;j>0;--j){ if(deadlineArr[j] == -1){ deadlineArr[j] = i; noOfJobs++; maxProfit += arr[i].profit; break; } } } return new int[]{noOfJobs,maxProfit}; } } /* class Job { int id, profit, deadline; Job(int x, int y, int z){ this.id = x; this.deadline = y; this.profit = z; } } */
"use client"; import React, { useEffect, useState } from "react"; import { useRouter } from "next/navigation"; import Navbar from "../../../components/nav/Navbar"; import { fetchCourseData, courseData, fetchCourses, fetchCourseVisualData, } from "@/app/utils/CourseUtils"; import { Label } from "@/app/components/ui/label"; import { Popover, PopoverTrigger, PopoverContent, } from "@/app/components/ui/popover"; import { ChevronDown, X } from "lucide-react"; import { RadioGroup, RadioGroupItem } from "@/app/components/ui/radio"; import { ArrowLeft } from "lucide-react"; import { WordCloudChart } from "@carbon/charts-react"; import "@carbon/charts-react/styles.css"; import { wordCloudData } from "@/app/utils/SummaryUtils"; import { useToast } from "@/app/components/ui/use-toast"; import { ScrollArea } from "@/app/components/ui/scroll-area"; export default function Page({ params, }: { params: { code: string; year: string }; }) { const { toast } = useToast(); const router = useRouter(); const [courseData, setCourseData] = useState<courseData | undefined>( undefined ); const [courseVisualData, setCourseVisualData] = useState< wordCloudData[] | undefined >(undefined); const [availableYrs, setAvailableYears] = useState<string[]>([]); useEffect(() => { const fetchData = []; fetchData.push( fetchCourseData( { code: params.code, year: params.year }, (courseRes) => { setCourseData(courseRes.course); }, (error) => { toast({ variant: "destructive", title: "Error", description: error, }); } ) ); fetchData.push( fetchCourseVisualData( { code: params.code, year: params.year }, (courseRes) => { let summaryValues = courseRes.summary.map((x) => { return { word: x.phrase, value: x.score, group: x.source }; }); setCourseVisualData(summaryValues); }, (error) => { toast({ variant: "destructive", title: "Error", description: error, }); } ) ); fetchData.push( fetchCourses( (res) => { const versions = res.courses.filter((x) => x.code === params.code); const availableYrs = []; for (const version of versions) { version.year && availableYrs.push(version.year); } setAvailableYears(availableYrs); }, (error) => { toast({ variant: "destructive", title: "Error", description: error, }); } ) ); Promise.all(fetchData); }, [params.code, params.year]); return ( <div className="flex flex-col items-center"> <Navbar /> <div className="lg:w-[60rem] md:w-[45rem] xs:w-screen xs:mx-4 mt-12 flex flex-col md:flex-row px-4"> <ArrowLeft className="w-4 md:w-6 mr-6 mt-2 ml-4 hover:text-slate-400 hover:cursor-pointer" strokeWidth={2.25} onClick={() => { router.back(); }} /> <div className="flex flex-col xs:w-1/2 md:w-2/3 md:pr-12 mx-4 "> <div> <div className="text-xl sm:text-3xl lg:text-4xl font-bold pb-4"> {courseData?.code} </div> <div className="flex gap-6 items-end justify-between md:pr-6 mb-6"> <div className="text-base sm:text-lg lg:text-2xl font-bold"> {courseData?.title} </div> <div className="text-sm sm:text-md lg:text-xl font-semibold"> {availableYrs.length === 1 ? ( params.year ) : ( <Popover> <PopoverTrigger asChild> <div className="flex items-end hover:cursor-pointer"> {params.year} <ChevronDown className="w-4 md:w-6" /> </div> </PopoverTrigger> <PopoverContent className="w-auto pr-24 pl-6 py-4"> <div> <Label htmlFor="course-version-selector">Year</Label> <RadioGroup defaultValue={`option-${params.year}`} onValueChange={(v) => { v = v.replace("option-", ""); router.push(`/courses/${v}/${params.code}`); }} > {availableYrs.sort().map((yr) => { return ( <div className="flex items-center space-x-2" key={yr} > <RadioGroupItem value={`option-${yr}`} id={`option-${yr}`} /> <Label htmlFor={`option-${yr}`}>{yr}</Label> </div> ); })} </RadioGroup> </div> </PopoverContent> </Popover> )} </div> </div> </div> <ScrollArea className={ "md:h-[30rem]md:pr-2 mt-0 sm:mt-2 lg:mt-6 text-xs sm:text-base lg:text-base xl:text-lg" } > {courseData?.summary} </ScrollArea> </div> <div className="flex flex-col w-screen xs:w-1/2 md:w-1/3 h-1/4 ml-0 px-4 md:px-0 lg:ml-6 mt-6"> {courseVisualData && ( <WordCloudChart data={courseVisualData} options={{ title: params.code, resizable: true, legend: { enabled: false, }, wordCloud: {}, height: "35rem", }} /> )} </div> </div> </div> ); }
--- permalink: expansion/concept_configuring_node_management_lifs.html sidebar: sidebar keywords: controller, module, physical, install, power, configure, node-mangement, lif, configure node-management lifs summary: "After the controller modules are physically installed, you can power on each one and configure its node-management LIF." --- = Configure node-management LIFs :icons: font :imagesdir: ../media/ [.lead] After the controller modules are physically installed, you can power on each one and configure its node-management LIF. .About this task You must perform this procedure on both the nodes. .Steps . Access the controller module through the serial console. . Power on the controller module, and wait while the node boots and the Cluster Setup wizard automatically starts on the console. + ---- Welcome to the cluster setup wizard. You can enter the following commands at any time: "help" or "?" - if you want to have a question clarified, "back" - if you want to change previously answered questions, and "exit" or "quit" - if you want to quit the cluster setup wizard. Any changes you made before quitting will be saved. You can return to cluster setup at any time by typing "cluster setup". To accept a default or omit a question, do not enter a value. ---- . Follow the prompts in the web-based Cluster Setup wizard to configure a node management LIF using the networking information you gathered earlier. . Type `exit` after node management LIF configuration is complete to exit the setup wizard and complete the administration tasks. + ---- Use your web browser to complete cluster setup by accessing https://10.63.11.29 Otherwise, press Enter to complete cluster setup using the command line interface: exit ---- . Log in to the node as the `admin` user, which does not require a password. + ---- Tue Mar 4 23:13:33 UTC 2015 login: admin ****************************************************** * This is a serial console session. Output from this * * session is mirrored on the SP console session. * ---- . Repeat the entire procedure for the second newly installed controller module.
import { Injectable } from '@angular/core'; import { HttpClient, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs'; import { isPresent } from 'app/core/util/operators'; import { ApplicationConfigService } from 'app/core/config/application-config.service'; import { createRequestOption } from 'app/core/request/request-util'; import { ISupplier, getSupplierIdentifier } from '../supplier.model'; export type EntityResponseType = HttpResponse<ISupplier>; export type EntityArrayResponseType = HttpResponse<ISupplier[]>; @Injectable({ providedIn: 'root' }) export class SupplierService { protected resourceUrl = this.applicationConfigService.getEndpointFor('api/suppliers'); constructor(protected http: HttpClient, protected applicationConfigService: ApplicationConfigService) {} create(supplier: ISupplier): Observable<EntityResponseType> { return this.http.post<ISupplier>(this.resourceUrl, supplier, { observe: 'response' }); } update(supplier: ISupplier): Observable<EntityResponseType> { return this.http.put<ISupplier>(`${this.resourceUrl}/${getSupplierIdentifier(supplier) as number}`, supplier, { observe: 'response' }); } partialUpdate(supplier: ISupplier): Observable<EntityResponseType> { return this.http.patch<ISupplier>(`${this.resourceUrl}/${getSupplierIdentifier(supplier) as number}`, supplier, { observe: 'response', }); } find(id: number): Observable<EntityResponseType> { return this.http.get<ISupplier>(`${this.resourceUrl}/${id}`, { observe: 'response' }); } query(req?: any): Observable<EntityArrayResponseType> { const options = createRequestOption(req); return this.http.get<ISupplier[]>(this.resourceUrl, { params: options, observe: 'response' }); } delete(id: number): Observable<HttpResponse<{}>> { return this.http.delete(`${this.resourceUrl}/${id}`, { observe: 'response' }); } addSupplierToCollectionIfMissing(supplierCollection: ISupplier[], ...suppliersToCheck: (ISupplier | null | undefined)[]): ISupplier[] { const suppliers: ISupplier[] = suppliersToCheck.filter(isPresent); if (suppliers.length > 0) { const supplierCollectionIdentifiers = supplierCollection.map(supplierItem => getSupplierIdentifier(supplierItem)!); const suppliersToAdd = suppliers.filter(supplierItem => { const supplierIdentifier = getSupplierIdentifier(supplierItem); if (supplierIdentifier == null || supplierCollectionIdentifiers.includes(supplierIdentifier)) { return false; } supplierCollectionIdentifiers.push(supplierIdentifier); return true; }); return [...suppliersToAdd, ...supplierCollection]; } return supplierCollection; } }
%% We are going to analyze the test accuracy across classes here %% 1) Load data dataFolder = "../../../../../../../data/MedNIST"; % Go through every folder (label) and load all images categs = dir(dataFolder); % Initialize vars N = 58954; % total number of images XData = zeros(64, 64, 1, N); % height = width = 64, 10k imgs per class (greyscale) YData = zeros(N, 1); % except BreatMRI, that has only 8954 % Load images count = 1; for i = 3:length(categs)-1 label = dir(dataFolder + "/"+ string(categs(i).name)); for k = 3:length(label) XData(:, :, :, count) = imread([label(k).folder '/' label(k).name]); YData(count) = i-2; count = count + 1; end end % YData = categorical(YData); XData_dl = dlarray(XData, "SSCB"); %% 2) Evaluate all models on the complete dataset % Iterate trhough every folder and subfolder and analyze all the models path = pwd; folders = dir(path); % Skip the first two that appear in every folder and subfolder as those % correspond to (".", and "..") results = zeros(45,58954); % to save the predicted results model_count = 1; accuracy = zeros(45,1); models(45) = string; % Go into every folder of and analyze each model for r = 3:5 % iterate through regularizers (3) sub_path = [path, filesep, folders(r).name, filesep]; inits_path = dir(sub_path); for i = 3:length(inits_path) % go through all initializations (3 x 3) if inits_path(i).isdir temp_path = [sub_path, inits_path(i).name, filesep, 'models', filesep]; models_path = dir([temp_path, '*.mat']); for m = 1:length(models_path) % go through all models ( 5 x 3 x 3 ) netpath = [temp_path, models_path(m).name]; net_info = load(netpath); curr_net = net_info.net; if isa(curr_net, "dlnetwork") yPred = predict(curr_net, XData_dl); [~,predictedLabels] = max(extractdata(yPred)); predictedLabels = predictedLabels'; else predictedLabels = classify(curr_net, XData); predictedLabels = cellfun(@(x) str2double(x), cellstr(predictedLabels)); end acc_labels = predictedLabels == YData; accuracy(model_count) = sum(acc_labels)/N; results(model_count,:) = acc_labels; models(model_count) = models_path(m).name; model_count = model_count + 1; end end end end % 3) Get accuracy statistics per model per class % 6 classes: [Abdominal CT, Breast MRI, Chest CT, cxr , Hand, Head CT] % labels : [ 1 2 3 4 5 6 ] % data indexes abdomen = 1:10000; breast = 10001:18954; chest = 18955:28954; cxr = 28955:38954; hand = 38955:48954; head = 48955:58954; acc_classes = zeros(45,6); for i = 1:45 acc_classes(i,1) = sum(results(i,abdomen)); acc_classes(i,2) = sum(results(i,breast)); acc_classes(i,3) = sum(results(i,chest)); acc_classes(i,4) = sum(results(i,cxr)); acc_classes(i,5) = sum(results(i,hand)); acc_classes(i,6) = sum(results(i,head)); end %% Finally, save images that all models correctly predict to analyze its robustness % we are going to save the first 50 indexes per class that are correctly % classified by all models numClasses = 6; nClassImgs = 50; k = 1; xVerIdxs = zeros(numClasses*nClassImgs,1); % 1) Abdomen xVerIdxs(1:nClassImgs) = findAccData(results, abdomen, nClassImgs); % 2) Breast xVerIdxs(nClassImgs + 1:nClassImgs*2) = findAccData(results, breast, nClassImgs); % 3) chest xVerIdxs(nClassImgs*2+1:nClassImgs*3) = findAccData(results, chest, nClassImgs); % 4) cxr xVerIdxs(nClassImgs*3+1:nClassImgs*4) = findAccData(results, cxr, nClassImgs); % 5) Hand xVerIdxs(nClassImgs*4+1:nClassImgs*5) = findAccData(results, hand, nClassImgs); % 6) Head xVerIdxs(nClassImgs*5+1:nClassImgs*6) = findAccData(results, head, nClassImgs); % Save results and verification image indexes save("acc_results.mat", "xVerIdxs", "results", "acc_classes", "accuracy", "models"); %% Helper Functions function good_idxs = findAccData(res_models,idxs, nVerif) k = 1; ix = idxs(1); good_idxs = zeros(nVerif,1); while k <= nVerif && ix <= idxs(end) if all(res_models(:,ix) == 1) good_idxs(k) = ix; k = k+1; end ix = ix+1; end end
import Box from "@mui/material/Box"; import Button from "@mui/material/Button"; import MenuItem from "@mui/material/MenuItem"; import Select from "@mui/material/Select"; import TextField from "@mui/material/TextField"; import { useState } from "react"; import { useNavigate } from "react-router-dom"; import { SearchType } from "../../config/types/search.type"; import SearchOutlinedIcon from "@mui/icons-material/SearchOutlined"; import InputAdornment from "@mui/material/InputAdornment"; import { blue } from "@mui/material/colors"; import InputLabel from "@mui/material/InputLabel"; import FormControl from "@mui/material/FormControl"; const SearchField = () => { const searchTypeOptions = [ "traveler", "company", "program", "country", "hotel" ]; const [type, setType] = useState<SearchType | null>(searchTypeOptions[0] as SearchType); const [keyword, setKeyword] = useState<string | null>(""); const navigate = useNavigate(); return ( <Box p={1} display={"flex"} alignItems={"flex-end"} sx={{ mx: 0.5 }}> <TextField variant={"outlined"} sx={{ mx: 0.5 }} id="outlined-helperText" label="search keyword" size="small" color="primary" InputProps={{ startAdornment: ( <InputAdornment position="start"> <SearchOutlinedIcon /> </InputAdornment> ) }} value={keyword} onChange={( event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement> ) => setKeyword(event.target.value)} /> <FormControl> <InputLabel id="type-select">Type</InputLabel> <Select sx={{ mx: 0.5 }} id="type-select" size="small" value={type} label="Type" onChange={(event: any) => setType(event.target.value)} > {searchTypeOptions.map((option) => ( <MenuItem key={option} value={option}> {option} </MenuItem> ))} </Select> </FormControl> <Button sx={{ mx: 0.5 }} variant="contained" color="secondary" size="medium" disableElevation onClick={() => { navigate(`/search/${type}?keyword=${keyword}`); setKeyword('') }} > Search </Button> </Box> ); }; export default SearchField;
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:shop_app/const/strings.dart'; import 'package:shop_app/logic/auth.dart'; import 'package:shop_app/logic/notifier.dart'; import 'package:shop_app/router.dart'; import 'package:firebase_core/firebase_core.dart'; import 'firebase_options.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); runApp(MyApp(appRouter: AppRouter())); } class MyApp extends StatelessWidget { final AppRouter appRouter; const MyApp({super.key, required this.appRouter}); // This widget is the root of your application. @override Widget build(BuildContext context) { return Provider<AuthBase>( create: (_)=>Auth(), child: MaterialApp( debugShowCheckedModeBanner: false, title: 'E-commerce App', theme: ThemeData( scaffoldBackgroundColor: const Color(0xffE5E5E5), primaryColor: Colors.red, inputDecorationTheme: InputDecorationTheme( labelStyle: Theme.of(context).textTheme.subtitle1, focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(3), borderSide: const BorderSide(color: Colors.grey), ), disabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(3), borderSide: const BorderSide(color: Colors.grey), ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(3), borderSide: const BorderSide(color: Colors.grey), ), errorBorder:OutlineInputBorder( borderRadius: BorderRadius.circular(3), borderSide: const BorderSide(color: Colors.red), ), focusedErrorBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(3), borderSide: const BorderSide(color: Colors.red), ), ), ), onGenerateRoute: appRouter.generateRoute, initialRoute: landingPageRoute, ), ); } }
import { App, Modal, Plugin, Setting } from "obsidian"; import { Display } from "./display"; import { VendingMachine } from "./vendingMachine"; import { coinIds, coinLabels } from "./coins"; export default class VendingMachinePlugin extends Plugin { async onload() { this.addCommand({ id: "open-vending-machine", name: "Open Vending Machine", callback: () => { new VendingMachineDialog(this.app).open(); }, }); } } export class VendingMachineDialog extends Modal { private _display: Display; private _vendingMachine: VendingMachine = new VendingMachine(new Display()); constructor(app: App) { super(app); this._display = new Display(); this._vendingMachine = new VendingMachine(this._display); } onOpen() { const { contentEl, titleEl } = this; titleEl.setText("Vending Machine"); const display = contentEl.createEl("div", { text: "" }); this._display.showIn(display); const coinSlot = new Setting(contentEl); for (const coinId of coinIds) { coinSlot.addButton((button) => { button.setButtonText(coinLabels[coinId]); button.onClick(() => { this._vendingMachine.insertCoin(coinId); }); }); } } onClose() { const { contentEl } = this; contentEl.empty(); } }
import 'package:carousel_slider/carousel_slider.dart'; import 'package:flutter/material.dart'; import 'package:flutter_grocery_store_admin/view/photo_screen/photo_screen.dart'; import 'package:provider/provider.dart'; import '../../../controller/custom_page_indicator_controller.dart'; import '../../../model/product_model.dart'; import '../../../utils/global_widgets/custom_page_indicartor.dart'; import '../../../utils/global_widgets/my_network_image.dart'; class CarouselImageView extends StatelessWidget { const CarouselImageView({ super.key, required this.item, }); final ProductModel item; @override Widget build(BuildContext context) { return Column( mainAxisSize: MainAxisSize.min, children: [ CarouselSlider.builder( itemCount: item.imageUrl?.length ?? 0, itemBuilder: (context, index, realIndex) => GestureDetector( onTap: () => Navigator.push( context, MaterialPageRoute( builder: (context) => PhotoScreen.network( imageUrlList: item.imageUrl, initialIndex: index, ), )), child: MyNetworkImage( imageUrl: item.imageUrl != null && item.imageUrl!.isNotEmpty ? item.imageUrl![index] : '', ), ), options: CarouselOptions( viewportFraction: 1, enableInfiniteScroll: false, onPageChanged: (index, reason) { context .read<CustomPageIndicatorController>() .setSelectedIndex(index); }, ), ), const SizedBox(height: 10), Consumer<CustomPageIndicatorController>( builder: (BuildContext context, CustomPageIndicatorController value, Widget? child) => CustomPageIndicator( count: item.imageUrl?.length ?? 0, pageIndex: value.selectedIndex, ), ), ], ); } }
# Kotlin 扩展函数与带接收器的函数文字 > 原文:<https://dev.to/frevib/kotlin-extension-function-vs-function-literal-with-receiver-411d> # Kotlin 扩展函数和带接收器的函数文字 在 Kotlin 中,可以向现有类添加一个方法(在 Kotlin 中称为成员函数)。这被称为*扩展函数*。 也有可能从函数文本内部的类中访问成员函数。这被称为带有接收者的*函数。* # 扩展功能 假设您想要向`StringBuilder`类添加一个新的成员函数,例如`appendMonkey()`将字符串“monkey”附加到一个字符串中。因为`StringBuilder`在 Java SDK 中,我们不能修改它。在 Kotlin 中,我们可以定义一个扩展函数,用一个新的成员函数来扩展现有的类,比如`StringBuilder`。 我们将`appendMonkey()`扩展函数定义如下: ``` fun StringBuilder.appendMonkey(): StringBuilder = this.append("monkey") ``` `this`指的是`StringBuilder`对象,我们可以省略: ``` fun StringBuilder.appendMonkey(): StringBuilder = append("monkey") ``` 完整示例: ``` import java.lang.StringBuilder fun main() { val sb = StringBuilder() sb.append("Hello extension function ") sb.appendMonkey() println(sb.toString()) } fun StringBuilder.appendMonkey(): StringBuilder = append("monkey") ``` # 带接收器的函数文字 与*扩展函数*密切相关的是带有接收者的*函数。有两种类型的函数文字:* * 希腊字母的第 11 个 * 匿名函数 实际上,你最有可能[使用 lambda 表达式,所以我们在下面的例子中使用它。](https://kotlinlang.org/docs/reference/lambdas.html#anonymous-functions) 使用扩展函数,你可以在现有的类中添加一个新的成员函数,使用带有接收者的*函数,你可以在*的 lambda 块中(在花括号`{}`中)访问现有类的成员函数*。* 让我们用接收者创建一个*函数文本,它使用`StringBuilder`类将字符串“monkey”添加到一个字符串中。* ``` val lambdaAppendMonkey: StringBuilder.() -> StringBuilder = { this.append("monkey") } ``` 再次,`this`指的是`StringBuilder`对象,所以我们省略: ``` val lambdaAppendMonkey: StringBuilder.() -> StringBuilder = { append("monkey") } ``` 完整示例: ``` import java.lang.StringBuilder fun main() { val lambdaAppendMonkey: StringBuilder.() -> StringBuilder = { append("monkey") } val sb = StringBuilder() sb.append("Hello lambda ") println(lambdaAppendMonkey(sb).toString()) } ``` 在这里,在 lambda 的块内部,我们可以访问`append()`成员函数,因为我们显式地将返回类型声明为`StringBuilder.() -> StringBuilder`。这个返回类型基本上是说: “返回一个不带参数并返回一个`StringBuilder object`、**和**的函数,让这个函数访问`StringBuilder`成员函数”。 祝你好运!
# iam-security-cdk questions IAM Policy Validation Script (CDK) This script utilizes the AWS CDK library to validate IAM roles and policies within your deployment for full access to DynamoDB. It helps prevent accidental deployments granting excessive permissions. Requirements: Node.js and npm installed AWS CDK installed (npm install aws-cdk-lib) Basic understanding of CDK and IAM concepts Deployment: Ensure the script is saved as a .js or .ts file (e.g., iam-policy-validation.js). Deploy the script using the CDK command: Bash cdk deploy <stack_name> -c environment=local content_copy Replace <stack_name> with your desired stack name. The -c environment=local flag specifies deployment to a local mock environment (LocalStack). Functionality: The script retrieves all defined IAM roles and policies within the deployment scope using CDK constructs (optional: replace with retrieving roles/policies from existing infrastructure). It iterates through each role and checks its assumeRolePolicy for statements allowing full DynamoDB access (dynamodb:*). It then iterates through each policy and checks its document for statements allowing full DynamoDB access. If any role or policy grants full DynamoDB access, an error is thrown, blocking the deployment. Pseudocode: Define function validateIAMRoles(roles): Loop through each role in roles: Check if the role's assumeRolePolicy allows dynamodb:* action: If yes, throw an error indicating full DynamoDB access granted by role. Define function validateIAMPolicies(policies): Loop through each policy in policies: Check if the policy document allows dynamodb:* action: If yes, throw an error indicating full DynamoDB access granted by policy. Retrieve all IAM roles and policies from deployment scope (or existing infrastructure). Call validateIAMRoles with retrieved roles. Call validateIAMPolicies with retrieved policies. If no errors are thrown, deployment proceeds. It integrates with Github Actions where its triggered in the infrastructure deployment step and it checks if any IAM policies grant full IAM access to dynamodb tables.If a policy is found the deployment will be halted and an alert will be sent to the team
import { NavLink } from 'react-router-dom' import client1 from '../../assets/client-1.jpg' import client2 from '../../assets/client-2.jpg' import client3 from '../../assets/client-3.jpg' import { motion, useAnimation } from "framer-motion"; import { useEffect } from "react"; const CardServices = () => { const scrollToTop = () => { window.scrollTo(0, 0); // Esto llevará la página al principio }; // Control de animación para las cards const cardAnimation = useAnimation(); // Umbral de desplazamiento para activar las animaciones const scrollThreshold = 200; // Puedes ajustar esto según tus necesidades // Función para manejar el scroll const handleScroll = () => { const scrollY = window.scrollY; if (scrollY > scrollThreshold) { cardAnimation.start({ opacity: 1, y: 0, scale: 1 }); } }; useEffect(() => { // Agregar un event listener para el scroll window.addEventListener("scroll", handleScroll); // Limpiar el event listener cuando el componente se desmonta return () => { window.removeEventListener("scroll", handleScroll); }; }, []); return ( <section className="client" id="card-services"> <div className="section__container client__container"> <h2 className="section__header mt-20">¿En qué te puedo ayudar?</h2> <div className="client__grid"> <motion.div className="client__card" initial={{ opacity: 0, y: 30, scale: 1 }} animate={cardAnimation} // Aplicar animación controlada por cardAnimation exit={{ opacity: 0, y: -30, scale: 1 }} whileHover={{ scale: 1.05 }} transition={{ duration: 0.5 }} > <img src={client1} alt="icono de Wev Developer and SEO Engineer" /> <p> Construcción de tu <b>primera página web</b>. Integración y mejoramiento de SEO para un <span className='text-green-700 font-bold'>óptimo posicionamiento</span> en los principales buscadores. </p> <div className='flex flex-1 justify-center mt-4'> <NavLink to="/portfolio" onClick={scrollToTop}> <button className="px-6 py-2 font-medium bg-emerald-700 text-white w-fit transition-all shadow-[3px_3px_0px_black] hover:shadow-none hover:translate-x-[3px] hover:translate-y-[3px]"> Conoce Mis Proyectos </button> </NavLink> </div> </motion.div> <motion.div className="client__card" initial={{ opacity: 0, y: 30, scale: 1 }} animate={cardAnimation} // Aplicar animación controlada por cardAnimation exit={{ opacity: 0, y: -30, scale: 1 }} whileHover={{ scale: 1.05 }} transition={{ duration: 0.5 }} > <img src={client2} alt="icono de diseño web y adaptabilidad" /> <p> Diseño de Webs y Apps para que el usuario que visite tu plataforma tenga una <span className='text-green-700 font-bold'>experiencia favorable</span> y decida regresar. <b> Interfaz adaptable</b> a cualquier dispositivo, ya sea Celular, PC, Tablet o TV. </p> </motion.div> <motion.div className="client__card" initial={{ opacity: 0, y: 30, scale: 1 }} animate={cardAnimation} // Aplicar animación controlada por cardAnimation exit={{ opacity: 0, y: -30, scale: 1 }} whileHover={{ scale: 1.05 }} transition={{ duration: 0.5 }} > <img src={client3} alt="icono de soporte y mantenimiento web" /> <p> Mantenimiento 24/7 y soporte constante. <br /> <span className='text-blue-700 font-semibold'> ¿Ya contás con una web? </span> <br /> <span className='text-green-700 font-medium underline underline-offset-2'> Vamos a optimizarla. </span> </p> <div className='flex flex-1 justify-center mt-4'> <NavLink to="/services" onClick={scrollToTop}> <button className="px-6 py-2 font-medium bg-emerald-700 text-white w-fit transition-all shadow-[3px_3px_0px_black] hover:shadow-none hover:translate-x-[3px] hover:translate-y-[3px]"> Acerca de mi </button> </NavLink> </div> </motion.div> </div> </div> </section> ); } export default CardServices
package com.hotel.ratingservice.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.hotel.ratingservice.entities.Rating; import com.hotel.ratingservice.service.RatingService; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; @RestController @RequestMapping("/ratings") @NoArgsConstructor @AllArgsConstructor(onConstructor = @__(@Autowired)) public class RatingController { private RatingService ratingService; @PostMapping("/createRating") public ResponseEntity<Rating> createRating(@RequestBody Rating rating){ Rating createdRating = ratingService.createRating(rating); return ResponseEntity.status(HttpStatus.CREATED).body(createdRating); } @GetMapping("/getAllRatings") public ResponseEntity<List<Rating>> getAllRatings(){ List<Rating> ratings = ratingService.getAllRatings(); return ResponseEntity.status(HttpStatus.OK).body(ratings); } @GetMapping("/getRatingByUserId") public List<Rating> getRatingByUserId(@RequestParam Long userId){ return ratingService.getRatingByUserId(userId); } @GetMapping("/getRatingByHotelId") public List<Rating> getRatingByHotelId(@RequestParam Long hotelId){ return ratingService.getRatingByHotelId(hotelId); } }
// *********************************************** // This example commands.js shows you how to // create various custom commands and overwrite // existing commands. // // For more comprehensive examples of custom // commands please read more here: // https://on.cypress.io/custom-commands // *********************************************** // // // -- This is a parent command -- // Cypress.Commands.add('login', (email, password) => { ... }) // // // -- This is a child command -- // Cypress.Commands.add('drag', { prevSubject: 'element'}, (subject, options) => { ... }) // // // -- This is a dual command -- // Cypress.Commands.add('dismiss', { prevSubject: 'optional'}, (subject, options) => { ... }) // // // -- This will overwrite an existing command -- // Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... }) Cypress.Commands.add("loginViaUi", (user) => { cy.get("#username").type(user.username); cy.get("#password").type(user.password); cy.get("[data-test='signin-submit']").click(); cy.get("[data-test='transaction-list']", { timeout: 5000 }).should( "be.visible" ); }); Cypress.Commands.add("transactionFilter", (min, max) => { cy.get("[data-test='transaction-list-filter-amount-range-button']") .scrollIntoView() .click({ force: true }); cy.get("[data-test='transaction-list-filter-amount-range-slider']").click( min * 0.1875, 0 ); cy.get("[data-test='transaction-list-filter-amount-range-slider']").click( max * 0.2, 0 ); }); Cypress.Commands.add("getByDataId", (dataTestid) => { return cy.get(`[data-test=${dataTestid}]`); });
# Honey Haven (Developer: Maksims Buraks) ![Mockup image](docs/am-i-responsive.png) [live web-page](https://honeyhaven-236ab8f8ceba.herokuapp.com/) ## Table of contents - [Honey Haven](#honey-haven) - [Table of contents](#table-of-contents) - [Project Overview](#project-overview) - [Business Model](#business-model) - [Project Goals](#project-goals) - [User Stories](#user-stories) - [Site Owner Stories](#site-owner-stories) - [User Experience](#user-experience) - [Target Audience](#target-audience) - [User Requirements and Expectations](#user-requirements-and-expectations) - [User Stories](#user-stories) - [First-time User](#first-time-user) - [Returning User](#returning-user) - [Site Owner](#site-owner) - [Design](#design) - [Design Choices](#design-choices) - [Kanban-Board](#kanban-board) - [Colour](#colour) - [Fonts](#fonts) - [Structure](#structure) - [Wireframes](#wireframes) - [Tech Used](#tech-used) - [Languages](#languages) - [Tools](#tools) - [Validation](#validation) - [HTML Validation](#html-validation) - [CSS Validation](#css-validation) - [Python Validation](#python-validation) - [JS Validation](#js-validation) - [Tests](#tests) - [Devices tested on on:](#devices-tested-on-on) - [Browser tested on on:](#browser-tested-on-on) - [Bugs](#Bugs) - [Deployment](#deployment) - [Future Features](#future-features) - [Credits](#credits) - [Media](#media) - [Code](#code) - [Acknowledgements](#acknowledgements) ## Project Overview Welcome to Honey Haven, the one stop shop for everything related to natural honey as well as products! This project is essentially a proof of concept that will be worked on, and eventually become a fully fledged e-commerce store. Please note that while products at the moment are limited the end goal is to flesh it out once we determine exact products to be sold! The website is a B2C and B2B model. It provides services to customers through shopping with a quick and easy pathway to purchase. User profiles display previous orders and the ability to save delivery info. The store also allows customers to subscribe to a news letter which in turn allows them to recieve emails updating them on new potential products and/or offers. There is a contact section that allows users to leave a message which will be displayed to the admin panel (future features will include a display of messages in the admin profile with a reply functionality) Admins have the ability to edit/update and delete items. Full editing of the bag items for Users are also available. SEO scores returned high through out as the keywords helped optimize them! ## Business Model # Facebook Page This project utilizes a facebook page to increase the clients reach and influence. It is based in cavan so the target audience would be local but through marketing it would allow to expand it's reach further in Ireland! ![Facebook](docs/honey-haven-fb1.png) ![Facebook](docs/honey-haven-fb2.png) ### SEO For the seo, key words relating to honey, organics and accesories were streamlined. All relevant images have good alts and products have appropriate descriptions, all other content was made sure to not over saturate the website. The goal was to make the objective clear, what we offer and an easy way to access it. ## Project Goals ### User Stories - To View list of Products - To View Details of Products - To View/Update/Delete in bag view - To be able to register - To be able to view profile and update delivery info/view previous orders - To be able to quickly navigate/search/sort products - To be able to quickly reach checkout without any issues - To have secure payment - To be able to see order confirmation via view and email - To be able to get in contact - To be able to subscribe to a newsletter service to keep up to date on offers ### Site Owner Stories - Admin management Panel, to view all models data - Add/Edit Items outside of admin panel - Delete Items outside of admin panel - Send News updates to list of subscribers ### Target Audience - Honey enthusiasts local to Ireland ### User Requirements and Expectations - A simple and natural way to navigate the website - Quick acessibility to relevant information - Quick acessibility to relevant products - Appealing design that responds accordingly - User Subscribe functionality - Detail view of products - Login functionality in order to get in contact - Subscription service ## Design ### Design Choices ### UX Website design was inspired by a variety of e-com websites, with the focus of the user having a clear goal. Every section is easy to understand, website flow is easy and navigation is intuative. Path to purchase is made as easy as possible. Design choices were minimal, stripping back the fancy animations. Less is more, but at the same time the layout and design was focused on finding a balance between the 'less is more' and appealing design. ### Kanban-Board A kanban board was utilised to set specific goals that would aid agile development! All goals are subdivded into each respective epicFor a detailed view of my goals please find it following the link: <br> <a href="https://github.com/users/MaksimB96/projects/7">Kanban Overview</a> ![Kanban Board](docs/kanban.png) ### ER Diagram Please find the Entity relationship diagram utilized to bring the project to fruition! The bulk of the logic happens between the user and products which ultimatley resuts in the order being placed. The contact form is a stand alone form that gets submitted to the admin panel which later a staff member will get in contact with. Subscription forms store info in the db which is then used by the admin via the admin news segment to send news to a list of emails. <br> Boutique Ado greatly helped establish the website foundations, along with my 3 models being(Subscribers, NewsLtter and Contact Form) ![ER Diagram](docs/er.png) ### Colour Colors used were the bootstrap bg dark with accents of grey and black and the main accent of yellow. These colors were chosen as all these tones play well together adding a layer of depth to the site while maintaining a minimal structure. <br> ![Color Scheme](docs/colors.png) ### Fonts Fonts used were Abril Fatface with a fall back of cursive for the majority of headings as well as Lato with a fall back of sans-serif which I found complements the playful design of Abril and adds nice contrasts, as well as allowing users to quickly pick up on the vital points of info. ### Structure The Structure of the website is clear and concise. Bright colors draw in the user, I untilised the rule of thirds on the home page to make the overall flow pleasant, as well as not over crowding areas with text. The aim was simple and clear, and specific towards an audience interested in honey produce. Navigation is intuative, and the path to purchase is simple and not cluttered. <br> The website is made up of multiple pages: - The Index - The Products - The Product Detail - The Bag - Checkout Area - Checkout Success - User Profile (If authenticated) - News Segment (If super User) - Edit/Add segemt (If super User) - Allauth essentials ### Wireframes <details><summary>Index</summary><img src="docs/wireframes/index-wf.png"></details> <details><summary>Product View</summary><img src="docs/wireframes/products-wf.png"></details> <details><summary>Product Detail</summary><img src="docs/wireframes/product-d-wf.png"></details> <details><summary>Bag</summary><img src="docs/wireframes/bag-wf.png"></details> <details><summary>Checkout</summary><img src="docs/wireframes/check-out-wf.png"></details> <details><summary>Profile</summary><img src="docs/wireframes/profile-wf.png"></details> <details><summary>Admin Edit/Add</summary><img src="docs/wireframes/admin-edit-wf.png"></details> <details><summary>Admin News/Contact Form</summary><img src="docs/wireframes/admin-news-wf.png"></details> <details><summary>Allauth all portals</summary><img src="docs/wireframes/allauth-wf.png"></details> ## Tech Used ### Languages - HTML - CSS - Java Script - Pyhton - Django ### Tools - Git - Git Hub - Git Pod - Figma - Google Fonts - Adobe Color Wheel - Font Awesome - Favicon.io - Circle Crop - postgresql - psycopg - Canva - Boot strap 4 - pixelr - Django - Crispy Forms - panda_io - Amazon Web Services ## Validation ### HTML Validation W3C mark-up was utilised in order to validate html of the website. All Pages pass with no errors. Other significant urlls have been correected! <details><summary>HTML</summary> <img src="docs/validation/html/index-html.png"> </details> <br> ### CSS Validation W3C CSS validator was utilised in order to make sure the css code passes standards with no errors. <details><summary>Full Document</summary> <img src="docs/validation/css/css-valid.png"> </details> <br> ### Python Validation CI Python linter used here to validate my views, due to time constraints on resubmission, full screenshots not available, however views/modelss aand forms triple checked to make sure that the fall in line with pep standards <details><summary>Home</summary> <img src="docs/validation/python/home-view.png"> </details> <details><summary>Products</summary> <img src="docs/validation/python/products-view.png"> </details> <details><summary>Bag</summary> <img src="docs/validation/python/bag-view.png"> </details> <details><summary>Checkout</summary> <img src="docs/validation/python/checkout-view.png"> </details> <details><summary>Contacts</summary> <img src="docs/validation/python/contacts-view.png"> </details> <details><summary>Profiles</summary> <img src="docs/validation/python/profiles-view.png"> </details> <details><summary>Subscription</summary> <img src="docs/validation/python/subscription-view.png"> </details> ### JS Validation JSHint validator was utilised in order to make sure the javascript code passes standards with no errors or warnings, all functions return without errors! <br> ### Performance Below is the performance of all pages (note that performace was consistant across all pages with a high SEO): <details><summary>Performance</summary> <img src="docs/performance.png"> </details> ### Tests #### Devices tested on on - Iphone SE, XR, 11, 12, 14, 14 pro, samsung s5 - Ipad - Macbook Pro/Air - Lenovo Platform - Dell Platform #### Browser tested on on - Chrome - Safari - Brave/Brave Mobile ### Manual Tests Manual testing Through out the site focused on the core functionality. I had a sample group of individuals 10+ using a variety of devices to browse through it. Please note that due to being tight on time full testing was diffficult to fully describe. - Manual testing ensured that the main nav worked correctly, linking to their respective links. This included core functionality, mainly the nav scroll effect, expansion etc. - Product sorting was tested to ensure sorting and searching items worked as intended. Subjects browsed all categories in order to get indended results - Adding bag items was tested to ensure it worked as intended. Once added it was important to see visuka feedback, correct totaling and a visual display of items in bag. - Deleting/Updating an item was tested to ensure the bag view worked correctly along with bag tools working. This was also tested for the admin side of things. - Allauth Portals were tested to make sure that they worked as intended - News letter functionality was tested to ensure features worked correctly. This meant creating a letter and using the subscribed subjects, to receive the letter. It also ensured the letter functionality worked - Contact section was ensured to work as intended (Admin message panel on front end considered for future development). When contact was submitted, all messages would be stored in the DB for the admin to see. ### Bugs During Development I ran in to a few bugs. The last 2 issues prevented me from passing which were corrected now. Media Files not fully rendering even with proper aws deployment: -This was fixed by implementing a media context proccessor. Sorting and some categories did not work: -This was fixed by getting rid of the base js in the extended templates Codeanywhere workspaces deletion: -The cause of this was unknown, however thanks to Sean we migrated back to gitpod which was a more reliable IDE Contact form server error: -This was simply due to the db not being fully integrated Internal server error on deployed site: -This was a typo in the products view for loop which I did not commit, site works fine now Incorrect Totaling on checkout success: -This was an error found in my signals which had a double typed function Confirmation Email not sending: -This was due to the send mail finction having an equals sign which prevented it from being called ## Deployment Honey Haven followed a multi-step deployment. The website was deployed as follows: ### GitHub The process for github was as follows: - First, Navigate to [GitHub](https://github.com/). - Now go to your repositories and find the project you wish to deploy in my case honey haven - In the repository click on 'Settings' located on the right hand side on the top menu. - Scroll down to 'Pages'. - Once at 'Source' click on the dropdown and select 'main' branch, and then save it. - The page will reload and you'll see the link of your published page displayed under 'GitHub' pages. ### Gitpod - Navigate to [Gitpod](https://gitpod.io/) workspaces - In the browser’s address bar, prefix the entire URL with gitpod.io/# and press Enter. - Googles gitpod browser extension allows it to be a single click function. - Side Note: - Initially the project was developed through CodeAnywhere, however due to it's buggy nature the workspace was deleted, thanks to Sean(Tutor Support) we migrated to Gitpod and after a bit of work got the project back, the DB had to be re-established however. <hr> ### elephantSQL Secondly a DB was to be established, I utilized elephantSQL. * Go to [ElephantSQL.com](https://www.elephantsql.com/) * The Tiny Turtle option was used as the free teir to upload and host the DB - To sign in I simply logged in via the github portal - Create a new app. - Name the app. Preferably something similar to the project - Select a plan: <strong>Tiny Turtle Plan</strong> - Select Region: In my case I selected EU-West-1 (IRELAND). - Then click review. - Return to the ElephantSQL dashboard and click on the database instance name for this project. - Verify the DB was connected by running instances. <hr> ### AWS Thirdly AWS was used to host my static and media files, while more complicated, I find less issues when items are hosted! I created an account on [Amazon Web Services](https://aws.amazon.com/) - Follow a multi-step log in procedure, this includes email verification and utilization of a credit card (which will be charged if usage exceeds free teir) <u>Create a bucket</u> - Once my account was established, find S3 using the search bar, select and navigate to S3 to create a new bucket which will be used to store your static and media files - Create the bucket - Eu Ireland was selected as the region. - In settings select *ACLs enabled* and a bucket ownership dropdown will appear, select *Bucket owner preferred* - On the Block Public Access settings for this bucket section, uncheck *Block all public access*, check the *I acknowledge that the current settings might result in this bucket and the objects within becoming public* checkbox, this renders the bucket public access. - In bucket settings select the *properties* tab. Scroll down to find the *static web hosting* section, select *enable static web hosting* - using the generated ARN, navigate to the bucket policy section, click *edit* and select *policy generator*. From the *Select Type Policy* dropdown options, select S3 bucket policy. We want to allow all principal by adding the `*` to the input and the from the -Actions* dropdown, select *GetObject*. - Paste the ARN into the ARN input field and click *add statement*, then click *generate policy*, copy this Policy from the new popup and paste it into the bucket policy editor and add `/*` at the end of the resource value to allow access to all resources in this policy. - Utilize the updated **cross-origin resource sharing** in the below code snippet: ```json [ { "AllowedHeaders": [ "Authorization" ], "AllowedMethods": [ "GET" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [] } ] ``` - Find IAM using the search bar, select and navigate to IAM to create a group, create an access policy to give group access to the S3 bucket and assign the created user to the group so it can use the policy to access the files. - A group was then created in *User Groups* - Add a name for your group, one that is relevent to your project, in my case honey haven - Open the *JSON* tab on the new page and click the *import managed policy* - Search for S3 and select the pre-built *AmazonS3FullAccess* policy and click *import* - Edit the policy by pasting the S3 ARN on *resource*, tutor support helped understand this proccess as it was drastically different from the video guide: ```json { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "s3:*", "Resource": [ "arn:aws:s3:::bucket-name", "arn:aws:s3:::bucket-name/*", ] }, "Statement": [ { "Effect": "Allow", "Action": "s3:*", "Resource": [ "arn:aws:s3:::bucket-name", "arn:aws:s3:::bucket-name/*", ] } ] } ``` - Click review - Assign an appropriate name - Next attach your policy previously created to the group - Select the Policy you created and click *add permissions* - We have to create a user for the group. Click *Users* from the left sidebar and then click the *add users* button and add a name for the user, in my case honeyhaven-staticfiles-user - Next tick *programmatic access* - Add user to the group - Then download the .csv file which will contain this user's access key and secret access key which we'll use to authenticate them from our Django app. It is important to keep these safe as to do the process again will require a new user. ### Connect AWS to django First, you are required to install boto and django-storages to read these. After these have been installed and your settings reflect this, the following parameters were added to settings: ```python if 'USE_AWS' in os.environ: AWS_S3_OBJECT_PARAMETERS = { 'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT', 'CacheControl': 'max-age=9460800', } AWS_STORAGE_BUCKET_NAME = 'your bucket name goes here' AWS_S3_REGION_NAME = 'your selected region goes here' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' ``` The CSV file that was created earlier containing the respective keys were then added to heroku config vars to set it up. Then, additional settings were implemeted in order to allow aws to utilize the static and media files as well as over riding variables: ```python STATICFILES_STORAGE = 'custom_storages.StaticStorage' STATICFILES_LOCATION = 'static' DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' MEDIAFILES_LOCATION = 'media' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{STATICFILES_LOCATION}/' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{MEDIAFILES_LOCATION}/' ``` Once this was completed and the static files pushed, the static folder was established in AWS. Afterwhich, my media files were uploaded to the newly created media folder in AWS! It is worth noting that an extra line of code was added to my context processor to allow all media files to load accordingly: ```python 'django.template.context_processors.media', ``` <hr> ### Heroku lastly, Heroku was set up to host the web app. - Create a new app, and name it, in my case honeyhaven. - I then selected the closest region being EU. - Once the app was created, open the Settings tab. - Click reveal config vars. - Add the config var <strong><i>DATABASE_URL</i></strong>, utilising the url provided by elephantSQL. - Add the config var <strong><i>AWS_ACCESS_KEY_ID</i></strong>, add the value previously obtained from aws. - Add the config var <strong><i>AWS_SECRET_ACCESS_KEY</i></strong>, add the value previously obtained from aws. - Add the config var <strong><i>USE_AWS</i></strong>, and for the value set it to true. - Add the config var <strong><i>STRIPE_PUBLIC_KEY</i></strong>, add the value previously obtained from the stripe dev dashboard. - Add the config var <strong><i>STRIPE_SECRET_KEY</i></strong>, add the value previously obtained from the stripe dev dashboard. - Add the config var <strong><i>STRIPE_WH_SECRET</i></strong>, add the value previously obtained from the stripe dev dashboard > webhooks. - Add the config var <strong><i>SECRET_KEY</i></strong>, add a random key generated for the project. - Adjust settings to allow for auto deploy and then deploy! <hr> ### Github cloning/forking It is worth mentioning how to clone/fork a project #### Cloning 1. Go to your repo 2. Locate the Code button above the list of files and click it 3. Select if you prefer to clone using HTTPS, SSH, or GitHub CLI and click the copy button to copy the URL to your clipboard 4. Open Git Bash or Terminal 5. Change the current working directory to the one where you want the cloned directory 6. In your IDE Terminal, type the following command to clone a repo: - `git clone <repo link>` 7. Press Enter to create your local clone. ### Forking 1. Go to your repo 2. At the top of the Repository, above the *Settings* button on the menu, locate the *Fork* button. 3. User should now have access to the forked repo ## Future Features There are a few more feartures that I would like to implement in the future. These Include: 1. Admin view message panel in manage section 2. Rating System/comment section 3. Flesh out the products 4. A Feedback Section 5. Additional support through webkits for mozilla and other browsers ## Credits ### Media Logo media created by me using <a href="https://www.canva.com/">Canva</a>, this includes Icons and backgound images. <br> Any Icons used found on <a href="https://fontawesome.com/">Font Awesome</a> <br> # Images 1. Landing page - Kat Smith 2. HoneySpoon - Mae My 3. Spoon and honey - Daily Slowdown 4. Small Jar - Dario Menendez 5. Large Jar - Kier 6. Bee suit - gryffn 7. Lip Balm - Antoni Shkraba 8. Candle - Jill Burrow 9. Beeswax paper - Karina Zhukovskaya 10. Bee Flower - Erik Kartis ### Code 1. Product/bag/checkout/search/wh handling logic (and some layout) inspired by : <a href="https://www.youtube.com/watch?v=3_3q_dE4_qs&t=649s">Code Institute Boutique Ado</a> 2. subscription form with my modifications by : <a href="https://www.youtube.com/watch?v=hWtlskOaFNI&t=3315s">KenBroTec</a> 3. Interactive search bar : <a href="https://bbbootstrap.com/snippets/expandable-search-bar-12368750">bbbootstrap</a> 4. Bootstrap Documentation 5. Django Documentation 6. Stripe Docs 7. Github docs ## Acknowledgements - would like to thank my wonderful girfriend for the inspiration and idea conception, and for the slight scare at the hospital - CI for provide me the knowledge to under-take this task - Tutor Support for provideing better knowledge to implement the code and salvaging my project, especially Sean and Ed - CI Boutique Ado for a solid foundation and logic behind e-commerce applications - The wonderful community over on Slack! - The amazing studetnt support staff that helped me during my tough times ### Side Note Due to the unfortunate circumstances that befell my partner, I missed the submission deadline due to the emergency, thanks to student support and the wonderful tutor team they helped me push through by giving me that extra bit of time. That being said I was still rushed to push the project, therefore I apologise in advance if the documentation was not fully completed. Thank you code institute for providing an amazing skill set that I will strive to refine and improve moving into this industry!
/* SPACING SYSTEM (px) 2 / 4 / 8 / 12 / 16 / 24 / 32 / 48 / 64 / 80 / 96 / 128 FONT SIZE SYSTEM (px) 10 / 12 / 14 / 16 / 18 / 20 / 24 / 30 / 36 / 44 / 52 / 62 / 74 / 86 / 98 */ /* MAIN COLOR : #1f8686;; #165e5e; TINTS: #e9f3f3; GREY COLOR : #333 ; BORDER RADIUS: 30px; FONT WEIGHT: Default: 400; Medium: 500; Semi-Bold: 600; Bold: 700 letter-spacing: 0.75px; -0.5px LINE-HEIGHT: Default: 1 1.05 Paragraph default: 1.6 */ *{ margin: 0; padding: 0; box-sizing: border-box; } html{ /* font-size: 10px; 10px / 16px = 0.625 * 100 = 62.5 1rem = 10px*/ font-size: 62.5%; } body{ font-family: 'Rubik', sans-serif; line-height: 1; font-weight: 400; color: #555; } /* ********************* */ /* GENERAL REUSABLE COMPONENTS */ /* ********************* */ .container{ max-width: 120rem; margin: 0 auto; padding: 0 3.2rem; } .grid{ display: grid; row-gap: 9.6rem; column-gap: 6.4rem; } .grid--center-v{ align-items: center; } .grid--2-cols{ grid-template-columns: repeat(2, 1fr ); } .grid--3-cols{ grid-template-columns: repeat(3, 1fr ); } .grid--4-cols{ grid-template-columns: repeat(4, 1fr ); } .heading-primary, .heading-secondary, .heading-tertiary{ font-weight: 700; letter-spacing: -0.5px; color: #333; } .heading-primary{ /* / 52 / 62 / 74 / */ font-size: 4.4rem; /* / 32 / 48 / */ margin-bottom: 3.2rem; line-height: 1.05; } .heading-secondary{ /* / 30 / 36 / 44 / 52 / */ font-size: 3.6rem; line-height: 1.02; margin-bottom: 9.6rem; font-weight: 500; } .heading-tertiary{ /* / 30 / 36 / 44 / 52 / */ font-size: 3rem; line-height: 1.2; margin-bottom: 4.8rem; font-weight: 500; } .heading-quaternary{ font-size: 2.4rem; line-height: 1.1; margin-bottom: 2.4rem; font-weight: 500; } .subheading{ display: inline-block; text-transform: uppercase; font-size: 1.6rem; font-weight: 500; color: #1f8686;; margin-bottom: 1.6rem; letter-spacing: 0.75px; } .btn{ display: inline-block; text-decoration: none; font-size: 2rem; font-weight: 600; padding: 1.6rem 3.2rem; border-radius: 3rem; transition: all 0.3s; } .btn--full{ background-color: #1f8686; color: #fff; } .btn--full:hover, .btn--full:active{ background-color: #165e5e; } .btn--outline{ background-color: #fff; color: #555; } .btn--outline, .btn--outline:hover, .btn--outline:active{ background-color: #e9f3f3; box-shadow: inset 0 0 0 3px #fff; } .list{ list-style-type: none; display: flex; flex-direction: column; gap: 1.6rem; margin-bottom: 4.8rem; } .list-icon{ width: 3rem; height: 3rem; color: #042e35; } .list-item{ font-size: 1.8rem; display: flex; align-items: center; gap: 1.6rem; } /* HELPER CLASSES */ .margin-right-sm{ margin-right: 1.6rem!important; } .margin-bottom-md{ margin-bottom: 4.8rem!important; } strong{ font-weight: 500; } .center-text{ text-align: center; } .white-heading{ color: #fff!important; font-weight: 400; } .margin-right-md{ margin-right: 9.6rem; }
<!doctype html> <html lang="ja" xmlns:th="http://www.thymeleaf.org"> <head th:replace="_fragment::header(title=${title})"> <meta charset="UTF-8"/> <title></title> <link rel="icon" href="../static/app/img/favicon.ico"/> <link href="../static/tether/css/tether.min.css" rel="stylesheet"/> <link href="../static/bootstrap4a2/css/bootstrap.min.css" rel="stylesheet"/> <link href="../static/font-awesome/css/font-awesome.min.css" rel="stylesheet"/> <link href="../static/c3/css/c3.min.css" rel="stylesheet"/> <link href="../static/app/css/style.css" rel="stylesheet"/> </head> <body> <div th:replace="_fragment::navigator" class="navigator"> <nav class="navbar navbar-dark navbar-static-top bg-inverse bg-faded"> <div class="collapse navbar-toggleable-xs" id="navbar-header"> <a class="navbar-brand" href="/"> <object type="image/svg+xml" data="../static/app/img/logo.svg" alt="logo" width="32" height="32"></object> whisker </a> </div> </nav> </div> <!-- #modal --> <div id="modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="modal-label" aria-hidden="true" data-backdrop="static" data-keyboard="false"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close" data-loading-text="&times;" autocomplete="off"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="modal-title">Repository settings <span class="setting-type"></span></h4> </div> <div class="modal-body"> <form class="form-horizontal"> <input id="reposId" type="hidden"/> <fieldset class="form-group"> <label class="form-control-label form-control-sm" for="reposName">Name*</label> <small class="text-muted">Example: ProjectRepos</small> <input id="reposName" class="form-control form-control-sm" type="text" placeholder="Required"/> <label class="form-control-label form-control-sm" for="reposExt">Extensions</label> <small class="text-muted" th:text="'Default: ' + ${defaultExtensions}">Default: .abc, .xyz</small> <input id="reposExt" class="form-control form-control-sm" type="text" placeholder="Optional"/> <label class="form-control-label form-control-sm" for="reposFilter">Filter</label> <small class="text-muted">Example: .*(Service|Repository).*</small> <input id="reposFilter" class="form-control form-control-sm" type="text" placeholder="Optional"/> </fieldset> <fieldset class="form-group"> <h5 class="form-control-label text-muted">Git</h5> <label class="form-control-label form-control-sm" for="gitDir">Directory path*</label> <small class="text-muted">Example: /home/foo/repos/.git</small> <input id="gitDir" class="form-control form-control-sm" type="text" placeholder="Required"/> <label class="form-control-label form-control-sm" for="gitRegex">Extract regex</label> <small class="text-muted" th:text="'Default: ' + ${defaultRegex}">Default: .*/extract/regex/(.+)\..+</small> <input id="gitRegex" class="form-control form-control-sm" type="text" placeholder="Optional"/> </fieldset> <fieldset class="form-group"> <h5 class="form-control-label text-muted">Source file</h5> <label class="form-control-label form-control-sm" for="sourceDir">Directory path*</label> <small class="text-muted">Example: /home/foo/repos/src</small> <input id="sourceDir" class="form-control form-control-sm" type="text" placeholder="Required"/> <label class="form-control-label form-control-sm" for="sourceRegex">Extract regex</label> <small class="text-muted" th:text="'Default: ' + ${defaultRegex}">Default: .*/extract/regex/(.+)\..+</small> <input id="sourceRegex" class="form-control form-control-sm" type="text" placeholder="Optional"/> </fieldset> <fieldset class="form-group"> <h5 class="form-control-label text-muted">Class file</h5> <label class="form-control-label form-control-sm" for="classFileDir">Directory path*</label> <small class="text-muted">Example: /home/foo/repos/target/classes</small> <input id="classFileDir" class="form-control form-control-sm" type="text" placeholder="Required"/> <label class="form-control-label form-control-sm" for="classFileRegex">Extract regex</label> <small class="text-muted" th:text="'Default: ' + ${defaultRegex}">Default: .*/extract/regex/(.+)\..+</small> <input id="classFileRegex" class="form-control form-control-sm" type="text" placeholder="Optional"/> </fieldset> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal" data-loading-text="Cancel" autocomplete="off">Cancel</button> <button type="button" class="btn btn-primary" id="modal-btn-save" data-loading-text="Please wait.." autocomplete="off">Save</button> </div> </div> </div> </div> <!-- /#modal --> <div class="container"> <h1 class="text-uppercase" th:text="${title}">Title</h1> <p class="lead"></p> <table class="table table-hover"> <thead> <tr> <th class="col-name">Name</th> <th class="col-ext">Extensions</th> <th class="col-filter">FILTER</th> <th class="col-gitDir">Git dir</th> <th class="col-gitRegex">Git regex</th> <th class="col-modifier">Modifier</th> <th class="col-modified">Modified</th> <th></th> <th><a class="item-add" href="#">Add</a></th> </tr> </thead> <tbody> <tr th:each="repos : ${repositories}"> <td class="val-name filter-value ellipsis" title="Name" data-container="body" data-toggle="popover" data-placement="top" data-trigger="hover" th:text="${repos.name}" th:attr="data-val-name=${repos.name}"> Repos Name </td> <td class="val-extensions filter-value ellipsis" title="Extensions" data-container="body" data-toggle="popover" data-placement="top" data-trigger="hover" th:text="${#strings.listJoin(repos.extensions, ', ')}" th:attr="data-val-extensions=${#strings.listJoin(repos.extensions, ', ')}"> .ext, .x </td> <td class="val-filter filter-value ellipsis" title="Filter" data-container="body" data-toggle="popover" data-placement="top" data-trigger="hover" th:text="${repos.filter}" th:attr="data-val-name=${repos.filter}"> Repos Filter </td> <td class="val-git-directory filter-value ellipsis" title="Git dir" data-container="body" data-toggle="popover" data-placement="top" data-trigger="hover" th:text="${repos.git.directory}" th:attr="data-val-git-directory=${repos.git.directory}"> /dir/path </td> <td class="val-git-extract-regex filter-value ellipsis" title="Git regex" data-container="body" data-toggle="popover" data-placement="top" data-trigger="hover" th:text="${repos.git.extractRegex}" th:attr="data-val-git-extract-regex=${repos.git.extractRegex}"> .*/regex </td> <td class="val-modifier filter-value ellipsis" title="Modifier" data-container="body" data-toggle="popover" data-placement="top" data-trigger="hover" th:text="${repos.modifier}" th:attr="data-val-modifier=${repos.modifier}"> Modifier </td> <td class="val-modified filter-value ellipsis" title="Modified" data-container="body" data-toggle="popover" data-placement="top" data-trigger="hover" th:text="${#dates.format(repos.modified, 'yyyy-MM-dd HH:mm:ss')}" th:attr="data-val-modified=${#dates.format(repos.modified, 'yyyy-MM-dd HH:mm:ss')}"> 2016-01-19 </td> <td> <a class="item-copy" href="#">Copy</a> </td> <td> <a class="item-edit" href="#" th:attr="data-val-id=${repos.id}, data-val-name=${repos.name}, data-val-extensions=${#strings.listJoin(repos.extensions, ', ')}, data-val-filter=${repos.filter}, data-val-git-directory=${repos.git.directory}, data-val-git-extract-regex=${repos.git.extractRegex}, data-val-source-directory=${repos.source.directory}, data-val-source-extract-regex=${repos.source.extractRegex}, data-val-class-file-directory=${repos.classFile.directory}, data-val-class-file-extract-regex=${repos.classFile.extractRegex}">Edit</a> </td> </tr> </tbody> </table> </div><!-- /.container --> <footer th:replace="_fragment::footer"> <script src="../static/jquery2/js/jquery.min.js"></script> <script src="../static/tether/js/tether.min.js"></script> <script src="../static/bootstrap4a2/js/bootstrap.min.js"></script> <script src="../static/d3/js/d3.min.js"></script> <script src="../static/c3/js/c3.min.js"></script> <script src="../static/app/js/app.js"></script> </footer> <script type="text/javascript" th:inline="javascript"> /*<![CDATA[*/ /* * Popover */ $('[data-toggle="popover"]').popover({ content: function() { return $(this).text(); } }); /* * Get modal */ var getModalForm = function() { return { id: $('#reposId').val(), name: $('#reposName').val(), extensions: ($('#reposExt').val() ? $('#reposExt').val().replace(/\s/, '').split(',') : []), filter: $('#reposFilter').val(), git: { directory: $('#gitDir').val(), extractRegex: $('#gitRegex').val() }, source: { directory: $('#sourceDir').val(), extractRegex: $('#sourceRegex').val() }, classFile: { directory: $('#classFileDir').val(), extractRegex: $('#classFileRegex').val() } }; }; /* * Set modal form */ var setModalForm = function(data) { $('#reposId').val(data.reposId); $('#reposName').val(data.reposName); $('#reposExt').val(data.reposExt); $('#reposFilter').val(data.reposFilter); $('#gitDir').val(data.gitDir); $('#gitRegex').val(data.gitRegex); $('#sourceDir').val(data.sourceDir); $('#sourceRegex').val(data.sourceRegex); $('#classFileDir').val(data.classFileDir); $('#classFileRegex').val(data.classFileRegex); }; /* * Set modal button [Save] */ var setModalBtnSave = function(saveAction) { $('#modal-btn-save').on({ click: saveAction }); }; /* * Show add modal */ $('.item-add').on({ click: function() { var $this = $(this); $('.setting-type').text('[Add]'); setModalForm({ reposId: '', reposName: '', reposExt: '', reposFilter: '', gitDir: '', gitRegex: '', sourceDir: '', sourceRegex: '', classFileDir: '', classFileRegex: '' }); setModalBtnSave(function() { var $this = $(this); $.ajax({ type: 'POST', url: /*[[ @{/api/v1/repositories} ]]*/ '#', contentType: 'application/json;charset=UTF-8', processData: false, data: JSON.stringify(getModalForm()), statusCode: { 404: function() { console.log('page not found'); } } }).done(function() { location.href = /*[[ @{/repository} ]]*/ '#'; }); }); $('#modal').modal('show'); } }); /* * Show copy modal */ $('.item-copy').on({ click: function () { var $this = $(this); var $tr = $this.closest('tr'); $('.setting-type').text('[Copy]'); setModalForm({ reposId: '', reposName: $tr.find('.item-edit').data('val-name'), reposExt: $tr.find('.item-edit').data('val-extensions'), reposFilter: $tr.find('.item-edit').data('val-filter'), gitDir: $tr.find('.item-edit').data('val-git-directory'), gitRegex: $tr.find('.item-edit').data('val-git-extract-regex'), sourceDir: $tr.find('.item-edit').data('val-source-directory'), sourceRegex: $tr.find('.item-edit').data('val-source-extract-regex'), classFileDir: $tr.find('.item-edit').data('val-class-file-directory'), classFileRegex: $tr.find('.item-edit').data('val-class-file-extract-regex') }); setModalBtnSave(function() { var $this = $(this); $.ajax({ type: 'POST', url: /*[[ @{/api/v1/repositories} ]]*/ '#', contentType: 'application/json;charset=UTF-8', processData: false, data: JSON.stringify(getModalForm()), statusCode: { 404: function() { console.log('page not found'); } } }).done(function() { location.href = /*[[ @{/repository} ]]*/ '#'; }); }); $('#modal').modal('show'); } }); /* * Show edit modal */ $('.item-edit').on({ click: function () { var $this = $(this); var $tr = $this.closest('tr'); $('.setting-type').text('[Edit]'); setModalForm({ reposId: $tr.find('.item-edit').data('val-id'), reposName: $tr.find('.item-edit').data('val-name'), reposExt: $tr.find('.item-edit').data('val-extensions'), reposFilter: $tr.find('.item-edit').data('val-filter'), gitDir: $tr.find('.item-edit').data('val-git-directory'), gitRegex: $tr.find('.item-edit').data('val-git-extract-regex'), sourceDir: $tr.find('.item-edit').data('val-source-directory'), sourceRegex: $tr.find('.item-edit').data('val-source-extract-regex'), classFileDir: $tr.find('.item-edit').data('val-class-file-directory'), classFileRegex: $tr.find('.item-edit').data('val-class-file-extract-regex') }); setModalBtnSave(function() { var $this = $(this); $.ajax({ type: 'PUT', url: /*[[ @{/api/v1/repositories} ]]*/ '#', contentType: 'application/json;charset=UTF-8', processData: false, data: JSON.stringify(getModalForm()), statusCode: { 404: function() { console.log('page not found'); } } }).done(function() { location.href = /*[[ @{/repository} ]]*/ '#'; }); }); $('#modal').modal('show'); } }); /*]]>*/ </script> </body> </html>
classdef arlas < handle %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Class definition arlas % For use with ARLas (Auditory Research Laboratory auditory software) % % Auditory Research Lab, The University of Iowa % Deptartment of Communication Sciences & Disorders % The University of Iowa % Author: Shawn S. Goodman, PhD % Date: September 14, 2016 % Last Updated: November 4, 2017 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% properties (SetAccess = private) arlasVersion = '2018.11.14'; sep % path delimiter appriate for the current operating system map % struct containing file paths initPath initFile home % current working directory, prior to starting arlas (will return here when exits) %----- handles for graphical user interface ----- ----- H % Figure handle ----- guiSize CONTROL % CONTROL Panel ----- h % control panel gui gui % dimensions of the control panel nButtons = 5; % number of buttons h_splash h_init % initialization button h_pause % calibrate button h_load % load button h_run % run button h_abort % abort button ATTEN_OUT % ATTEN_OUT Panel ----- h_DACgain % figure for controlling DAC gain h_gainCh1 h_gainCh2 h_gainUp h_gainDn h_continue VIEW % CURRENT pannel ----- h_subjID h_subjLabel h_subjBox h_expLabel h_expBox h_opLabel h_opBox enterSubjID h_enterSubjID subjID_OK ping % used to determine whether the same versions of all arlas class files are being used deadInTheWater % detemines whether error already occured and whether to print error msg end properties (SetAccess = public) objInit % object of class initARLas (initialization) objPlayrec % object of class playrecARLas (play and record using playrec utility) initialized % whether the system is currently initialized killRun % whether the abort button has been pushed expFileName expPathName loaded % whether a calibration file is currently loaded subjectID experimentID operatorID end methods function obj = arlas(~) % initialize object of class initARLas try obj.sep = filesep; % get the path delimiter appropriate to the operating system being used dummy = which('arlas'); % get the location of the currently-running verison of arlas.m indx = length(dummy); % strip off the file name at the end stop = 0; while ~stop if strcmp(dummy(indx),obj.sep) stop = 1; dummy = dummy(1:indx); % location of arlas base = dummy(1:end-13); % base location is dummy less the 13 characters: Core\classes\ end indx = indx - 1; if indx < 1 errorTxt = {' Issue: Unable to path location of currently running version of ARLas.' ' Action: Aborting initialization.' ' Location: arlas.arlas.' }; errorMsgARLas(errorTxt); return end end obj.home = pwd; % get the current working directory addpath(genpath(base)) % add all directories and subdirectories cd(base) % change directory to the base location (will change directories back home upon exit) format compact % save space in command window % create a map to needed directories obj.map.calibrations = [base,'Peripheral',obj.sep,'calibrations',obj.sep]; obj.map.experiments = [base,'Peripheral',obj.sep,'experiments',obj.sep]; obj.map.sysConfigs = [base,'Peripheral',obj.sep,'sysConfigs',obj.sep]; obj.map.data = [base,'Data',obj.sep]; % check to make sure that these directories exist; if not, alert user errorTxt = {' Issue: Unexpected ARLas directory structure found.' ' Action: Aborting ARLas.' ' Location: arlas.initPlayrec.' ' Recommended Fix: Make sure the following ARLas structure exists:.' ' ------------------------------------ ' ' ARLas (base directory)' ' \\Core' ' \\classes (* Note: The file arlas.m is located here.)' ' \\classSupport' ' \\general' ' \\gui' ' \\playrec' ' \\Peripheral' ' \\analysis' ' \\calibrations' ' \\experiments' ' \\sysConfigs' ' \\Data' ' ------------------------------------ ' }; OK = 1; if exist(obj.map.calibrations,'dir') ~= 7 OK = 0; end if exist(obj.map.experiments,'dir') ~= 7 OK = 0; end if exist(obj.map.sysConfigs,'dir') ~= 7 try mkdir(obj.map.sysConfigs) addpath(genpath(obj.map.sysConfigs)) catch OK = 0; end end if exist(obj.map.data,'dir') ~= 7 try mkdir(obj.map.data) addpath(genpath(obj.map.data)) catch OK = 0; end end if exist(obj.map.data,'dir') ~= 7 OK = 0; end if OK == 0 errorMsgARLas(errorTxt); return end obj.initPath = obj.map.sysConfigs; obj.initFile = 'newSysConfig.mat'; obj.initGui % initialize the gui v0 = obj.arlasVersion; obj.ping = 1; test1 = initARLas(obj); % instantiate an object of class initARLas v1 = []; try v1 = test1.arlasVersion; catch; end test2 = playrecARLas(test1); % instantiate an object of class initARLas v2 = []; try v2 = test2.arlasVersion; catch; end delete(test1) delete(test2) fail = 0; if isempty(v0) || isempty(v0) || isempty(v2) fail = 1; end if ~strcmp(v0,v1) fail = 1; end if ~strcmp(v0,v2) fail = 1; end if fail == 1 warnTxt = {' Issue: Mismatch detected between arlas versions.' ' Action: Update to most current verion: https://github.com/myKungFu/ARLas.' ' Ensure that arlas.m, initARLAs.m, and playrecARLas.m are all the same version.' ' Failure to correct this may result in unstable performance!' }; warnMsgARLas(warnTxt); end obj.ping = 0; obj.deadInTheWater = 0; catch ME errorTxt = {' Issue: Unexpected error creating object of class arlas.' ' Action: None.' ' Location: arlas.' }; errorMsgARLas(errorTxt); objPlayrec.printError(ME) end end function abort(varargin) % instructions for aborting when gui closed try obj = varargin{1}; cd(obj.home) % change directory to the home location catch end try obj = varargin{1}; delete(obj.objInit) delete(obj.objPlayrec) delete(obj.H) delete(obj); catch while gcf~=1 delete(gcf); end; delete(gcf); end end function initGui(varargin) % initialize the arlas graphical user interface obj = varargin{1}; try % delete figure if it already exists delete(obj.H) catch end try % create new main figure %[left, bottom,width, height] obj.guiSize.width = 545; % figure width in pixels obj.guiSize.height = 620; %625; %675; %750; scrsz = get(0,'ScreenSize'); % get the current screen size obj.guiSize.left = round(scrsz(4) * .1); % location of left edge obj.guiSize.bottom = scrsz(4) * .1; % location of bottom overhang = (obj.guiSize.bottom + obj.guiSize.height)-scrsz(4); % adjust so gui doesn't hang off the top of the screen if overhang > 0 % if positive value (meaning figure is off the screen) overhang = overhang + 0; % give a little extra to account for top of the figure %if overhang <= obj.guiSize.bottom % try to fix this problem obj.guiSize.bottom = obj.guiSize.bottom - overhang; % correct for the overhang %else % otherwise, do the best you can % obj.guiSize.bottom = 1; % put it as low as possible %end end rect = [obj.guiSize.left, obj.guiSize.bottom, obj.guiSize.width, obj.guiSize.height]; obj.H = figure('Position',rect,'Color',[1 1 1],'Units','Pixels',... 'CloseRequestFcn',@obj.abort,'Name',['ARLas version ',obj.arlasVersion],... 'NumberTitle','off','MenuBar','none','Resize','on','Color',[1 1 1],'Tag','ARLas'); % create panels within main gui figure ----- obj.CONTROL = uipanel('Parent',obj.H,'Title','CONTROL PANEL','FontSize',12,... 'BackgroundColor','white','Units','Pixels','Position',[10 10 105*5+4 140]); obj.VIEW = uipanel('Parent',obj.H,'Title','VIEW','FontSize',12,... 'BackgroundColor','white','Units','Pixels','Position',[10 160 105*5+4 455]); % Populate control panel ----- obj.gui.height = 105; obj.gui.width = 105; obj.h_splash = uicontrol('Parent',obj.CONTROL,'Style','togglebutton',... 'BackgroundColor',[1 1 1],'Position',[(obj.gui.width*0) 1 obj.gui.width*5 obj.gui.height],... 'Visible','on','CData',imread('splash.jpg'),'BusyAction','queue','Interruptible','off'); pause(2) delete(obj.h_splash) obj.h_init = uicontrol('Parent',obj.CONTROL,'Style','togglebutton',... 'BackgroundColor',[1 1 1],'Position',[(obj.gui.width*0) 1 obj.gui.width obj.gui.height],... 'Callback',@obj.initPlayrec,'Visible','on','TooltipString','INITIALIZE playrec software',... 'CData',imread('initGray.jpg'),'BusyAction','queue','Interruptible','on'); obj.h_load = uicontrol('Parent',obj.CONTROL,'Style','togglebutton',... 'BackgroundColor',[1 1 1],'Position',[(obj.gui.width*1) 1 obj.gui.width obj.gui.height],... 'Callback',@obj.loadExperiment,'Visible','on','TooltipString','LOAD experiment file',... 'CData',imread('loadGray.jpg'),'BusyAction','queue','Interruptible','on'); obj.h_pause = uicontrol('Parent',obj.CONTROL,'Style','togglebutton',... 'BackgroundColor',[1 1 1],'Position',[(obj.gui.width*2) 1 obj.gui.width obj.gui.height],... 'Callback',@obj.pauseExperiment,'Visible','on','TooltipString','PAUSE experiment file',... 'CData',imread('pauseGray.jpg'),'BusyAction','queue','Interruptible','on'); obj.h_run = uicontrol('Parent',obj.CONTROL,'Style','togglebutton',... 'BackgroundColor',[1 1 1],'Position',[(obj.gui.width*3) 1 obj.gui.width obj.gui.height],... 'Callback',@obj.runExperiment,'Visible','on','TooltipString','RUN experiment or calibration file',... 'CData',imread('runGray.jpg'),'BusyAction','queue','Interruptible','on'); obj.h_abort = uicontrol('Parent',obj.CONTROL,'Style','togglebutton',... 'BackgroundColor',[1 1 1],'Position',[(obj.gui.width*4) 1 obj.gui.width obj.gui.height],... 'Callback',@obj.abortExperiment,'Visible','on','TooltipString','ABORT current process',... 'CData',imread('abortGray.jpg'),'BusyAction','queue','Interruptible','on'); obj.buttonManager(10) catch ME if obj.deadInTheWater == 1 return else obj.deadInTheWater = 1; end errorTxt = {' Issue: Error creating GUI.' ' Action: None.' ' Location: in arlas.initGui.' }; errorMsgARLas(errorTxt); obj.printError(ME) end end function buttonManager(varargin) % change colors and states of buttons on bottom bar obj = varargin{1}; try code = varargin{2}; flickerLen = 0.1; % length of flicker for error notification flickerReps = 5; % number of flickers % 10s are for arlas gui % 20s are for initializing the system % 30s are for pausing % 40s are for loading experiment files % 50s are for running % 60s are for aborting % % the 'Tag' field is used to indicate whether a button can be used % or not. Will be set to zero when its callback is currently % running, as well. switch code case 10 % initialize arlas gui (FUNCTION initGui) set(obj.h_init,'Value',0,'Tag','on','CData',imread('initYellow.jpg')) set(obj.h_load,'Value',0,'Tag','off','CData',imread('loadGray.jpg')) set(obj.h_pause,'Value',0,'Tag','off','CData',imread('pauseGray.jpg')) set(obj.h_run,'Value',0,'Tag','off','CData',imread('runGray.jpg')) set(obj.h_abort,'Value',0,'Tag','off','CData',imread('abortGray.jpg')) case 20 % Begin initializing the system (FUNCTION initPlayrec) set(obj.h_init,'Value',1,'Tag','off','CData',imread('initGreen.jpg')) set(obj.h_load,'Value',0,'Tag','off','CData',imread('loadGray.jpg')) set(obj.h_pause,'Value',0,'Tag','off','CData',imread('pauseGray.jpg')) set(obj.h_run,'Value',0,'Tag','off','CData',imread('runGray.jpg')) set(obj.h_abort,'Value',0,'Tag','off','CData',imread('abortGray.jpg')) case 21 % -- unsuccessful initialization for ii=1:flickerReps set(obj.h_init,'Value',1,'Tag','off','CData',imread('initRed.jpg')) pause(flickerLen) set(obj.h_init,'Value',1,'Tag','off','CData',imread('initGreen.jpg')) pause(flickerLen) end set(obj.h_init,'Value',0,'Tag','on','CData',imread('initGreen.jpg')) set(obj.h_load,'Value',0,'Tag','off','CData',imread('loadGray.jpg')) set(obj.h_pause,'Value',0,'Tag','off','CData',imread('pauseGray.jpg')) set(obj.h_run,'Value',0,'Tag','off','CData',imread('runGray.jpg')) set(obj.h_abort,'Value',0,'Tag','off','CData',imread('abortGray.jpg')) case 22 % -- successful initialization set(obj.h_init,'Value',0,'Tag','on','CData',imread('initYellow.jpg')) set(obj.h_load,'Value',0,'Tag','on','CData',imread('loadYellow.jpg')) set(obj.h_pause,'Value',0,'Tag','off','CData',imread('pauseGray.jpg')) set(obj.h_run,'Value',0,'Tag','off','CData',imread('runGray.jpg')) set(obj.h_abort,'Value',0,'Tag','off','CData',imread('abortGray.jpg')) case 30 % Begin pausing the system (FUNCTION pauseExperiment) set(obj.h_init,'Value',0,'Tag','off','CData',imread('initGray.jpg')) set(obj.h_load,'Value',0,'Tag','off','CData',imread('loadGray.jpg')) set(obj.h_pause,'Value',1,'Tag','off','CData',imread('pauseGreen.jpg')) set(obj.h_run,'Value',0,'Tag','off','CData',imread('runGray.jpg')) set(obj.h_abort,'Value',0,'Tag','off','CData',imread('abortGray.jpg')) case 31 % -- unsuccessful pause for ii=1:flickerReps set(obj.h_pause,'Value',1,'Tag','off','CData',imread('pauseRed.jpg')) pause(flickerLen) set(obj.h_pause,'Value',1,'Tag','off','CData',imread('pauseGreen.jpg')) pause(flickerLen) end set(obj.h_init,'Value',0,'Tag','on','CData',imread('initGray.jpg')) set(obj.h_load,'Value',0,'Tag','off','CData',imread('loadGray.jpg')) set(obj.h_pause,'Value',0,'Tag','on','CData',imread('pauseYellow.jpg')) set(obj.h_run,'Value',0,'Tag','on','CData',imread('runGreen.jpg')) set(obj.h_abort,'Value',0,'Tag','on','CData',imread('abortRed.jpg')) case 32 % -- successful pause ON set(obj.h_init,'Value',0,'Tag','off','CData',imread('initGray.jpg')) set(obj.h_load,'Value',0,'Tag','off','CData',imread('loadGray.jpg')) set(obj.h_pause,'Value',0,'Tag','on','CData',imread('pauseGreen.jpg')) set(obj.h_run,'Value',0,'Tag','off','CData',imread('runGray.jpg')) set(obj.h_abort,'Value',0,'Tag','on','CData',imread('abortRed.jpg')) case 33 % -- successful pause OFF set(obj.h_init,'Value',0,'Tag','off','CData',imread('initGray.jpg')) set(obj.h_load,'Value',0,'Tag','off','CData',imread('loadGray.jpg')) set(obj.h_pause,'Value',0,'Tag','on','CData',imread('pauseYellow.jpg')) set(obj.h_run,'Value',0,'Tag','on','CData',imread('runGreen.jpg')) set(obj.h_abort,'Value',0,'Tag','on','CData',imread('abortRed.jpg')) case 40 % Begin loading experiment file (FUNCTION loadExperiment) set(obj.h_init,'Value',0,'Tag','off','CData',imread('initGray.jpg')) set(obj.h_load,'Value',1,'Tag','off','CData',imread('loadGreen.jpg')) set(obj.h_pause,'Value',0,'Tag','off','CData',imread('pauseGray.jpg')) set(obj.h_run,'Value',0,'Tag','off','CData',imread('runGray.jpg')) set(obj.h_abort,'Value',0,'Tag','off','CData',imread('abortGray.jpg')) case 41 % -- failed to load experiment file for ii=1:flickerReps set(obj.h_load,'Value',1,'Tag','off','CData',imread('loadRed.jpg')) pause(flickerLen) set(obj.h_load,'Value',1,'Tag','off','CData',imread('loadGreen.jpg')) pause(flickerLen) end set(obj.h_init,'Value',0,'Tag','on','CData',imread('initYellow.jpg')) set(obj.h_load,'Value',0,'Tag','on','CData',imread('loadYellow.jpg')) set(obj.h_pause,'Value',0,'Tag','off','CData',imread('pauseGray.jpg')) set(obj.h_run,'Value',0,'Tag','off','CData',imread('runGray.jpg')) set(obj.h_abort,'Value',0,'Tag','off','CData',imread('abortGray.jpg')) case 42 % -- successfully loaded experiment file set(obj.h_init,'Value',0,'Tag','on','CData',imread('initYellow.jpg')) set(obj.h_load,'Value',0,'Tag','on','CData',imread('loadedYellow.jpg')) set(obj.h_pause,'Value',0,'Tag','off','CData',imread('pauseGray.jpg')) set(obj.h_run,'Value',0,'Tag','on','CData',imread('runYellow.jpg')) set(obj.h_abort,'Value',0,'Tag','off','CData',imread('abortGray.jpg')) case 50 % Begin running an experiment file (FUNCTION runExperiment) set(obj.h_init,'Value',0,'Tag','off','CData',imread('initGray.jpg')) set(obj.h_load,'Value',0,'Tag','off','CData',imread('loadedGray.jpg')) set(obj.h_pause,'Value',0,'Tag','on','CData',imread('pauseYellow.jpg')) set(obj.h_run,'Value',1,'Tag','off','CData',imread('runGreen.jpg')) set(obj.h_abort,'Value',0,'Tag','on','CData',imread('abortRed.jpg')) case 51 % -- unsuccessfully ran experiment for ii=1:flickerReps set(obj.h_run,'Value',1,'Tag','off','CData',imread('runRed.jpg')) pause(flickerLen) set(obj.h_run,'Value',1,'Tag','off','CData',imread('runGreen.jpg')) pause(flickerLen) end set(obj.h_init,'Value',0,'Tag','on','CData',imread('initYellow.jpg')) set(obj.h_load,'Value',0,'Tag','on','CData',imread('loadedYellow.jpg')) set(obj.h_pause,'Value',0,'Tag','off','CData',imread('pauseGray.jpg')) set(obj.h_run,'Value',0,'Tag','on','CData',imread('runYellow.jpg')) set(obj.h_abort,'Value',0,'Tag','off','CData',imread('abortGray.jpg')) case 52 % -- successfully ran experiment set(obj.h_init,'Value',0,'Tag','on','CData',imread('initYellow.jpg')) set(obj.h_load,'Value',0,'Tag','on','CData',imread('loadedYellow.jpg')) set(obj.h_pause,'Value',0,'Tag','off','CData',imread('pauseGray.jpg')) set(obj.h_run,'Value',0,'Tag','on','CData',imread('runYellow.jpg')) set(obj.h_abort,'Value',0,'Tag','off','CData',imread('abortGray.jpg')) case 60 % Begin aborting run (FUNCTION abortExperiment) set(obj.h_init,'Value',0,'Tag','off','CData',imread('initGray.jpg')) set(obj.h_load,'Value',0,'Tag','off','CData',imread('loadedGray.jpg')) set(obj.h_pause,'Value',0,'Tag','off','CData',imread('pauseGray.jpg')) set(obj.h_run,'Value',0,'Tag','off','CData',imread('runGray.jpg')) set(obj.h_abort,'Value',1,'Tag','off','CData',imread('abortRed.jpg')) case 61 % -- failed to abort run for ii=1:flickerReps set(obj.h_abort,'Value',1,'Tag','off','CData',imread('abortGray.jpg')) pause(flickerLen) set(obj.h_abort,'Value',1,'Tag','off','CData',imread('abortRed.jpg')) pause(flickerLen) end set(obj.h_init,'Value',0,'Tag','on','CData',imread('initYellow.jpg')) set(obj.h_load,'Value',0,'Tag','on','CData',imread('loadedYellow.jpg')) set(obj.h_pause,'Value',0,'Tag','off','CData',imread('pauseGray.jpg')) set(obj.h_run,'Value',0,'Tag','on','CData',imread('runYellow.jpg')) set(obj.h_abort,'Value',0,'Tag','off','CData',imread('abortGray.jpg')) case 62 % -- successfully aborted run set(obj.h_init,'Value',0,'Tag','on','CData',imread('initYellow.jpg')) set(obj.h_load,'Value',0,'Tag','on','CData',imread('loadedYellow.jpg')) set(obj.h_pause,'Value',0,'Tag','off','CData',imread('pauseGray.jpg')) set(obj.h_run,'Value',0,'Tag','on','CData',imread('runYellow.jpg')) set(obj.h_abort,'Value',0,'Tag','off','CData',imread('abortGray.jpg')) otherwise end pause(.05) catch errorTxt = {' Issue: Button management error.' ' Action: None.' ' Location: in arlas.buttonManager.' }; errorMsgARLas(errorTxt); obj.printError(ME) end end % define the five main functions ------------------ function initPlayrec(varargin) % initialize playrec and arlas obj = varargin{1}; try % if init tag is set to off (not available), return if strcmp(obj.h_init.Tag,'off') obj.h_init.Value = 0; return else obj.deadInTheWater = 0; end catch end try % get rid of any open figures from playrecARLas obj.objPlayrec.killPlots % if there are any open playrecARLas figures, make them disappear catch end try % delete any currently open playrecARLas objects delete(obj.objPlayrec) catch end try % get rid of any open figures from initARLas obj.objInitARLas.killPlots catch end try % delete any currently open initARLas objects delete(obj.objInitARLas); catch end try % set init button to on and other buttons to off obj.buttonManager(20) set(obj.VIEW,'Title','VIEW: Initialize') catch end try % instantiate a new object of class initARLas obj.objInit = initARLas(obj); % instantiate a new object of class initARLas obj.objInit.initGui % create the init gui d = dir([obj.map.sysConfigs,'*.mat']); % look for previously saved initialization files if size(d,1) >= 1 % if files exist % ask user which one to use [fileName,pathName] = uigetfile([obj.map.sysConfigs,'*.mat'],'Select the initialization file.'); if fileName == 0 % if user canceled and did not pick a file obj.buttonManager(21) % flash an error and discover new files obj.objInit.discover return end try % if previously saved initialization values exist, try to use them dummy = load([pathName,fileName]); % load the saved initialization obj.objInit.trySavedValues(dummy); obj.buttonManager(22) catch ME %----------------------------------------------------- if obj.deadInTheWater == 1 return else obj.deadInTheWater = 1; end errorTxt = {' Issue: Unable to initialize: arlas.m using saved values, function init.playrec.' ' Action: Create new initialization.' ' Location: arlas.initPlayrec.' }; errorMsgARLas(errorTxt); obj.buttonManager(21) obj.printError(ME) end else alertTxt = {' Issue: No saved System Configuration Files wre detected.' ' Action: Discovering current system devices.' ' Location: arlas.initPlayrec.' }; alertMsgARLas(alertTxt); obj.buttonManager(21) obj.objInit.discover set(obj.VIEW,'Title','VIEW: ') end catch ME if obj.deadInTheWater == 1 return else obj.deadInTheWater = 1; end errorTxt = {' Issue: Unable to initialize: Unexpeced error.' ' Action: None.' ' Location: arlas.initPlayrec.' }; errorMsgARLas(errorTxt); obj.buttonManager(21) obj.printError(ME) end end function loadExperiment(varargin) % select an experiment to run obj = varargin{1}; try % if init tag is set to off (not available), return if strcmp(obj.h_init.Tag,'off') obj.h_init.Value = 0; return else obj.deadInTheWater = 0; end catch end try % if load tag is set to off (not available), return if strcmp(obj.h_load.Tag,'off') obj.h_load.Value = 0; return end catch end try % get rid of any existing objInit plots obj.objInit.killPlots catch end try % attempt to load an experiment file obj.buttonManager(40) set(obj.VIEW,'Title','VIEW: Load Experiment File') obj.expPathName = obj.map.experiments; obj.expFileName = uigetfile([obj.expPathName,obj.sep,'*.m'],'Load Experiment File'); if obj.expFileName == 0 % if user canceled and did not pick a file obj.buttonManager(41) % flash an error and simply return set(obj.VIEW,'Title','VIEW: ') return else obj.expFileName = obj.expFileName(1:end-2); % strip off the .m extension end set(obj.VIEW,'Title','VIEW: ') catch ME set(obj.VIEW,'Title','VIEW: ') obj.expFileName = 0; obj.h_load.TooltipString = 'LOAD experiment file'; obj.buttonManager(41) obj.printError(ME) return end try % if there is more than one experiment file with the same name, alert user if ~obj.expFileName % if no experiment file was chosen or process was aborted return else % if an experiment file was chosen dummy = which(obj.expFileName,'-ALL'); % get all instances of chosen file name nFiles = length(dummy); % number of files with chosen name if nFiles > 1 warnTxt = {' Issue: More than one experiment file with this name exists on the search path.' ' Action: Highly reccommended that you remove duplicate files.' ' Location: arlas.load.' }; warnMsgARLas(warnTxt); obj.h_load.TooltipString = ['LOADED EXPERIMENT: ',obj.expFileName]; obj.buttonManager(41) for ii=1:nFiles disp(dummy(ii)) end else end end catch end try % set the tool-tip string if ~obj.expFileName % if no experiment file was chosen or process was aborted obj.h_load.TooltipString = 'LOAD experiment file'; obj.buttonManager(41) else % if an experiment file was chosen obj.h_load.TooltipString = ['LOADED EXPERIMENT: ',obj.expFileName]; obj.buttonManager(42) end catch ME if obj.deadInTheWater == 1 return else obj.deadInTheWater = 1; end errorTxt = {' Issue: Unable to set tool-tip string.' ' Action: None.' ' Location: arlas.load.' }; errorMsgARLas(errorTxt); obj.buttonManager(21) obj.printError(ME) end end function pauseExperiment(varargin) % pause the currently-running experiment obj = varargin{1}; try % if pause tag is set to off (not available), return if strcmp(obj.h_pause.Tag,'off') obj.h_pause.Value = 0; return else obj.deadInTheWater = 0; end catch end try % turn pause on or off obj.buttonManager(30) % starting pause routine... pause(0.001) if obj.objPlayrec.pauseRun == 1 % if the run is already paused obj.buttonManager(33) pause(0.001) obj.objPlayrec.pauseRun = 0; % turn pause off else % if the run is not paused obj.buttonManager(32) % starting pause routine obj.objPlayrec.pauseRun = 1; % turn pause on end catch ME if obj.deadInTheWater == 1 return else obj.deadInTheWater = 1; end errorTxt = {' Issue: Error pausing playrec.' ' Action: None.' ' Location: arlas.pauseExperiment.' }; errorMsgARLas(errorTxt); obj.printError(ME) obj.buttonManager(31) obj.objPlayrec.pauseRun = 0; % turn pause off return end end function runExperiment(varargin) % run the currently-loaded experiment obj = varargin{1}; try % if run tag is set to off (not available), return if strcmp(obj.h_run.Tag,'off') obj.h_run.Value = 0; return else obj.deadInTheWater = 0; end catch end try % get rid of any existing objInit plots obj.objInit.killPlots catch end try % get the subject, experiment, and operator IDs obj.buttonManager(50) set(obj.VIEW,'Title','VIEW: Playback & Record') obj.killRun = 0; obj.getSubjID uiwait(obj.h_subjID) % wait until the figure is closed if obj.subjID_OK == 0 obj.buttonManager(51) % unsuccessful; possibly user closed box with upper right x set(obj.VIEW,'Title','VIEW: ') return end catch ME if obj.deadInTheWater == 1 return else obj.deadInTheWater = 1; end errorTxt = {' Issue: Error getting subject ID.' ' Action: None.' ' Location: in arlas.runExperiment.' }; errorMsgARLas(errorTxt); obj.buttonManager(51) obj.printError(ME) set(obj.VIEW,'Title','VIEW: ') return end try % run the experiment try % delete any currently open playrecARLas objects delete(obj.objPlayrec) catch end try % initialize a new object of class playrecARLas obj.objPlayrec = playrecARLas(obj.objInit); catch ME if obj.deadInTheWater == 1 return else obj.deadInTheWater = 1; end errorTxt = {' Issue: Error creating new playrecARLas object.' ' Action: None.' ' Location: in arlas.runExperiment.' }; errorMsgARLas(errorTxt); obj.buttonManager(51) obj.printError(ME) set(obj.VIEW,'Title','VIEW: ') return end fh = str2func(obj.expFileName); % create a function handle fh(obj); % try executing the experiment file obj.buttonManager(52) % successful completion set(obj.VIEW,'Title','VIEW: ') catch ME obj.objPlayrec.killPlots % get rid of playrecARLas plots obj.killRun = 1; if obj.deadInTheWater == 1 return else obj.deadInTheWater = 1; end if obj.objPlayrec.killRun == 1 errorTxt = {' Issue: Run aborted by user.' ' Action: Run stopped early.' ' Location: in arlas.runExperiment.' }; else errorTxt = {' Issue: Error in experiment file.' ' Action: Run stopped early.' [' Location: ',obj.expFileName,'.m; Reported in arlas.runExperiment.'] }; indx = []; for ii=1:length(ME.stack) if strfind(obj.expFileName,ME.stack(ii).name) == 1 indx = [indx;ii]; end end if ~isempty(indx) me.identifier = ME.identifier; me.message = ME.message; me.stack = ME.stack(indx(1)); ME = me; end end errorMsgARLas(errorTxt); obj.buttonManager(51) obj.printError(ME) end end function abortExperiment(varargin) % abort the currently-running experiment obj = varargin{1}; try % if abort tag is set to off (not available), return if strcmp(obj.h_abort.Tag,'off') obj.h_abort.Value = 0; return else obj.deadInTheWater = 0; end catch end try % manage abort buttons and view obj.buttonManager(60) set(obj.VIEW,'Title','VIEW: Abort') catch end try % try and abort sequence try obj.objPlayrec.killRun = 1; catch end try obj.killRun = 1; catch end pause(0.01) try playrec('delPage'); catch end catch ME if obj.deadInTheWater == 1 return else obj.deadInTheWater = 1; end errorTxt = {' Issue: Unsuccessful abort attempt.' ' Action: Abort not completed.' ' Location: in arlas.abortExperiment.' }; errorMsgARLas(errorTxt); obj.buttonManager(61) % aborted unsuccesfully (with unexpected errors) obj.printError(ME) return end try % get rid of remaining plots obj.objPlayrec.killPlots catch end try % report aborted successfully obj.buttonManager(62) catch end end % functions that get and return values for use in experiment files -------- function [samplingRate] = fs(varargin) % return the current sampling rate obj = varargin{1}; try samplingRate = obj.objInit.fs_now; catch ME end end function setRecList(varargin) % define the input channels to be used for recording % Usage: obj.setRecList(ch,label,micSens,gain); % Specify channel number for each (1 through maxN, where maxN is the maximum for the sound card) % For each, specify a label, mic sensitivity, and gain. % Label is a string for idenfification and file saving purposes % Mic sens is in V/Pa. If no microphone is used, set = 1. % Gain refers to hardware gain applied prior to ADC by the sound card. Specify in dB. obj = varargin{1}; try % check for correct number, type, and value of inputs if size(varargin,2) ~= 5 disp('Incorrect number of inputs') return end ch = varargin{2}; % channel designation ok = obj.checkInput_ch(ch); if ~ok return end label = varargin{3}; micSens = varargin{4}; ampGain = varargin{5}; maxGain = 200; % maximum gain allowed. This added as a caution to avoid gain entered in linear units if ampGain > maxGain errorTxt = {' Issue: Gain exceeds maxGain of 200 dB.' ' Fix: Ensure gain is entered as a dB value, not as a linear value.' ' Location: in playrecARLas.setRecList.' }; errorMsgARLas(errorTxt); return end catch ME txt = 'problem with specified input arguments'; errorTxt = {[' Issue: Error specifying stimulus: ',txt] ' Action: None.' ' Location: in arlas.setRecList.' }; errorMsgARLas(errorTxt); obj.printError(ME) end try % add new values to objPlayrec object indx = find(obj.objPlayrec.recChanList==ch); % check to see if chan already exists if isempty(indx) indx = length(obj.objPlayrec.recChanList) + 1; end obj.objPlayrec.recChanList(1,indx) = ch; obj.objPlayrec.micSens(1,indx) = micSens; obj.objPlayrec.ampGain(1,indx) = ampGain; obj.objPlayrec.label{1,indx} = label; catch ME txt = 'problem with specified channels'; errorTxt = {[' Issue: Error specifying stimulus: ',txt] ' Action: None.' ' Location: in arlas.setRecList.' }; errorMsgARLas(errorTxt); obj.printError(ME) end end function setPlayList(varargin) % define the output channels to be used for recording % Usage: obj.setPlayList(stimulus,ch); % Load one vector at a time. Each vector is a channel of output. % Use vector of zeros if desire an output channel with no output. % Specify channel number for each (1 through maxN, where maxN is the maximum for the sound card) obj = varargin{1}; if size(varargin,2) ~= 3 disp('Incorrect number of inputs') return end ch = varargin{3}; % channel designation ok = obj.checkInput_ch(ch); if ~ok obj.objPlayrec.killRun = 1; obj.objPlayrec.killPlots return end stim = varargin{2}; % stimulus R = size(stim,1); if R < 2 errorTxt = {' Issue: Error specifying stimulus: number of rows must be > 1' ' Action: None.' ' Location: in playrecARLas.setPlayList.' }; errorMsgARLas(errorTxt); return end try % if input is correct format, load for playback indx = find(obj.objPlayrec.playChanList==ch); % check to see if chan already exists if isempty(indx) indx = length(obj.objPlayrec.playChanList) + 1; end obj.objPlayrec.playChanList(1,indx) = ch; obj.objPlayrec.loadingDock.(matlab.lang.makeValidName(['Ch',num2str(ch)])) = stim; catch ME errorTxt = {[' Issue: Error specifying stimulus: ',txt] ' Action: None.' ' Location: in playrecARLas.setPlayList.' }; errorMsgARLas(errorTxt); end end function clearRecList(varargin) % clear previously used input channels % Usage: obj.clearRecList(ch) --> this will delete a specific channel % obj.clearRecList([3 2 5]) --> this will delete all channels specified in the vector % obj(clearRecList --> this will delete all channels (except ch0 default) obj = varargin{1}; if size(varargin,2) == 1 obj.objPlayrec.recChanList = 0; obj.objPlayrec.micSens = 1; obj.objPlayrec.ampGain = 0; n = length(obj.objPlayrec.label); for ii=n:-1:2 obj.objPlayrec.label{1,ii} = []; end counter = 1; for ii=1:length(obj.objPlayrec.label) if ~isempty(obj.objPlayrec.label{1,ii}) temp{1,counter} = obj.objPlayrec.label{1,ii}; counter = counter + 1; end end obj.objPlayrec.label = temp; elseif size(varargin,2) == 2 try ch = varargin{2}; for jj=1:length(ch) ok = obj.checkInput_ch(ch(jj)); if ~ok obj.objPlayrec.killRun = 1; obj.objPlayrec.killPlots return end indx = find(obj.objPlayrec.recChanList==ch(jj)); % check to see if chan already exists if ~isempty(indx) obj.objPlayrec.recChanList(indx) = []; obj.objPlayrec.micSens(indx) = []; obj.objPlayrec.ampGain(indx) = []; obj.objPlayrec.label{1,indx} = []; counter = 1; for ii=1:length(obj.objPlayrec.label) if ~isempty(obj.objPlayrec.label{1,ii}) temp{1,counter} = obj.objPlayrec.label{1,jj}; counter = counter + 1; end end obj.objPlayrec.label = temp; end end catch errorTxt = {' Issue: Error deleting recording channel.' ' Action: None.' ' Location: in playrecARLas.clearRecList.' }; errorMsgARLas(errorTxt); end else disp('Incorrect number of inputs') return end end function clearPlayList(varargin) % clear previously used input channels % Usage: obj.clearPlayList(ch) --> this will delete a specific channel % obj.clearPlayList([3 2 5]) --> this will delete all channels specified in the vector % obj(clearPlayList --> this will delete all channels (except ch0 default) obj = varargin{1}; if size(varargin,2) == 1 obj.objPlayrec.playChanList = 0; names = fieldnames(obj.objPlayrec.loadingDock); for ii=2:size(names,1) obj.objPlayrec.loadingDock = rmfield(obj.objPlayrec.loadingDock,names{ii}); end elseif size(varargin,2) == 2 try ch = varargin{2}; for jj=1:length(ch) ok = obj.checkInput_ch(ch(jj)); if ~ok obj.objPlayrec.killRun = 1; obj.objPlayrec.killPlots return end indx = find(obj.objPlayrec.playChanList==ch(jj)); % check to see if chan already exists if ~isempty(indx) obj.objPlayrec.playChanList(indx) = []; name = ['Ch',num2str(ch(jj))]; obj.objPlayrec.loadingDock = rmfield(obj.objPlayrec.loadingDock,name); end end catch errorTxt = {' Issue: Error deleting recording channel.' ' Action: None.' ' Location: in playrecARLas.clearRecList.' }; errorMsgARLas(errorTxt); end else disp('Incorrect number of inputs') return end end function getRecList(varargin) % list the currently loaded input channels obj = varargin{1}; indx = find(obj.objPlayrec.recChanList); nChans = length(indx); disp(' ') disp('Current recChanList: ') for ii=1:nChans ch = obj.objPlayrec.recChanList(1,indx(ii)); micSens = obj.objPlayrec.micSens(1,indx(ii)); ampGain = obj.objPlayrec.ampGain(1,indx(ii)); label = obj.objPlayrec.label{1,indx(ii)}; disp(' ') disp([sprintf('%s','Channel Number = '),sprintf('%d',ch)]) disp([sprintf('%s','Mic Sensitivity = '),sprintf('%d',micSens)]) disp([sprintf('%s','Amplifier Gain = '),sprintf('%d',ampGain)]) disp([sprintf('%s','Channel Label = '),sprintf('%s',label)]) end end function getPlayList(varargin) % list the currently loaded output channels obj = varargin{1}; indx = find(obj.objPlayrec.playChanList); nChans = length(indx); disp(' ') disp('Current playChanList: ') for ii=1:nChans ch = obj.objPlayrec.playChanList(1,indx(ii)); disp(' ') disp([sprintf('%s','Channel Number = '),sprintf('%d',ch)]) end end function setNReps(varargin) % set the number of playback/record repetitions obj = varargin{1}; if nargin < 2 error('setNReps must be given an input argument. Example: obj.setNReps(50);') end N = varargin{2}; if N < 1 error('number of repetitions mube be >= 1') end N = round(N); % force N to be an integer %obj.objPlayrec.nReps = N; %obj.objPlayrec.setNReps({N},{'ok'}); obj.objPlayrec.setNReps(N); end function [nReps] = getNReps(varargin) % get the number of playback/record repetitions obj = varargin{1}; nReps = obj.objPlayrec.nReps; end function setFilter(varargin) % turn on/off the HP IIR filter obj = varargin{1}; toggle = varargin{2}; if toggle == 0 || toggle == 1 obj.objPlayrec.doFilter = toggle; else error('Input to setFilter must be 0 (off) or 1 (on).') end end function run(varargin) % run arlasPlayrec (collecte dataO obj = varargin{1}; obj.objPlayrec.run; end function [toggle] = getFilter(varargin) % turn on/off the HP IIR filter obj = varargin{1}; toggle = obj.objPlayrec.doFilter; end function [header,data] = retrieveData(varargin) % return the header and recording matrix obj = varargin{1}; partial = varargin{2}; if ~isa(partial,'char') errorTxt = {' Issue: Error specifying file to retrieve: input is not a string.' ' Fix: Specify a valid partial or full file name, enclosed in quotes.' ' Location: in playrecARLas.retrieveData.' }; errorMsgARLas(errorTxt); return end indx1 = strfind(obj.objPlayrec.savedFiles,partial); indx2 = find(~(cellfun('isempty',indx1))); if isempty(indx2) errorTxt = {' Issue: Error specifying file to retrieve: no match.' ' Fix: Specify a valid partial or full file name, enclosed in quotes.' ' Location: in playrecARLas.retrieveData.' }; errorMsgARLas(errorTxt); return end if length(indx2) > 1 errorTxt = {' Issue: Error specifying file to retrieve: more than one match.' ' Fix: Be more specific in giving a partial or full file name, enclosed in quotes.' ' Location: in playrecARLas.retrieveData.' }; errorMsgARLas(errorTxt); return end fileName = obj.objPlayrec.savedFiles{indx2}; % the name of the file saved to input channel 1 pathName = obj.objPlayrec.savedFilesPath; % the location of the saved files dummy = load([pathName,fileName]); % dummy contains two fields: header and data header = dummy.header; data = dummy.data; end % define supporting functions function getSubjID(varargin) % display dialog box for subject, experiment, and operator ID obj = varargin{1}; try delete(obj.h_subjID) catch end obj.subjID_OK = 0; % reset to zero height = 105; width = 105; scrsz = get(0,'ScreenSize'); % get the current screen size left = round(scrsz(4) * .05); bottom = scrsz(4) * .1; bottom = bottom + (1.4*105); rect = [left, bottom, width*5, height*2]; obj.h_subjID = figure('Position',rect); set(obj.h_subjID,'Name',' ','NumberTitle','off','MenuBar','none','Resize','off','Color',[1 1 1]) left = 290; width = 150; height = 40; bottom = 150; % SUBJECT ID obj.h_subjLabel = uicontrol('Style','text','String','Subject ID','FontSize',13,... 'position',[left bottom width height],'parent',obj.h_subjID,'HandleVisibility','off',... 'BackgroundColor',[1 1 1],'FontAngle','italic','HorizontalAlignment','left','Visible','on'); left = 30; width = 250; height = 30; bottom = 162; obj.h_subjBox = uicontrol('Style','edit','String',obj.subjectID,'FontSize',13,... 'position',[left bottom width height],'parent',obj.h_subjID,'HandleVisibility','off',... 'BackgroundColor',[1 1 1],'Visible','on','HorizontalAlignment','left'); left = 290; width = 150; height = 40; bottom = 110; % EXPERIMENT ID obj.h_expLabel = uicontrol('Style','text','String','Experiment ID','FontSize',13,... 'position',[left bottom width height],'parent',obj.h_subjID,'HandleVisibility','off',... 'BackgroundColor',[1 1 1],'FontAngle','italic','HorizontalAlignment','left','Visible','on'); left = 30; width = 250; height = 30; bottom = 122; obj.h_expBox = uicontrol('Style','edit','String',obj.experimentID,'FontSize',13,... 'position',[left bottom width height],'parent',obj.h_subjID,'HandleVisibility','off',... 'BackgroundColor',[1 1 1],'Visible','on','HorizontalAlignment','left'); left = 290; width = 150; height = 40; bottom = 70; % OPERATOR INITIALS obj.h_opLabel = uicontrol('Style','text','String','Operator Initials','FontSize',13,... 'position',[left bottom width height],'parent',obj.h_subjID,'HandleVisibility','off',... 'BackgroundColor',[1 1 1],'FontAngle','italic','HorizontalAlignment','left','Visible','on'); left = 30; width = 125; height = 30; bottom = 82; obj.h_opBox = uicontrol('Style','edit','String',obj.operatorID,'FontSize',13,... 'position',[left bottom width height],'parent',obj.h_subjID,'HandleVisibility','off',... 'BackgroundColor',[1 1 1],'Visible','on','HorizontalAlignment','left'); left = 385; width = 130; height = 50; bottom = 10; obj.h_enterSubjID = uicontrol('Style','pushbutton','BackgroundColor',[1 1 0],... 'Position',[left bottom width height],'parent',obj.h_subjID,... 'String','Enter ID','FontSize',13,'Visible','on','BusyAction','cancel',... 'Interruptible','off','Callback',@obj.enterID); end function enterID(varargin) % get subject, experiment, and operator IDs and save them; create folders obj = varargin{1}; subjID = get(obj.h_subjBox,'String'); % check subject ID is present if ~isempty(subjID) obj.subjectID = subjID; else uiwait(errordlg('Subject ID cannot be an empty string.','Subject ID Error','modal')) return end expID = get(obj.h_expBox,'String'); % check experiment ID is present if ~isempty(expID) d = dir(obj.map.data); N = length(d); match = 0; for ii=3:N % look to see if experiment folder already exists if d(ii).isdir if strcmp(d(ii).name,expID) match = 1; end end if match == 1 break end end if match obj.experimentID = expID; else button = questdlg(['Experiment ID does not exist. Create new directory?'],... 'Create Experiment Directory','Yes','No','No'); if strcmp(button,'No') return else success = mkdir(obj.map.data,expID); if success addpath([obj.map.data,expID]) obj.experimentID = expID; else error('Unable to create new Experiment Directory.') end end end d = dir([obj.map.data,expID]); N = length(d); match = 0; for ii=3:N % look for existing subject ID if d(ii).isdir if strcmp(d(ii).name,obj.subjectID) match = 1; end end if match == 1 break end end if ~match success = mkdir([obj.map.data,expID],obj.subjectID); pathName = [obj.map.data,expID,obj.sep,obj.subjectID]; addpath(pathName) if ~success error('Unable to create directory for subject ID.') end end else uiwait(errordlg('Experiment ID cannot be an empty string.','Experiment ID Error','modal')) return end opID = get(obj.h_opBox,'String'); if ~isempty(opID) obj.operatorID = opID; else uiwait(errordlg('Operator Initials cannot be an empty string.','Operator ID Error','modal')) return end % if the ID input is all good, the following lines will execute obj.subjID_OK = 1; delete(obj.h_subjID) end function printError(varargin) obj = varargin{1}; ME = varargin{2}; disp(ME.identifier) disp(ME.message) disp(ME.stack(1).line) end function [ok] = checkInput_ch(varargin) % check input arguments for the functions defineInput and defineOutput ok = 1; obj = varargin{1}; ch = varargin{2}; if sum(size(ch)) ~= 2 & ok == 1 ok = 0; txt = 'Channel must be a scalar value; not vector or matrix.'; end if ~isa(ch,'numeric') & ok == 1 ok = 0; txt = 'Channel must be data type numeric.'; end if mod(ch,1)~= 0 & ok == 1 ok = 0; txt = 'Channel must be an integer.'; end if ch < 1 & ok == 1 ok = 0; txt = 'Channel must be >= 1.'; end if ch > obj.objInit.chans_out & ok == 1 ok = 0; txt = 'Channel must be <= to max number of initialized channels'; end if ~ok obj.deadInTheWater = 1; errorTxt = {[' Issue: Error specifying channel: ',txt] ' Action: None.' ' Location: in playrecARLas.checkInput_ch.' }; errorMsgARLas(errorTxt); end end function [ok] = checkForErrors(varargin) % check to see if experiment should continue or stop due to errors obj = varargin{1}; %ok = ~obj.objPlayrec.killRun; % old way; do not use! ok = obj.killRun; errorTxt = {' Issue: the arlas method obj.checkForErrors is no longer supported.' ' Action: Replace with the following lines:' ' if obj.killRun' ' return' ' end' }; errorMsgARLas(errorTxt); obj.buttonManager(51) end end end
<template> <v-container class="fill-height"> <v-row justify="center" align="center"> <v-col cols="12"> <v-card> <v-card-title class="headline"> Tweets </v-card-title> </v-card> </v-col> <v-col cols="12"> <tweet-form :form-label="'New Tweet'" @new-tweet="addNewTweet" /> </v-col> <v-col v-for="item in tweets" :key="item.id" cols="12"> <tweet :tweet="item" /> </v-col> </v-row> </v-container> </template> <script> import { mapState } from "pinia" import { useBaseStore } from "@/stores/baseStore" import { usecoreStore } from "@/stores/coreStore" import Tweet from "@/components/Tweet.vue" import TweetForm from "@/components/TweetForm.vue" export default { name: "TweetsList", components: { Tweet, TweetForm }, setup() { const baseStore = useBaseStore() const coreStore = usecoreStore() return { baseStore, coreStore } }, computed: { ...mapState(usecoreStore, ["tweets", "tweetsLoading"]), }, mounted() { this.getTweets() }, methods: { getTweets() { this.coreStore.getTweets() }, async addNewTweet(tweet) { const newTweet = await this.coreStore.addNewTweet(tweet) this.baseStore.showSnackbar(`New tweet added #${ newTweet.id }`) this.getTweets() }, }, } </script> <style scoped> .done { text-decoration: line-through; } </style>
import { useEffect, useRef, useState } from 'react'; import { useDebounce } from '../hooks/useDebounce'; import { useListenKey } from '../hooks/useListenKey'; export function Navbar({ children }: { children?: React.ReactNode }) { return ( <nav className="navbar"> <ul> <Logo /> {children} </ul> </nav> ); } function Logo() { return ( <li className="logo"> <span role="img">🍿</span> <h1>usePopcorn</h1> </li> ); } export function Search({ onSearch }: { onSearch: (query: string) => void }) { const [query, setQuery] = useState(''); const debouncedQuery = useDebounce(query, 1000); const inputEl = useRef<HTMLInputElement>(null); useEffect(() => { onSearch(debouncedQuery); }, [debouncedQuery]); useListenKey('Enter', () => { if (document.activeElement === inputEl.current) return; inputEl.current?.focus(); }); const handleSubmitSearch = (e: React.KeyboardEvent<HTMLInputElement>) => { if (e.key === 'Enter') { onSearch(query.trim()); } }; return ( <li className="search"> <input ref={inputEl} type="text" placeholder="Search movies..." value={query} onChange={e => setQuery(e.currentTarget.value)} onKeyDown={handleSubmitSearch} /> </li> ); } export function NumResults({ num }: { num: number | string }) { return ( <li className="num-results"> <p> Found <b>{num}</b> movies </p> </li> ); }
import { Switch, Route, NavLink } from 'react-router-dom'; import GamesList from '../Games/GamesList'; import GamesID from '../Games/GamesID'; import HeaderCSS from './HeaderCSS'; function Header() { const nameSite = 'React Games'; return ( <HeaderCSS> <header> <div className='MessageWelcome'> <p className='Hello'>Welcome to {nameSite}!</p> </div> <ul className='Header'> <li className='items'> <NavLink exact to='/'> Main Page </NavLink> </li> <li className='items'> <NavLink to='/games'>Games</NavLink> </li> </ul> </header> <main> <Switch> <Route exact path='/' /> <Route exact path='/games' component={GamesList} /> <Route path='/games/:id' component={GamesID} /> </Switch> </main> </HeaderCSS> ); } export default Header;
import React, { useReducer, createContext, useCallback, useMemo, useRef } from 'react'; import { getPage, getLastPageNum, getProductURLs, getProductInfo, hasResult, hasProhibitedIngredients, downloadExcel, } from '../../js/scrap'; import prohibitedIngredients from '../../js/ingredients'; import myReduce from '../../js/myReduce'; const Context = createContext({}); function Store({ children }) { // console.log('Store render'); const [state, dispatch] = useReducer(myReduce, { input: '', keyword: '', curPageNum: 0, lastPageNum: 0, page: {}, }); const ingredients = useRef(prohibitedIngredients); const addProduct = useCallback( async (page, pageNum) => { try { const products = []; for (let URL of getProductURLs(page)) { const product = await getProductInfo(URL); const content = product.title + product.overview; if (!hasProhibitedIngredients(ingredients.current, content)) { products.push(product); dispatch({ type: 'SET_PAGE_PRODUCTS', payload: { pageNum, products } }); } } } catch (err) { console.error(err); } }, [ingredients] ); const onExportExcel = useCallback(async () => { try { await downloadExcel(state.page[state.curPageNum]); } catch (err) { console.error(err); } }, [state.page, state.curPageNum]); const onMove = useCallback( async (to) => { if (to < 1 || to > state.lastPageNum) { return; } if (!state.page[to]) { const page = await getPage(`https://kr.iherb.com/search?kw=${state.keyword}&p=${to}`); addProduct(page, to); } dispatch({ type: 'SET_CURRENT_PAGE_NUM', payload: to }); }, [addProduct, state] ); const onChange = useCallback(({ target: { value } }) => { dispatch({ type: 'INPUT_VALUE', payload: value }); }, []); const onSearch = useCallback( async ({ type, key }) => { if (type !== 'click' && (type !== 'keydown' || key !== 'Enter')) { return; } const { input } = state; if (input === '') { alert('키워드를 입력 해 주세요.'); return; } const page = await getPage(`https://kr.iherb.com/search?kw=${input}`); if (!hasResult(page)) { alert('결과가 없습니다.'); return; } dispatch({ type: 'SET_KEYWORD', payload: input }); dispatch({ type: 'SET_LAST_PAGE_NUM', payload: getLastPageNum(page) }); addProduct(page, 1); dispatch({ type: 'SET_CURRENT_PAGE_NUM', payload: 1 }); }, [state, addProduct] ); return ( <Context.Provider value={{ state, dispatch, onChange, onSearch, onExportExcel, onMove }}> {children} </Context.Provider> ); } export { Context }; export default Store;
export function Users({ users, isColored, deleteOne, changeFilter }) { return ( <table className="w-full"> <thead> <tr> <th className="text-center" colSpan={1}> Image </th> <th className="text-center" colSpan={2}> <button onClick={() => changeFilter('firstname')}>Name</button> </th> <th className="text-center" colSpan={2}> <button onClick={() => changeFilter('lastname')}>Last name</button> </th> <th className="text-center" colSpan={3}> <button onClick={() => changeFilter('country')}>Country</button> </th> <th className="text-center" colSpan={2}> Actions </th> </tr> </thead> <tbody> {users.map((user) => { return ( <tr key={user.login.uuid} className={ isColored ? '[&:nth-child(2n-1)]:bg-gray-300 [&:nth-child(2n)]:bg-gray-200/80' : '' } > <td className="text-center border-2 border-white" colSpan={1}> <img className="rounded-sm mx-auto" src={user.picture.thumbnail} alt={`${user.name.first} ${user.name.last}`} /> </td> <td className="text-center border-2 border-white" colSpan={2}> {user.name.first} </td> <td className="text-center border-2 border-white" colSpan={2}> {user.name.last} </td> <td className="text-center border-2 border-white" colSpan={3}> {user.location.country} </td> <td className="text-center border-2 border-white" colSpan={2}> <button className="rounded bg-gray-800 text-gray-200 py-2 px-4" onClick={() => deleteOne(user.login.uuid)} > Delete </button> </td> </tr> ); })} </tbody> </table> ); }
<?php /** * @copyright Copyright (c) 2016 Julius Härtl <jus@bitgrid.net> * * @author Julius Härtl <jus@bitgrid.net> * * @license GNU AGPL version 3 or any later version * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ namespace OCA\Direct_menu\Controller; use OCP\AppFramework\Http\TemplateResponse; use OCP\AppFramework\Http\DataDownloadResponse; use OCP\AppFramework\Utility\ITimeFactory; use OCP\IRequest; class AppController extends \OCP\AppFramework\Controller { public function __construct($appName, IRequest $request, ITimeFactory $timeFactory) { parent::__construct($appName, $request); $this->timeFactory = $timeFactory; } /** * @NoCSRFRequired * @PublicPage * * @return DataDownloadResponse */ public function stylesheet() { $inverted = false; if(\OCP\App::isEnabled('theming') && class_exists('\OCA\Theming\Util')) { $color = \OC::$server->getThemingDefaults()->getMailHeaderColor(); $util = \OC::$server->query(\OCA\Theming\Util::class); $inverted = $util->invertTextColor($color); } $navigation = \OC::$server->getNavigationManager()->getAll(); $navigationCount = count($navigation); // 250px for icon/appname // 170px for user menu + 1 icon spacing // 120px open search box $width = $navigationCount*50+250+170+120; $params = [ 'width' => $width, 'inverted' => $inverted ]; $template = new TemplateResponse('direct_menu', 'direct_menu', $params, 'blank'); $response = new DataDownloadResponse($template->render(), 'style', 'text/css'); $response->addHeader('Expires', date(\DateTime::RFC2822, $this->timeFactory->getTime())); $response->addHeader('Pragma', 'cache'); $response->cacheFor(3600); return $response; } }
package com.epam.dmgolub.gym.controller.mvc; import com.epam.dmgolub.gym.controller.ControllerUtilities; import com.epam.dmgolub.gym.dto.mvc.TraineeTrainingsSearchRequestDTO; import com.epam.dmgolub.gym.dto.mvc.TrainerTrainingsSearchRequestDTO; import com.epam.dmgolub.gym.dto.mvc.TrainingRequestDTO; import com.epam.dmgolub.gym.mapper.mvc.ModelToDtoMapper; import com.epam.dmgolub.gym.service.TraineeService; import com.epam.dmgolub.gym.service.TrainerService; import com.epam.dmgolub.gym.service.TrainingService; import com.epam.dmgolub.gym.service.TrainingTypeService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import javax.validation.Valid; import static com.epam.dmgolub.gym.controller.mvc.constant.Constants.NEW_TRAINING_VIEW_NAME; import static com.epam.dmgolub.gym.controller.mvc.constant.Constants.REDIRECT_TO_TRAINING_INDEX; import static com.epam.dmgolub.gym.controller.mvc.constant.Constants.TRAINEE; import static com.epam.dmgolub.gym.controller.mvc.constant.Constants.TRAINERS; import static com.epam.dmgolub.gym.controller.mvc.constant.Constants.TRAINING; import static com.epam.dmgolub.gym.controller.mvc.constant.Constants.TRAININGS; import static com.epam.dmgolub.gym.controller.mvc.constant.Constants.TRAINING_INDEX_VIEW_NAME; import static com.epam.dmgolub.gym.controller.mvc.constant.Constants.TRAINING_TYPES; import static com.epam.dmgolub.gym.controller.mvc.constant.Constants.TRAINING_VIEW_NAME; @Controller @RequestMapping("/trainings") public class TrainingController { private static final Logger LOGGER = LoggerFactory.getLogger(TrainingController.class); private final TraineeService traineeService; private final TrainerService trainerService; private final TrainingService trainingService; private final TrainingTypeService trainingTypeService; private final ModelToDtoMapper mapper; public TrainingController( final TraineeService traineeService, final TrainerService trainerService, final TrainingService trainingService, final TrainingTypeService trainingTypeService, final ModelToDtoMapper mapper ) { this.traineeService = traineeService; this.trainerService = trainerService; this.trainingService = trainingService; this.trainingTypeService = trainingTypeService; this.mapper = mapper; } @PostMapping() public String save( @ModelAttribute(TRAINING) @Valid final TrainingRequestDTO training, final BindingResult bindingResult, final Model model ) { LOGGER.debug("In save - validating new training"); if (bindingResult.hasErrors()) { ControllerUtilities.logBingingResultErrors(bindingResult, LOGGER, NEW_TRAINING_VIEW_NAME); model.addAttribute(TRAINEE, traineeService.findByUserName(training.getTraineeUserName())); model.addAttribute(TRAINERS, trainerService.findActiveTrainersAssignedOnTrainee(training.getTraineeUserName())); return NEW_TRAINING_VIEW_NAME; } trainingService.save(mapper.mapToTrainingModel(training)); LOGGER.debug("In save - training saved successfully. Redirecting to training index view"); return REDIRECT_TO_TRAINING_INDEX; } @GetMapping("/{id:\\d+}") public String findById(@PathVariable("id") final Long id, final Model model) { model.addAttribute(TRAINING, mapper.mapTrainingResponseDTO(trainingService.findById(id))); LOGGER.debug("In findById - Training with id={} fetched successfully. Returning training view name", id); return TRAINING_VIEW_NAME; } @GetMapping("/") public String findAll(final Model model) { model.addAttribute(TRAININGS, mapper.mapToTrainingResponseDTOList(trainingService.findAll())); final var trainingTypes = mapper.mapToTrainingTypeDTOList(trainingTypeService.findAll()); model.addAttribute(TRAINING_TYPES, trainingTypes); LOGGER.debug("In findAll - Trainings fetched successfully. Returning training index view name"); return TRAINING_INDEX_VIEW_NAME; } @GetMapping("/search-by-trainee") public String searchByTrainee( final @ModelAttribute @Valid TraineeTrainingsSearchRequestDTO traineeRequest, final BindingResult bindingResult, final Model model ) { LOGGER.debug("In searchByTrainee - Received a search request={}", traineeRequest); final var trainingTypes = mapper.mapToTrainingTypeDTOList(trainingTypeService.findAll()); model.addAttribute(TRAINING_TYPES, trainingTypes); if (bindingResult.hasErrors()) { ControllerUtilities.logBingingResultErrors(bindingResult, LOGGER, TRAINING_INDEX_VIEW_NAME); return TRAINING_INDEX_VIEW_NAME; } final var request = mapper.mapToTraineeTrainingsSearchRequest(traineeRequest); model.addAttribute(TRAININGS, trainingService.searchByTrainee(request)); return TRAINING_INDEX_VIEW_NAME; } @GetMapping("/search-by-trainer") public String searchByTrainer( final @ModelAttribute @Valid TrainerTrainingsSearchRequestDTO trainerRequest, final BindingResult bindingResult, final Model model ) { LOGGER.debug("In searchByTrainee - Received a search request={}", trainerRequest); model.addAttribute(TRAINING_TYPES, trainingTypeService.findAll()); if (bindingResult.hasErrors()) { ControllerUtilities.logBingingResultErrors(bindingResult, LOGGER, TRAINING_INDEX_VIEW_NAME); return TRAINING_INDEX_VIEW_NAME; } final var request = mapper.mapToTrainerTrainingsSearchRequest(trainerRequest); model.addAttribute(TRAININGS, trainingService.searchByTrainer(request)); return TRAINING_INDEX_VIEW_NAME; } }
<mat-toolbar color="primary"> <mat-toolbar-row> <span>Welcome to the page</span> <span class="example-spacer"></span> <button mat-raised-button color="warn" (click)="openDialog()">add user</button> </mat-toolbar-row> </mat-toolbar> <div class="container"> <div style="margin-top: 15px;"> <mat-form-field appearance="standard"> <mat-label>Filter</mat-label> <input matInput (keyup)="applyFilter($event)" placeholder="Ex. Mia" #input> </mat-form-field> <div class="mat-elevation-z8"> <table mat-table [dataSource]="dataSource" matSort> <!-- ID Column --> <ng-container matColumnDef="name"> <th mat-header-cell *matHeaderCellDef mat-sort-header> NAME </th> <td mat-cell *matCellDef="let row"> {{row.name | titlecase}} </td> </ng-container> <!-- Progress Column --> <ng-container matColumnDef="email"> <th mat-header-cell *matHeaderCellDef mat-sort-header> EMAIL </th> <td mat-cell *matCellDef="let row"> {{row.email }}</td> </ng-container> <!-- Name Column --> <ng-container matColumnDef="gender"> <th mat-header-cell *matHeaderCellDef mat-sort-header> GENDER </th> <td mat-cell *matCellDef="let row"> {{row.gender}} </td> </ng-container> <!-- Fruit Column --> <ng-container matColumnDef="phone"> <th mat-header-cell *matHeaderCellDef mat-sort-header> PHONE </th> <td mat-cell *matCellDef="let row"> {{row.phone}} </td> </ng-container> <ng-container matColumnDef="date"> <th mat-header-cell *matHeaderCellDef mat-sort-header> DATE </th> <td mat-cell *matCellDef="let row"> {{row.date | date}} </td> </ng-container> <ng-container matColumnDef="action"> <th mat-header-cell *matHeaderCellDef mat-sort-header> action </th> <td mat-cell *matCellDef="let row"> <button mat-icon-button (click)="editUser(row)" color="primary"> <mat-icon>edit</mat-icon> </button> <button mat-icon-button color="warn"> <mat-icon>delete</mat-icon> </button> </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> <!-- Row shown when there is no matching data. --> <tr class="mat-row" *matNoDataRow> <td class="mat-cell" colspan="4">No data matching the filter "{{input.value}}"</td> </tr> </table> <mat-paginator [pageSizeOptions]="[5, 10, 25, 100]" aria-label="Select page of users"></mat-paginator> </div> </div> </div>
<?php namespace App\Filament\Resources; use App\Filament\Resources\ArtikelResource\Pages; use App\Filament\Resources\ArtikelResource\RelationManagers; use App\Models\Artikel; use Faker\Core\DateTime; use Filament\Forms; use Filament\Forms\Components\DatePicker; use Filament\Forms\Components\Select; use Filament\Forms\Components\TextInput; use Filament\Forms\Form; use Filament\Resources\Resource; use Filament\Tables; use Filament\Tables\Columns\TextColumn; use Filament\Tables\Table; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\SoftDeletingScope; class ArtikelResource extends Resource { protected static ?string $model = Artikel::class; protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack'; public static function form(Form $form): Form { return $form ->schema([ TextInput::make('judul'), TextInput::make('isi_text'), DatePicker::make('tanggal_publikasi'), Select::make('desa_id')->relationship('desa','nama_desa') ]); } public static function table(Table $table): Table { return $table ->columns([ TextColumn::make('judul')->searchable(), TextColumn::make('isi_text'), TextColumn::make('tanggal_publikasi'), TextColumn::make('desa_id'), ]) ->filters([ // ]) ->actions([ Tables\Actions\EditAction::make(), Tables\Actions\DeleteAction::make(), ]) ->bulkActions([ Tables\Actions\BulkActionGroup::make([ Tables\Actions\DeleteBulkAction::make(), ]), ]) ->emptyStateActions([ Tables\Actions\CreateAction::make(), ]); } public static function getRelations(): array { return [ // ]; } public static function getPages(): array { return [ 'index' => Pages\ListArtikels::route('/'), 'create' => Pages\CreateArtikel::route('/create'), // 'edit' => Pages\EditArtikel::route('/{record}/edit'), ]; } }
import torch import torch.nn.functional as F def preprocess_tensor_for_kl(tensor): # 将张量的所有值转换为绝对值 tensor_abs = torch.abs(tensor) # 按列归一化张量,使每列的和为1 column_sums = tensor_abs.sum(dim=0, keepdim=True) tensor_normalized = tensor_abs / column_sums return tensor_normalized def cosine_similarity_loss_columnwise(x1, x2): """ Computes the cosine similarity loss between two tensors column-wise. Args: x1 (Tensor): A tensor. x2 (Tensor): Another tensor of the same size as x1. Returns: Tensor: Loss value. """ # Normalize x1 and x2 along the first dimension (column-wise) x1_normalized = F.normalize(x1, p=2, dim=0) x2_normalized = F.normalize(x2, p=2, dim=0) # Compute cosine similarity column-wise cos_sim = torch.sum(x1_normalized * x2_normalized, dim=0) cos_sim_show = cos_sim.detach().cpu().numpy() # Calculate loss as 1 - cosine similarity loss = 1 - cos_sim return loss.mean() def l1_regularization_columnwise(matrix, lambda_reg): """ Apply L1 regularization column-wise to a 2D matrix. Args: matrix (Tensor): The input 2D tensor (matrix). lambda_reg (float): The regularization coefficient. Returns: Tensor: The L1 regularization loss calculated column-wise. """ return lambda_reg * torch.mean(torch.norm(matrix, p=1, dim=0)) def compute_graph_regularization(Z, A, lambda_reg): """ Compute the graph regularization term using PyTorch. Parameters: Z (torch.Tensor): The self-representation matrix or feature matrix (size: N x N). A (torch.Tensor): The adjacency matrix of the graph (size: N x N). lambda_reg (float): The regularization parameter. Returns: torch.Tensor: The value of the graph regularization term. """ mask = torch.ones(Z.shape[0], Z.shape[0], dtype=torch.bool,device='cuda') mask.fill_diagonal_(0) N = A.size(0) D = torch.diag(A.sum(1)) # Degree matrix L = D - A # Laplacian matrix # L_mod = L - torch.diag(torch.diag(L)) # Modified Laplacian with zero diagonal reg_term = lambda_reg * torch.trace(torch.matmul(torch.matmul(Z.t(), L), Z)) return reg_term
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout"; import React from "react"; import { PROJECT_STATUS_CLASS_MAP, PROJECT_STATUS_TEXT_MAP, } from "@/constants.jsx"; import TasksTable from "../Task/TasksTable"; import Footer from "@/Components/Footer"; function Show({ auth, success, project, tasks, queryParams = null }) { return ( <AuthenticatedLayout user={auth.user} header={ <h2 className="font-semibold text-lg text-gray-600 leading-tight"> {`Project "${project.name}"`} </h2> } > {/* <Head title={`Project "${project.name}"`} /> */} {/* <pre>{JSON.stringify(project, null, 2)}</pre> */} <section className="container px-4 mx-auto mt-5 "> <div className="flex flex-col rounded-lg bg-gradient-to-br from-gray-800 to-gray-900"> <div className="-mx-4 -my-2 overflow-x-auto overflow-y-auto sm:-mx-6 lg:-mx-8 "> <div className="inline-block min-w-full py-2 align-middle md:px-6 lg:px-8"> <div className="overflow-hidden border border-gray-200 dark:border-gray-700 md:rounded-lg "> <div className="p-6"> <img src={project.image_path} alt="" className="w-full h-64 object-cover" /> </div> <div className="p-6 grid gap-1 grid-cols-2 "> <div className="grid grid-rows-4 grid-flow-col gap-4"> <div className=""> <label className=" block text-md font-medium text-gray-700 dark:text-gray-300" htmlFor="name" > Project ID </label> <p className=" block text-md font-medium text-gray-700 dark:text-gray-300"> {project.id} </p> </div> <div className=""> <label className=" block text-md font-medium text-gray-700 dark:text-gray-300" htmlFor="name" > Project Name </label> <p className=" block text-md font-medium text-gray-700 dark:text-gray-300"> {project.name} </p> </div> <div className=""> <label className=" block text-md font-medium text-gray-700 dark:text-gray-300" htmlFor="name" > Project Status </label> <p className="mt-2 block text-md font-medium text-gray-700 dark:text-gray-300"> <span className={ "text-sm font-medium whitespace-nowrap inline-flex items-center px-3 py-1 rounded-full gap-x-2 bg-gray-800 " + PROJECT_STATUS_CLASS_MAP[project.status] } > {PROJECT_STATUS_TEXT_MAP[project.status]} </span> </p> </div> <div className=""> <label className=" block text-md font-medium text-gray-700 dark:text-gray-300" htmlFor="name" > Created By </label> <p className=" block text-md font-medium text-gray-700 dark:text-gray-300"> {project.createdBy.name} </p> </div> </div> <div className="grid grid-rows-4 grid-flow-col gap-4"> <div className=""> <label className=" block text-md font-medium text-gray-700 dark:text-gray-300" htmlFor="name" > Due Date </label> <p className=" block text-md font-medium text-gray-700 dark:text-gray-300"> {project.due_date} </p> </div> <div className=""> <label className=" block text-md font-medium text-gray-700 dark:text-gray-300" htmlFor="name" > Create Date </label> <p className=" block text-md font-medium text-gray-700 dark:text-gray-300"> {project.created_at} </p> </div> <div className=""> <label className=" block text-md font-medium text-gray-700 dark:text-gray-300" htmlFor="name" > Updated By </label> <p className=" block text-md font-medium text-gray-700 dark:text-gray-300"> {project.updatedBy.name} </p> </div> </div> </div> <div className="pt-0 p-6"> <label className="block text-md font-medium text-gray-700 dark:text-gray-300" htmlFor="name" > Description </label> <p className=" block text-md font-medium text-gray-700 dark:text-gray-300"> {project.description} </p> </div> </div> </div> </div> </div> </section> <section className="container px-4 mx-auto mt-5 "> <div className="flex flex-col rounded-lg "> <div className="-mx-4 -my-2 overflow-x-auto overflow-y-auto sm:-mx-6 lg:-mx-8 "> <div className="inline-block min-w-full py-2 align-middle md:px-6 lg:px-8"> <div className="overflow-hidden md:rounded-lg "> <TasksTable tasks={tasks} success={success} queryParams={queryParams} hideProjectColumn={true}/> </div> </div> </div> </div> </section> <Footer/> </AuthenticatedLayout> ); } export default Show;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Random Password Generator</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="container"> <h1>Generate a <br/><span>Random Password</span></h1> <div class="display"> <input type="text" id="password" placeholder="Password"> <img src="images/copy.png" onclick="copyPassword()"> </div> <button onclick="createPassword()"> <img src="images/generate.png">Generate Password</button> </div> <script> const passwordBox = document.getElementById("password"); const length = 12; const upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const lowerCase ="abcdefghijklmnopqrstuvwxyz"; const number = "0123456789" const symbol = "@#$%^&*()_+~|}{[]></-="; const allChars = upperCase + lowerCase + number + symbol; function createPassword(){ let password = ""; password += upperCase[Math.floor(Math.random() * upperCase.length)]; password += lowerCase[Math.floor(Math.random() * lowerCase.length)]; password += number[Math.floor(Math.random() * number.length)]; password += symbol[Math.floor(Math.random() * symbol.length)]; while(length > password.length){ password += allChars[Math.floor(Math.random() * allChars.length)]; } passwordBox.value = password; } function copyPassword() { passwordBox.select(); document.execCommand("copy") } </script> </body> </html>
// // Created by johannes on 11/12/21. // #ifndef PROJECT_MASS_ASSIGNEMENT_H #define PROJECT_MASS_ASSIGNEMENT_H #include "aweights.h" #include "blitz/array.h" #include "io_utils.h" #include "transformations.h" /* * Return the nearest grid point for a single coordinate. * * @param coord coordinate. * @param n_grid size of the grid. */ template<typename real_t> real_t ngp(real_t coord, int n_grid) { return std::floor(n_grid * (coord + 0.5)); } /* * Return a grid of mass densities given a particle distribution. * * The algorithm used is nearest grid point. * * @param particles Particles to distribute * @param n_grid Grid size in 3d. */ template<typename real_t> blitz::Array<real_t, 3> assign_mass_ngp(blitz::Array<real_t, 2> particles, int n_grid) { blitz::Array<real_t, 3> res(n_grid, n_grid, n_grid); for (auto i = 0; i < particles.extent(blitz::firstDim); ++i) { blitz::TinyVector<real_t, 3> grid_point; for (auto j = 0; j < particles.extent(blitz::secondDim); ++j) { real_t p = particles(i, j); grid_point(j) = ngp(p, n_grid); } real_t mass = 1.; res(grid_point) += mass; } return res; } /* * Return a grid of mass densities given a particle distribution. * * @param particles Particles to distribute. * @param n_grid Grid size in 3d. * @param wrap Wrapping function to map values from [-n_grid, 2*n_grid) to the * range [0, n_grid). It should be equivalent to (i + n_grid) % n_grid. * @param out Grid for assigning the masses. * @param order Order of the mass assignment weights. */ template <typename real_t, int Order> void assign_mass(blitz::Array<real_t, 2> particles, int n_grid, int (*wrap)(int, int), blitz::Array<real_t, 3> out) { out = 0; for (auto row = 0; row < particles.extent(blitz::firstDim); ++row) { real_t p = particles(row, 0); real_t p_grid = grid_coordinate(p, n_grid); AssignmentWeights<Order> wx(p_grid); p = particles(row, 1); p_grid = grid_coordinate(p, n_grid); AssignmentWeights<Order> wy(p_grid); p = particles(row, 2); p_grid = grid_coordinate(p, n_grid); AssignmentWeights<Order> wz(p_grid); for (auto i = 0; i < Order; ++i) { for (auto j = 0; j < Order; ++j) { for (auto k = 0; k < Order; ++k) { int x = wrap(wx.i + i, n_grid); int y = wrap(wy.i + j, n_grid); int z = wrap(wz.i + k, n_grid); out(x, y, z) += wx.H[i] * wy.H[j] * wz.H[k]; } } } } } /* * Return a grid of mass densities given a particle distribution. * * Use a grid bigger with margins instead of using a modulo operation. * * @param particles Particles to distribute * @param n_grid Grid size in 3d. * @param order Order of the mass assignment weights. */ template <typename real_t, int Order> blitz::Array<real_t, 3> assign_mass_with_margins(blitz::Array<real_t, 2> particles, int n_grid) { using blitz::Array; using blitz::firstDim; using blitz::Range; int margin = (Order - 1); int n_grid_m = n_grid + 2 * margin; blitz::Array<real_t, 3> res_m(n_grid_m, n_grid_m, n_grid_m); res_m = 0; blitz::Range inside(blitz::Range(margin, n_grid + margin - 1)); blitz::Array<real_t, 3> res = res_m(inside, inside, inside); for (auto row = 0; row < particles.extent(blitz::firstDim); ++row) { real_t p = particles(row, 0); real_t p_grid = grid_coordinate(p, n_grid); AssignmentWeights<Order> wx(p_grid); p = particles(row, 1); p_grid = grid_coordinate(p, n_grid); AssignmentWeights<Order> wy(p_grid); p = particles(row, 2); p_grid = grid_coordinate(p, n_grid); AssignmentWeights<Order> wz(p_grid); for (auto i = 0; i < Order; ++i) { for (auto j = 0; j < Order; ++j) { for (auto k = 0; k < Order; ++k) { int x = wx.i + i + margin; int y = wy.i + j + margin; int z = wz.i + k + margin; res_m(x, y, z) += wx.H[i] * wy.H[j] * wz.H[k]; } } } } // Copy margins blitz::Range all = blitz::Range::all(); blitz::Range left = blitz::Range(margin, 2 * margin - 1); blitz::Range left_margin = blitz::Range(0, margin - 1); blitz::Range right = blitz::Range(n_grid, n_grid + margin - 1); blitz::Range right_margin = blitz::Range(margin + n_grid, n_grid + 2 * margin - 1); // x-direction res_m(left, all, all) += res_m(right_margin, all, all); res_m(right, all, all) += res_m(left_margin, all, all); // y-direction res_m(all, left, all) += res_m(all, right_margin, all); res_m(all, right, all) += res_m(all, left_margin, all); // z-direction res_m(all, all, left) += res_m(all, all, right_margin); res_m(all, all, right) += res_m(all, all, left_margin); return res; } #endif // PROJECT_MASS_ASSIGNEMENT_H
# Dataset Factorization This is the pytorch implementation of the following NeurIPS 2022 paper: **[Dataset Distillation via Factorization](https://arxiv.org/abs/2210.16774)** *Songhua Liu, Kai Wang, Xingyi Yang, Jingwen Ye, and Xinchao Wang.* <img src="https://github.com/Huage001/DatasetFactorization/blob/main/teaser.png" width="1024px"/> ## Installation * Create a new environment if you want: ```bash conda create -n HaBa python=3.8 conda activate HaBa ``` * Clone the repo and install the required packages: ```bash git clone https://github.com/Huage001/DatasetFactorization.git cd DatasetFactorization pip install -r requirements.txt ``` ## Dataset Distillation * Install required packages: ```bash pip install -r requirements.txt ``` * First, generate buffer of training trajectories using: ```bash python buffer.py --dataset=CIFAR10 --model=ConvNet --train_epochs=50 --num_experts=100 --zca --buffer_path={path_to_buffer_storage} --data_path={path_to_dataset} ``` * Then, edit *run_cifar10_ipc[xx]_style5.sh*. Change *{path_to_buffer_storage}* to your path of buffers and *{path_to_dataset}* to your path of datasets. * Run: ```bash bash run_cifar10_ipc[xx]_style5.sh ``` *[xx]* can be 1, 10, or 50. * Most of hyper-parameters are following [the baseline repo](https://github.com/GeorgeCazenavette/mtt-distillation). You may also try other configurations of arguments in the .sh files freely. * *distill.py* contains the original implementation of the baseline method [MTT](https://github.com/GeorgeCazenavette/mtt-distillation) for comparison. ## Acknowledgement This code borrows heavily from [mtt-distillation](https://github.com/GeorgeCazenavette/mtt-distillation) and [DatasetCondensation](https://github.com/VICO-UoE/DatasetCondensation). ## Citation If you find this project useful in your research, please consider cite our paper and [the default baseline method](https://arxiv.org/abs/2203.11932): ```latex @article{liu2022dataset, author = {Songhua Liu, Kai Wang, Xingyi Yang, Jingwen Ye, Xinchao Wang}, title = {Dataset Distillation via Factorization}, journal = {NeurIPS}, year = {2022}, } ``` ```latex @inproceedings{ cazenavette2022distillation, title={Dataset Distillation by Matching Training Trajectories}, author={George Cazenavette and Tongzhou Wang and Antonio Torralba and Alexei A. Efros and Jun-Yan Zhu}, booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition}, year={2022} } ```
document.querySelector('.timestamp').innerText = (new Date()).toLocaleTimeString(); document.querySelector('.ajax-html').addEventListener('click', getHtmlAjax); const XHR_STATE_DONE = 4; const HTTP_STATUS_CODE = 200; function getHtmlAjax () { const xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === XHR_STATE_DONE && xhr.status === 200) { document.querySelector('.html-container').innerHTML = xhr.responseText } } xhr.open('GET', 'client-data.html', true); xhr.send(); } document.querySelector('.fetch-html').addEventListener('click', fetchHtml); //function fetchHtml() { // fetch('client-data.html') // .then( response => response.text() ) // .then(html => document.querySelector('.html-container').innerHTML = html); //} async function fetchHtml() { const response = await fetch('client-data.html'); const html = await response.text(); document.querySelector('.html-container').innerHTML = html; } //JSON document.querySelector('.ajax-json').addEventListener('click', getAjaxJson); function getAjaxJson() { const xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === XHR_STATE_DONE && xhr.status === 200) { const clientData = JSON.parse(xhr.responseText); document.querySelector('.client-name').innerText = clientData.name; document.querySelector('.account-balance').innerText = clientData.balance; } } xhr.open('GET', 'client-data.json', true); xhr.send(); } document.querySelector('.fetch-json').addEventListener('click', fetchJson); function fetchJson() { fetch('client-data.json') .then( response => response.json() ) .then( clientData => { document.querySelector('.client-name').innerText = clientData.name; document.querySelector('.account-balance').innerText = clientData.balance; }); }
const ApiDirectory = artifacts.require("ApiDirectory"); const expect = require('chai').expect; const utils = require("./helpers/utils"); const example = require("./helpers/api_examples"); const api1 = example.api_1; const api2 = example.api_2; const api3 = example.api_3; contract("ApiDirectory", (accounts) => { let [alice, bob, carl] = accounts; // Accounts array holds the 10 test accounts on ganache let contractInstance; beforeEach(async () => { contractInstance = await ApiDirectory.new(); // Make a new contract abstraction instance for every test }); xit("should be able to create an API entry of coverage: 'patras'", async () => { const result = await contractInstance.createApi(api1.openapi, api1.info, api1.servers, api1.paths, api1.security, api1.components, api1.tags, api1.externalDocs, api1.x_category, api1.x_coverage, {from: alice}); const api = await contractInstance.getApiWithCoverage("patras"); // Deprecated for (i=0; i<api.length; i++) { const keys_length = Object.keys(api[i]).length; const api_keys = Object.keys(api[i]).slice(Math.floor(keys_length/2), keys_length); console.log('api added keys:\n' + api_keys); const no_empty_api = utils.removeEmptyStrings(api[i]); utils.iterateNested(no_empty_api); console.log('api added:\n'); console.log(no_empty_api); } expect(result.receipt.status).to.equal(true); expect(result.logs[0].args.x_coverage).to.equal("patras"); }); xit("should be able to create an API entry of coverage in an Rectangle Area", async () => { const result = await contractInstance.createApi(api1.openapi, api1.info, api1.servers, api1.paths, api1.security, api1.components, api1.tags, api1.externalDocs, api1.x_category, api1.x_coverage, {from: alice}); const count = await contractInstance.getApiCount({from: alice}); const owner = await contractInstance.getOwnerOf(0, {from: alice}); console.log(`Alice has ${count} APIs registered and the producer of API with id=0 is ${owner}`); expect(result.receipt.status).to.equal(true); }); it("should be able to check Category && if Point is in Rectangle erea and then return APIs", async () => { const result1 = await contractInstance.createApi(api3.openapi, api3.info, api3.servers, api3.paths, api3.security, api3.components, api3.tags, api3.externalDocs, api3.x_category, api3.x_coverage, {from: alice}); const result2 = await contractInstance.createApi(api2.openapi, api2.info, api2.servers, api2.paths, api2.security, api2.components, api2.tags, api2.externalDocs, api2.x_category, api2.x_coverage, {from: bob}); const t = 1000000; const patras_center= {lat:38.24264*t, lng: 21.73073*t}; const antirrio = {lat: 38.33192*t, lng: 21.74454*t}; const vrachnaiika = {lat: 38.16730*t, lng: 21.67520*t}; const panachaiko = {lat: 38.24136*t, lng: 21.84834*t}; const psilalonia = {lat: 38.24070*t, lng: 21.73512*t}; const agia = {lat: 38.26907*t, lng: 21.74487*t} const aigio = {lat: 38.23511*t, lng: 22.07048*t} const api = await contractInstance.getApiWithCatAndCov("SmartCity", aigio); for (i=0; i<api.length; i++) { const no_empty_api = utils.removeEmptyStrings(api[i]); utils.iterateNested(no_empty_api); console.log('api added:\n'); console.log(no_empty_api); } expect(result1.receipt.status && result2.receipt.status).to.equal(true); }); xit("should be able to receive payment (in ether) for function call and pay API producers", async () => { const result1 = await contractInstance.createApi(api1.openapi, api1.info, api1.servers, api1.paths, api1.security, api1.components, api1.tags, api1.externalDocs, api1.x_category, api1.x_coverage, {from: alice}); const result2 = await contractInstance.createApi(api2.openapi, api2.info, api2.servers, api2.paths, api2.security, api2.components, api2.tags, api2.externalDocs, api2.x_category, api2.x_coverage, {from: bob}); let contract_balance_before = web3.utils.fromWei(await web3.eth.getBalance(contractInstance.address), "ether"); let alice_balance_before = web3.utils.fromWei(await web3.eth.getBalance(alice), "ether"); let bob_balance_before = web3.utils.fromWei(await web3.eth.getBalance(bob), "ether"); let carl_balance_before = web3.utils.fromWei(await web3.eth.getBalance(carl), "ether"); let price = web3.utils.toWei('3', "ether"); const t = 1000000; const patras_center= {lat:38.24264*t, lng: 21.73073*t}; const call = await contractInstance.getApiWithCoveragePayable(patras_center, {from: carl, value: price}); const api = call.logs[0].args.returnApiListing; for (i=0; i<api.length; i++) { const no_empty_api = utils.removeEmptyStrings(api[i]); utils.iterateNested(no_empty_api); console.log('api added:\n'); console.log(no_empty_api); } let contract_balance_after = web3.utils.fromWei(await web3.eth.getBalance(contractInstance.address), "ether"); let alice_balance_after = web3.utils.fromWei(await web3.eth.getBalance(alice), "ether"); let bob_balance_after = web3.utils.fromWei(await web3.eth.getBalance(bob), "ether"); let carl_balance_after = web3.utils.fromWei(await web3.eth.getBalance(carl), "ether"); console.log("Contract balance before trans: "); console.log(contract_balance_before); console.log("Contract balance after trans: "); console.log(contract_balance_after); console.log("Alice balance before trans: "); console.log(alice_balance_before); console.log("Alice balance after trans: "); console.log(alice_balance_after); console.log("Bob balance before trans: "); console.log(bob_balance_before); console.log("Bob balance after trans: "); console.log(bob_balance_after); console.log("Carl balance before trans: "); console.log(carl_balance_before); console.log("Carl balance after trans: "); console.log(carl_balance_after); expect(result1.receipt.status && result2.receipt.status).to.equal(true); }); })
/*! # 2023 Day 25: Snowverload ## Cutting connections <https://adventofcode.com/2023/day/25> This is another one that was trivial in Python (due to the `networkx` library), and so applying the same solution in Rust using `rustworkx-core`. ```python from pathlib import Path import networkx as nx def read(fn): txt = Path(fn).read_text() lines = [t.replace(":", "").split() for t in txt.splitlines()] return {a[0]: frozenset(a[1:]) for a in lines} data = read("25data.txt") graph = nx.from_dict_of_lists(data) cuts = nx.minimum_edge_cut(graph) graph.remove_edges(cuts) a,b = (graph.subgraph(c) for c in nx.connected_components(graph)) print(len(a), "*", len(b), "=", len(a) * len(b)) ``` */ use petgraph::graph::UnGraph; use rustworkx_core::connectivity::stoer_wagner_min_cut; fn read(text: &str) -> UnGraph<&str, ()> { let mut graph = UnGraph::new_undirected(); let mut nodes = std::collections::HashMap::new(); for line in text.lines() { let (node, edges) = line.split_once(": ").unwrap(); let node = *nodes.entry(node).or_insert_with(|| graph.add_node(node)); for edge in edges.split(' ') { let edge = *nodes.entry(edge).or_insert_with(|| graph.add_node(edge)); graph.add_edge(node, edge, ()); } } graph } fn compute(text: &str) -> usize { let graph = read(text); let len = find_edges(&graph); len * (graph.node_count() - len) } fn find_edges(graph: &UnGraph<&str, ()>) -> usize { let (cut, items) = stoer_wagner_min_cut(graph, |_| Ok::<_, ()>(1)) .unwrap() .unwrap(); assert_eq!(cut, 3); items.len() } fn main() { let text = std::fs::read_to_string("input/25.txt").unwrap(); let result = compute(&text); println!("Answer = {result}"); } #[cfg(test)] mod tests { use super::*; const INPUT: &str = "\ jqt: rhn xhk nvd rsh: frs pzl lsr xhk: hfx cmg: qnr nvd lhk bvb rhn: xhk bvb hfx bvb: xhk hfx pzl: lsr hfx nvd qnr: nvd ntq: jqt hfx bvb xhk nvd: lhk lsr: lhk rzs: qnr cmg lsr rsh frs: qnr lhk lsr"; #[test] fn test_first() { let result = compute(INPUT); assert_eq!(result, 54); } }
import json import re import gradio as gr import fitz, io, os from PIL import Image import dotenv from langchain_community.chat_models.openai import ChatOpenAI import openai dotenv.load_dotenv() from langchain.llms import OpenAI from langchain.chains import LLMChain from langchain.prompts import PromptTemplate class Paper: def __init__(self,file): self.file = file self.paper_info = self.get_paper_info() self.max_img = self.get_image_path("D:\Pycharm_Projects\llm_report_generate\extracted_images") def get_image_path(self, pic_path): if not os.path.exists(pic_path): os.mkdir(pic_path) checkIM = r"/Subtype(?= */Image)" with fitz.open(self.file) as doc: lenXREF = doc.xref_length() max_size = 0 max_img = None for i in range(1, lenXREF): text = doc.xref_object(i) isImage = re.search(checkIM, text) if not isImage: continue pix = fitz.Pixmap(doc, i) if pix.size < 10000: # 设置最小图片尺寸阈值 continue if pix.size > max_size: max_size = pix.size if max_img: max_img.clear_with() # 删除之前保存的较小图片 max_img = pix if max_img: max_img.save(os.path.join(pic_path, "max_image.png")) return os.path.join(pic_path, "max_image.png") def get_paper_info(self): llm = OpenAI(temperature=.7) # llm = ChatOpenAI( # model_name="chatglm", # openai_api_base="http://localhost:8000/v1", # openai_api_key="EMPTY", # streaming=False, # ) template = """ 你是一个专业的研究者,擅长从论文的首页介绍部分提取关键信息并以Markdown格式进行总结。给定一篇论文的介绍内容如下: {content} 请根据以上内容,提取并总结以下信息: 1. 论文的标题(中英文) 2. 详细的摘要(中英文) 3. 第一作者的姓名 4. 第一作者的所属单位 5. 论文的发表日期 6. 论文的出版单位 并按照以下Markdown格式组织这些信息: ```markdown # 论文标题 - 中文标题: (中文标题) - English Title: (英文标题) ## 主要信息 - 第一作者: (第一作者姓名) - 所属单位: (第一作者所属单位) - 发表日期: (发表日期) - 出版单位: (出版单位) ### English Abstract - (英文摘要) ### 中文摘要 - (中文摘要) ``` 请注意,上面的()是用来指示需要填充的信息,实际使用时需要替换为相应的内容。 请将实际的内容替换到相应的大括号位置,并确保Markdown格式正确,以便于阅读和理解。 """ llm_chain = LLMChain( llm=llm, prompt=PromptTemplate.from_template(template)) with fitz.open(self.file) as doc: first_page_content = doc[0].get_text() response = llm_chain(first_page_content)['text'] print(response) return response
#include "3-calc.h" #include <stdlib.h> #include <stdio.h> /** * main - Entry point * Description: Performs simple operations (+, -, *, /, %) on two integers. * Usage: calc num1 operator num2 * num1 and num2 are integers. * operator is one of: +, -, *, /, %. * Error cases: * - If the number of arguments is wrong, exits with status 98. * - If the operator is none of the above, exits with status 99. * - If trying to divide by 0, exits with status 100. * @argc: Argument count. * @argv: Argument vector. * Return: 0 on success. */ int main(int argc, char *argv[]) { int num1, num2, result; int (*op_func)(int, int); if (argc != 4) { printf("Error\n"); exit(98); } num1 = atoi(argv[1]); num2 = atoi(argv[3]); op_func = get_op_func(argv[2]); if (!op_func) { printf("Error\n"); exit(99); } if ((*argv[2] == '/' || *argv[2] == '%') && num2 == 0) { printf("Error\n"); exit(100); } result = op_func(num1, num2); printf("%d\n", result); return (0); }
#ifndef ANIMATOR_H #define ANIMATOR_H #include "includes.h" using steady_clock = std::chrono::steady_clock; typedef std::chrono::time_point<steady_clock> time_point; enum class AnimUpdate { Once, Loop, PingPong }; struct AnimData { std::size_t index = 0; bool played = false; bool reverse = false; float totalTime = 0.0f; AnimUpdate update = AnimUpdate::Loop; float duration; inline void Update(const std::size_t& size, float deltaTime) { switch(update) { case AnimUpdate::Loop: { totalTime += deltaTime; index = (std::size_t)(totalTime / duration) % size; } break; case AnimUpdate::Once: { totalTime += played ? 0.0f : deltaTime; index = std::min<std::size_t>(totalTime / duration, size - 1); } break; case AnimUpdate::PingPong: { totalTime += deltaTime; index = std::min<std::size_t>(totalTime / duration, size - 1); if(played) Reverse(); } break; } played = totalTime >= duration * (size - 1); index = reverse ? size - 1 - index : index; } inline void Reverse() { reverse = !reverse; played = false; totalTime = 0.0f; } inline void Reset() { played = false; totalTime = 0.0f; index = 0; } }; struct AnimFrameList { std::vector<Sprite> frames; inline void AddFrame(const std::string& path) { frames.emplace_back(path); } inline void AddFrame(const Sprite& spr) { frames.push_back(spr); } inline Sprite& GetFrame(const std::size_t& index) { return frames[index]; } inline Sprite& operator[](const std::size_t& index) { return frames[index]; } }; struct Animator { AnimData data; AnimFrameList frameList; inline void AddFrame(const std::string& path) { frameList.AddFrame(path); } inline void AddFrame(const Sprite& spr) { frameList.AddFrame(spr); } inline Sprite& GetFrame() { return frameList.GetFrame(data.index); } inline Sprite& operator[](const std::size_t& index) { return frameList[index]; } inline void Update(float deltaTime){ data.Update(frameList.frames.size(), deltaTime); } }; #endif
import 'package:cafejari_flutter/core/di.dart'; import 'package:cafejari_flutter/core/extension/null.dart'; import 'package:cafejari_flutter/ui/app_config/app_color.dart'; import 'package:cafejari_flutter/ui/components/back_button_app_bar.dart'; import 'package:cafejari_flutter/ui/state/global_state/global_state.dart'; import 'package:cafejari_flutter/ui/view_model/global_view_model.dart'; import 'package:flutter/material.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter/foundation.dart'; import 'package:go_router/go_router.dart'; import 'package:url_launcher/url_launcher.dart'; class InAppWebViewScreen extends ConsumerStatefulWidget { const InAppWebViewScreen({Key? key}):super(key:key); @override InAppWebViewScreenState createState() => InAppWebViewScreenState(); } class InAppWebViewScreenState extends ConsumerState<InAppWebViewScreen> { final GlobalKey webViewKey = GlobalKey(); late final PullToRefreshController pullToRefreshController; double progress = 0; @override void initState() { super.initState(); pullToRefreshController = PullToRefreshController( settings: PullToRefreshSettings( color: AppColor.white, backgroundColor: AppColor.primary, slingshotDistance: 40, distanceToTriggerSync: 40 ), onRefresh: () async { final GlobalState globalState = ref.watch(globalViewModelProvider); if (defaultTargetPlatform == TargetPlatform.android) { await globalState.webViewController?.reload(); } else if (defaultTargetPlatform == TargetPlatform.iOS) { await globalState.webViewController?.loadUrl(urlRequest: URLRequest(url: await globalState.webViewController?.getUrl())); } }, ); } @override Widget build(BuildContext context) { final GlobalState globalState = ref.watch(globalViewModelProvider); final GlobalViewModel globalViewModel = ref.watch(globalViewModelProvider.notifier); return PopScope( canPop: false, onPopInvoked: (result) async { bool? canGoBack = await globalState.webViewController?.canGoBack(); if(canGoBack.isNotNull && canGoBack!) { globalState.webViewController?.goBack(); } else { if(context.mounted) GoRouter.of(context).pop(); } }, child: Scaffold( appBar: BackButtonAppBar( backGroundColor: AppColor.white, onBack: () => GoRouter.of(context).pop(), backButtonText: globalState.webViewTitle, ), body: Column( children: <Widget>[ progress < 1.0 ? LinearProgressIndicator(value: progress, color: AppColor.primary) : Container(), Expanded( child: Stack( children: [ InAppWebView( key: webViewKey, initialUrlRequest: URLRequest(url: WebUri.uri(globalState.webViewUri)), initialSettings: InAppWebViewSettings( javaScriptCanOpenWindowsAutomatically: true, javaScriptEnabled: true, useOnDownloadStart: true, useOnLoadResource: true, useShouldOverrideUrlLoading: true, mediaPlaybackRequiresUserGesture: true, allowFileAccessFromFileURLs: true, allowUniversalAccessFromFileURLs: true, verticalScrollBarEnabled: true, useHybridComposition: true, allowContentAccess: true, builtInZoomControls: true, thirdPartyCookiesEnabled: true, allowFileAccess: true, supportMultipleWindows: true, allowsInlineMediaPlayback: true, allowsBackForwardNavigationGestures: true, ), pullToRefreshController: pullToRefreshController, onProgressChanged: (controller, progress) { if (progress == 100) {pullToRefreshController.endRefreshing();} setState(() {this.progress = progress / 100;}); }, onWebViewCreated: (InAppWebViewController controller) { globalViewModel.initWebViewController(controller); }, shouldOverrideUrlLoading: (controller, navigationAction) async { var uri = navigationAction.request.url!; if (![ "http", "https", "file", "chrome", "data", "javascript", "about" ].contains(uri.scheme)) { if (await canLaunchUrl(uri)) { // Launch the App await launchUrl( uri, ); // and cancel the request return NavigationActionPolicy.CANCEL; } } return NavigationActionPolicy.ALLOW; } ) ] ) ) ] ) ), ); } }
import {Component, OnInit} from '@angular/core'; import {FormBuilder, FormControl} from "@angular/forms"; import {CityApiService} from "../../../Core/Https/city-api.service"; import {TransferAPIService} from "../../../Core/Https/transfer-api.service"; import {MessageService} from "../../../Core/Services/message.service"; import {CheckErrorService} from "../../../Core/Services/check-error.service"; import {ErrorsService} from "../../../Core/Services/errors.service"; import {Router} from "@angular/router"; import {CommonApiService} from "../../../Core/Https/common-api.service"; import {SessionService} from "../../../Core/Services/session.service"; import {CalenderServices} from "../../../Core/Services/calender-service"; import {PublicService} from "../../../Core/Services/public.service"; import {ResponsiveService} from "../../../Core/Services/responsive.service"; import {PostSetReqDTO} from "../../../Core/Models/BlogDTO"; import {BlogApiService} from "../../../Core/Https/blog-api.service"; import {CategoryApiService} from "../../../Core/Https/category-api.service"; import {MatDialog} from "@angular/material/dialog"; import {UploadSingleComponent} from "../../../common-project/upload-single/upload-single.component"; @Component({ selector: 'prs-add', templateUrl: './add.component.html', styleUrls: ['./add.component.scss'] }) export class AddComponent implements OnInit { //public Variable isMobile; isLoading = false; isSlugGenerated = false; selectedTags: string[] = [] thumbnail = ''; categories: number[] = [] postReq: PostSetReqDTO = { title: '', slug: '', body: '', categories: [], description: '', status: 'Show', tags: [], thumbnail: '' }; constructor( public categoryApi: CategoryApiService, public cityApi: CityApiService, public transferApi: TransferAPIService, public message: MessageService, public blogApi: BlogApiService, public checkError: CheckErrorService, public errorService: ErrorsService, public router: Router, public commonApi: CommonApiService, public dialog: MatDialog, public session: SessionService, public calenderServices: CalenderServices, public publicServices: PublicService, public fb: FormBuilder, public mobileService: ResponsiveService) { this.isMobile = mobileService.isMobile(); } ////formGroup postForm = this.fb.group({ title: new FormControl(''), slug: new FormControl(''), body: new FormControl(''), tags: new FormControl(), description: new FormControl(''), status: new FormControl('Show'), }); ngOnInit() { } setSlug() { this.generateSlug(); } submit(): void { // if (this.postForm.controls.body.value !== '') { // this.createPost() // } else { // this.message.custom('لطفا متن بلاگ خود را وارد کنید') // } this.createPost() } createPost(): void { this.isLoading = true; this.fillObj(); this.blogApi.createPost(this.postReq).subscribe((res: any) => { this.isLoading = false; if (res.isDone) { this.message.showMessageBig(res.message); this.postForm.reset(); this.router.navigateByUrl('/panel/blog/list') } }, (error: any) => { this.isLoading = false; if (error.status == 422) { this.errorService.recordError(error.error.data); this.markFormGroupTouched(this.postForm); this.message.showMessageBig('اطلاعات ارسال شده را مجددا بررسی کنید') } else { this.message.showMessageBig('مشکلی رخ داده است لطفا مجددا تلاش کنید') } this.checkError.check(error); }) } fillObj() { this.postReq = { title: this.postForm.value.title, slug: this.postForm.value.slug, body: this.postForm.value.body, categories: this.categories, description: this.postForm.value.description, status: this.postForm.value.status, tags: this.postForm.value.tags, thumbnail: this.thumbnail } } getThumbnail(): void { const dialog = this.dialog.open(UploadSingleComponent, {}); dialog.afterClosed().subscribe(result => { this.thumbnail = result }) } getBody(body: any): void { this.postForm.controls.body.setValue(body); } getCategories(categories: any): void { this.categories = categories } private markFormGroupTouched(formGroup: any) { (<any>Object).values(formGroup.controls).forEach((control: any) => { control.markAsTouched(); if (control.controls) { this.markFormGroupTouched(control); } }); } generateSlug(): void { if (!this.isSlugGenerated) { this.blogApi.generateSlug(this.postForm.value.title).subscribe((res: any) => { if (res.data) { this.postForm.controls.slug.setValue(res.data); this.isSlugGenerated = true } else { this.message.custom(res.message) } }, (error: any) => { this.message.error() }) } else { } } getTags(tags: string[]): void { this.postForm.controls.tags.setValue(tags); } }
import React, { useState,useEffect } from "react"; import { Container, Box, Typography, Divider } from "@mui/material"; import Button from "@mui/material/Button"; import Logo from "../assest/logo.png"; import { Link, animateScroll as scroll } from "react-scroll"; import "./Header.css"; // Import your custom CSS file const Header = () => { const [Id, setID] = useState(2); const [toggle, setToggle] = useState(false); const [cardId, setCardId] = useState(2); const handleToggle = (id) => { setID(id); }; const handleClick = (id) => { setCardId(id); }; const handleMobileToggle = () => { setToggle(prevMode => !prevMode); }; return ( <Container className='header'> <Box className='logo-container'> <img src={Logo} alt='Logo' className='logoPage' /> </Box> {/* Large Screen Mobile Menu */} <Box className='Links' sx={{ display: { lg: "block", md: "block", sm: "none", xs: "none" } }}> <Link to='section1' spy={true} smooth={true} offset={70} duration={500} className='link'> Home </Link> <Link to='section2' spy={true} smooth={true} offset={70} duration={500} className='link'> Features </Link> <Link to='section3' spy={true} smooth={true} offset={70} duration={500} className='link'> Pricing </Link> <Link to='section7' spy={true} smooth={true} offset={70} duration={500} className='link'> FAQ </Link> <Link to='section5' spy={true} smooth={true} offset={70} duration={500} className='link'> Contact </Link> <Link activeClass='active' to='section6' spy={true} smooth={true} offset={70} duration={500} className='link'> Become an Affiliate </Link> </Box> <Box sx={{ display: { lg: "block", md: "block", sm: "none", xs: "none" } }}> <Button href='/login' className={Id === 1 ? "Homebtn1" : "Homebtn"} onClick={() => handleToggle(1)}> Login </Button> <Button href='/sign' className={Id === 2 ? "Homebtn1" : "Homebtn"} onClick={() => handleToggle(2)}> Sign Up </Button> </Box> <Box className='toggleHeader' onClick={handleMobileToggle}> <Box> <svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none'> <rect x='1.00098' y='5.00116' width='22' height='2' rx='1' fill='#1B1E28' /> <rect x='1.00098' y='11.0012' width='22' height='2' rx='1' fill='#1B1E28' /> <rect x='1.00098' y='17.0019' width='22' height='2' rx='1' fill='#1B1E28' /> </svg> </Box> </Box> {/* small screen mobile menu */} {toggle && ( <Box className='MobileHeader'> <Box display={"flex"} justifyContent={"space-between"} p={2}> <Typography sx={{ fontWeight: 600, fontSize: "20px" }}> Menu </Typography> <svg onClick={handleMobileToggle} xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none'> <g clip-path='url(#clip0_10668_2727)'> <path d='M20 5.61143L18.3886 4L12 10.3886L5.61143 4L4 5.61143L10.3886 12L4 18.3886L5.61143 20L12 13.6114L18.3886 20L20 18.3886L13.6114 12L20 5.61143Z' fill='#4C4448' /> </g> <defs> <clipPath id='clip0_10668_2727'> <rect width='24' height='24' fill='white' /> </clipPath> </defs> </svg> </Box> <Divider /> <Box sx={{ display: "flex", flexDirection: "column" }} className='mobileMenu'> <Link to='section1' spy={true} smooth={true} offset={70} duration={500} className='link'> Home </Link> <Link to='section2' spy={true} smooth={true} offset={70} duration={500} className='link'> Features </Link> <Link to='section3' spy={true} smooth={true} offset={70} duration={500} className='link'> Pricing </Link> <Link to='section7' spy={true} smooth={true} offset={70} duration={500} className='link'> FAQ </Link> <Link to='section5' spy={true} smooth={true} offset={70} duration={500} className='link'> Contact </Link> <Link activeClass='active' to='section6' spy={true} smooth={true} offset={70} duration={500} className='link'> Become an Affiliate </Link> </Box> <Divider sx={{marginTop:"20px"}} /> <Box m={2}> <Button href='/login' className={cardId === 1 ? "Homebtn2" : "Homebtn3"}> Login </Button> <Button href='/sign' className={cardId === 2 ? "Homebtn2" : "Homebtn3"} onClick={() => handleClick(1)} sx={{ marginLeft: "20px" }}> Sign Up </Button> </Box> </Box> )} </Container> ); }; export default Header;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System.Security.Claims; using web; using web.Models; [Route("api/[controller]")] public class ClothesController : ControllerBase { private readonly ClothesContext _context; private readonly UserManager<IdentityUser> _userManager; public ClothesController(UserManager<IdentityUser> userManager, ClothesContext context) { _userManager = userManager; _context = context; } // GET: api/Clothes [HttpGet] public async Task<ActionResult<IEnumerable<Clothes>>> GetClothes() { return await _context.Clothes.ToListAsync(); } // GET: api/Clothes/categories [HttpGet("categories")] public async Task<ActionResult<IEnumerable<Category>>> GetCategories() { return await _context.Categories.ToListAsync(); } // GET: api/Clothes/5 [HttpGet("{id}")] public async Task<ActionResult<Clothes>> GetClothes(int id) { var Clothes = await _context.Clothes.FindAsync(id); if (Clothes == null) return NotFound(); return Clothes; } // POST: api/Clothes [Authorize(Roles = "WebAdmin")] [HttpPost] public async Task<ActionResult<Clothes>> PostClothes([FromBody] Clothes Clothes) { _context.Clothes.Add(Clothes); await _context.SaveChangesAsync(); return CreatedAtAction("GetClothes", new { id = Clothes.ProductId }, Clothes); } // PUT: api/Clothes/5 [Authorize(Roles = "WebAdmin")] [HttpPut("{id}")] public async Task<IActionResult> PutClothes(int id, [FromBody] Clothes Clothes) { if (id != Clothes.ProductId) return BadRequest(); _context.Entry(Clothes).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!_context.Clothes.Any(e => e.ProductId == id)) return NotFound(); throw; } return NoContent(); } // DELETE: api/Clothes/5 [Authorize(Roles = "WebAdmin")] [HttpDelete("{id}")] public async Task<IActionResult> DeleteClothes(int id) { var Clothes = await _context.Clothes.FindAsync(id); if (Clothes == null) return NotFound(); _context.Clothes.Remove(Clothes); await _context.SaveChangesAsync(); return NoContent(); } }
import React from 'react'; import AuthContext from '../contexts/AuthContext'; import useStorage from '../hooks/useStorage'; import links from '../utility/links'; export default function AuthProvider(props) { const [token, setToken] = useStorage(localStorage, 'token'); const [profile, setProfile] = useStorage(localStorage, 'profile', true); const handleLogin = async ({ login, password }) => { try { const responseToken = await fetch(links.auth, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ login, password }), }); if (!responseToken.ok) { throw new Error('Ошибка аутентификации'); } const { token } = await responseToken.json(); console.log(links.private); const responseProfile = await fetch(`${links.private}/me`, { headers: { Authorization: `Bearer ${token}` }, }); if (!responseProfile.ok) { throw new Error('Данный профиль не существует'); } const profile = await responseProfile.json(); setToken(token); setProfile(profile); } catch (e) { setToken(null); setProfile(null); } }; const handleLogout = () => { setToken(null); setProfile(null); }; return ( <AuthContext.Provider value={{ handleLogin, handleLogout, token, profile }}> {props.children} </AuthContext.Provider> ); }
import axios from 'axios'; import { Tool } from 'langchain/tools'; class BingAPI extends Tool { name = 'bing'; description = `a search engine. useful when you need to answer questions about current events and time related questions.` + `input should be a search query. When arriving at the final or likely answer, make sure to cite results using [[number](URL)] notation after the reference.` + `If the provided search results refer to multiple subjects with the same name, write separate answers for each subject.`; key: string; params: Record<string, string>; constructor( apiKey: string | undefined = typeof process !== 'undefined' ? // eslint-disable-next-line no-process-env process.env?.BINGSERPAPI_API_KEY : undefined, params: Record<string, string> = {}, ) { super(); if (!apiKey) { throw new Error('BingSerpAPI API key not set. You can set it as BingApiKey in your .env file.'); } this.key = apiKey; this.params = params; } /** @ignore */ async _call(input: string): Promise<string> { const headers = { 'Ocp-Apim-Subscription-Key': this.key, accept: 'application/json', }; const params = { ...this.params, q: input, textDecorations: 'true', textFormat: 'HTML' }; const searchUrl = new URL('https://api.bing.microsoft.com/v7.0/search'); Object.entries(params).forEach(([key, value]) => { searchUrl.searchParams.append(key, value); }); const response = await axios.get(searchUrl.href, { headers }); if (response.status !== 200) { throw new Error(`HTTP error ${response.status}`); } const res = await response.data; const results: [] = res.webPages.value; if (results.length === 0) { return 'No good results found.'; } //[{id, name, url, displayUrl, snippet, dateLastCrawled, language, isNavigational, isFamilyFriendly}] const snippets = results .map((result: { snippet: string; url: string; name: string }, idx: number) => `[${idx}]"${result.snippet}"\nURL: ${result.url}`) .join('\n\n'); return snippets; } } export { BingAPI };
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:http/http.dart' as http; import 'package:profile_finder/core/utils/color_constant.dart'; import 'package:profile_finder/core/utils/size_utils.dart'; import 'package:profile_finder/model_final/model_final.dart'; import 'package:profile_finder/presentation/1ProfileFinder/MatchingList/1screen_advertisement.dart'; import 'package:profile_finder/presentation/1ProfileFinder/PrivateInvestigator/WhereIsTheSanFourtyThreeScreen.dart'; import 'package:profile_finder/widgets/CustomWidgetsCl/CustomClAll.dart'; import 'package:profile_finder/widgets/CustomWidgetsCl/CustomWidgets.dart'; import 'package:shared_preferences/shared_preferences.dart'; class FifteenAboutMe extends StatefulWidget { @override State<FifteenAboutMe> createState() => _FifteenAboutMeState(); } class _FifteenAboutMeState extends State<FifteenAboutMe> { String title = "About Me"; String aboutMee = "Please Update"; bool buttomClicked = false; Users _users = Users(); bool isLoading = true; late String uidUser; Future updateAboutDetails() async { SharedPreferences preferences = await SharedPreferences.getInstance(); uidUser = preferences.getString("uid2").toString(); print("uid for Update $uidUser "); final url = Uri.parse("http://${ApiService.ipAddress}/about_candidate/$uidUser"); final request = http.MultipartRequest('POST', url); // request.files // .add(await http.MultipartFile.fromPath('files', "headsizeFile!.path")); // request.fields['about_candidate_value'] = "aboutMee"; request.fields['about_candidate'] = aboutMee; try { final send = await request.send(); final response = await http.Response.fromStream(send); print(response.statusCode); print(response.body); if (response.statusCode == 200) { Fluttertoast.showToast( msg: "About Yourself Updated Successfully...!", backgroundColor: ColorConstant.deepPurpleA200, textColor: Colors.white, toastLength: Toast.LENGTH_SHORT, ); getDataAboutcandidate(); print("about candidate ${_users.aboutCandidate}"); // Future.delayed(const Duration(seconds: 10), () {}); // Navigator.pushNamed(context, AppRoutes.FourteenScreenscr); } } catch (e) { print("Error While Uploading$e"); } } void getDataAboutcandidate() async { SharedPreferences preferences = await SharedPreferences.getInstance(); uidUser = preferences.getString("uid2").toString(); final response = await http .get(Uri.parse("http://${ApiService.ipAddress}/alldata/$uidUser")); var json = jsonDecode(response.body); print("statusCodeIs ${response.statusCode}"); if (response.statusCode == 200) { _users = Users.fromJson(json); print(response.body); setState(() { isLoading = false; // aboutMee = _users.aboutCandidate; }); } else { print("error"); print(response.statusCode); } } @override void initState() { // TODO: implement initState // getData(); getDataAboutcandidate(); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: ColorConstant.whiteA700, appBar: ClAppbarLeadArrowBackSuffNo( title: '', // testingNextPage: WhereIsTheSanFourtyThreeScreen(private_investicator_id: '',) ), body: SingleChildScrollView( child: Padding( padding: EdgeInsets.symmetric(horizontal: 20), child: isLoading ? Center(child: CircularProgressIndicator()) : Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "About Me", textAlign: TextAlign.left, style: TextStyle( fontWeight: FontWeight.bold, fontSize: 22), ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ buttomClicked ? Container( height: DeviceSize.screenHeight - 150, decoration: BoxDecoration( // color: // widget.buttonclicked // ? // Colors.grey.shade100, // : Colors.transparent, borderRadius: BorderRadius.circular(8)), child: TextFormField( initialValue: _users.aboutCandidate, style: TextStyle( fontSize: 15, ), onChanged: (value) { setState(() { aboutMee = value; }); }, decoration: InputDecoration( isDense: true, border: OutlineInputBorder(), ), ), ) : Text( _users.aboutCandidate.toString(), style: const TextStyle( fontSize: 15, color: Colors.black), ), D10HCustomClSizedBoxWidget( height: 50, ), // widget.buttonclicked ? SizedBox() : Divider(), D10HCustomClSizedBoxWidget( height: 50, ), ], ), ], ), ), ), bottomNavigationBar: Padding( padding: const EdgeInsets.all(20), child: MyElevatedButton( onPressed: () async { setState(() { buttomClicked = !buttomClicked; }); if (buttomClicked == false) { updateAboutDetails(); } }, borderRadius: BorderRadius.circular(10), backgroundColor: Colors.transparent, child: Text( buttomClicked ? "Update" : "Edit", style: TextStyle(color: Colors.white), ), ), )); } }
// KILT Blockchain – https://botlabs.org // Copyright (C) 2019-2023 BOTLabs GmbH // The KILT Blockchain 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. // The KILT Blockchain is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // If you feel like getting in touch with us, you can do so at info@botlabs.org //! # DID lookup pallet //! //! This pallet stores a map from account IDs to DIDs. //! //! - [`Pallet`] #![cfg_attr(not(feature = "std"), no_std)] pub mod default_weights; pub mod migrations; mod connection_record; mod signature; #[cfg(test)] mod tests; #[cfg(test)] mod mock; #[cfg(feature = "runtime-benchmarks")] mod benchmarking; pub use crate::{default_weights::WeightInfo, pallet::*}; #[frame_support::pallet] pub mod pallet { use super::WeightInfo; use frame_support::{ ensure, pallet_prelude::*, traits::{Currency, ReservableCurrency, StorageVersion}, }; use frame_system::pallet_prelude::*; use kilt_support::{ deposit::Deposit, traits::{CallSources, StorageDepositCollector}, }; use sp_runtime::traits::BlockNumberProvider; pub use crate::connection_record::ConnectionRecord; use crate::signature::get_wrapped_payload; /// The identifier to which the accounts can be associated. pub(crate) type AccountIdOf<T> = <T as frame_system::Config>::AccountId; /// The identifier to which the accounts can be associated. pub(crate) type DidIdentifierOf<T> = <T as Config>::DidIdentifier; /// The signature type of the account that can get connected. pub(crate) type SignatureOf<T> = <T as Config>::Signature; /// The type used to describe a balance. pub(crate) type BalanceOf<T> = <<T as Config>::Currency as Currency<AccountIdOf<T>>>::Balance; /// The currency module that keeps track of balances. pub(crate) type CurrencyOf<T> = <T as Config>::Currency; /// The connection record type. pub(crate) type ConnectionRecordOf<T> = ConnectionRecord<DidIdentifierOf<T>, AccountIdOf<T>, BalanceOf<T>>; pub const STORAGE_VERSION: StorageVersion = StorageVersion::new(2); #[pallet::config] pub trait Config: frame_system::Config { type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>; type Signature: sp_runtime::traits::Verify<Signer = Self::Signer> + Parameter; type Signer: sp_runtime::traits::IdentifyAccount<AccountId = AccountIdOf<Self>> + Parameter; /// The origin that can associate accounts to itself. type EnsureOrigin: EnsureOrigin<<Self as frame_system::Config>::RuntimeOrigin, Success = Self::OriginSuccess>; /// The information that is returned by the origin check. type OriginSuccess: CallSources<AccountIdOf<Self>, DidIdentifierOf<Self>>; /// The identifier to which accounts can get associated. type DidIdentifier: Parameter + MaxEncodedLen; /// The currency that is used to reserve funds for each did. type Currency: ReservableCurrency<AccountIdOf<Self>>; /// The amount of balance that will be taken for each DID as a deposit /// to incentivise fair use of the on chain storage. The deposit can be /// reclaimed when the DID is deleted. #[pallet::constant] type Deposit: Get<BalanceOf<Self>>; /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; } #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] #[pallet::storage_version(STORAGE_VERSION)] pub struct Pallet<T>(_); /// Mapping from account identifiers to DIDs. #[pallet::storage] #[pallet::getter(fn connected_dids)] pub type ConnectedDids<T> = StorageMap<_, Blake2_128Concat, AccountIdOf<T>, ConnectionRecordOf<T>>; /// Mapping from (DID + account identifier) -> (). /// The empty tuple is used as a sentinel value to simply indicate the /// presence of a given tuple in the map. #[pallet::storage] #[pallet::getter(fn connected_accounts)] pub type ConnectedAccounts<T> = StorageDoubleMap<_, Blake2_128Concat, DidIdentifierOf<T>, Blake2_128Concat, AccountIdOf<T>, ()>; #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event<T: Config> { /// A new association between a DID and an account ID was created. AssociationEstablished(AccountIdOf<T>, DidIdentifierOf<T>), /// An association between a DID and an account ID was removed. AssociationRemoved(AccountIdOf<T>, DidIdentifierOf<T>), } #[pallet::error] pub enum Error<T> { /// The association does not exist. AssociationNotFound, /// The origin was not allowed to manage the association between the DID /// and the account ID. NotAuthorized, /// The supplied proof of ownership was outdated. OutdatedProof, /// The account has insufficient funds and can't pay the fees or reserve /// the deposit. InsufficientFunds, } #[pallet::call] impl<T: Config> Pallet<T> { /// Associate the given account to the DID that authorized this call. /// /// The account has to sign the DID and a blocknumber after which the /// signature expires in order to authorize the association. /// /// The signature will be checked against the scale encoded tuple of the /// method specific id of the did identifier and the block number after /// which the signature should be regarded invalid. /// /// Emits `AssociationEstablished` and, optionally, `AssociationRemoved` /// if there was a previous association for the account. /// /// # <weight> /// Weight: O(1) /// - Reads: ConnectedDids + ConnectedAccounts + DID Origin Check /// - Writes: ConnectedDids + ConnectedAccounts /// # </weight> #[pallet::call_index(0)] #[pallet::weight(<T as Config>::WeightInfo::associate_account())] pub fn associate_account( origin: OriginFor<T>, account: AccountIdOf<T>, expiration: <T as frame_system::Config>::BlockNumber, proof: SignatureOf<T>, ) -> DispatchResult { let source = <T as Config>::EnsureOrigin::ensure_origin(origin)?; let did_identifier = source.subject(); let sender = source.sender(); ensure!( frame_system::Pallet::<T>::current_block_number() <= expiration, Error::<T>::OutdatedProof ); let encoded_payload = (&did_identifier, expiration).encode(); ensure!( sp_runtime::traits::Verify::verify(&proof, &get_wrapped_payload(&encoded_payload[..])[..], &account), Error::<T>::NotAuthorized ); ensure!( <T::Currency as ReservableCurrency<AccountIdOf<T>>>::can_reserve( &sender, <T as Config>::Deposit::get() ), Error::<T>::InsufficientFunds ); Self::add_association(sender, did_identifier, account)?; Ok(()) } /// Associate the sender of the call to the DID that authorized this /// call. /// /// Emits `AssociationEstablished` and, optionally, `AssociationRemoved` /// if there was a previous association for the account. /// /// # <weight> /// Weight: O(1) /// - Reads: ConnectedDids + ConnectedAccounts + DID Origin Check /// - Writes: ConnectedDids + ConnectedAccounts /// # </weight> #[pallet::call_index(1)] #[pallet::weight(<T as Config>::WeightInfo::associate_sender())] pub fn associate_sender(origin: OriginFor<T>) -> DispatchResult { let source = <T as Config>::EnsureOrigin::ensure_origin(origin)?; ensure!( <T::Currency as ReservableCurrency<AccountIdOf<T>>>::can_reserve( &source.sender(), <T as Config>::Deposit::get() ), Error::<T>::InsufficientFunds ); Self::add_association(source.sender(), source.subject(), source.sender())?; Ok(()) } /// Remove the association of the sender account. This call doesn't /// require the authorization of the DID, but requires a signed origin. /// /// Emits `AssociationRemoved`. /// /// # <weight> /// Weight: O(1) /// - Reads: ConnectedDids + ConnectedAccounts + DID Origin Check /// - Writes: ConnectedDids + ConnectedAccounts /// # </weight> #[pallet::call_index(2)] #[pallet::weight(<T as Config>::WeightInfo::remove_sender_association())] pub fn remove_sender_association(origin: OriginFor<T>) -> DispatchResult { let who = ensure_signed(origin)?; Self::remove_association(who) } /// Remove the association of the provided account ID. This call doesn't /// require the authorization of the account ID, but the associated DID /// needs to match the DID that authorized this call. /// /// Emits `AssociationRemoved`. /// /// # <weight> /// Weight: O(1) /// - Reads: ConnectedDids + ConnectedAccounts + DID Origin Check /// - Writes: ConnectedDids + ConnectedAccounts /// # </weight> #[pallet::call_index(3)] #[pallet::weight(<T as Config>::WeightInfo::remove_account_association())] pub fn remove_account_association(origin: OriginFor<T>, account: AccountIdOf<T>) -> DispatchResult { let source = <T as Config>::EnsureOrigin::ensure_origin(origin)?; let connection_record = ConnectedDids::<T>::get(&account).ok_or(Error::<T>::AssociationNotFound)?; ensure!(connection_record.did == source.subject(), Error::<T>::NotAuthorized); Self::remove_association(account) } /// Remove the association of the provided account. This call can only /// be called from the deposit owner. The reserved deposit will be /// freed. /// /// Emits `AssociationRemoved`. /// /// # <weight> /// Weight: O(1) /// - Reads: ConnectedDids /// - Writes: ConnectedDids /// # </weight> #[pallet::call_index(4)] #[pallet::weight(<T as Config>::WeightInfo::remove_sender_association())] pub fn reclaim_deposit(origin: OriginFor<T>, account: AccountIdOf<T>) -> DispatchResult { let who = ensure_signed(origin)?; let record = ConnectedDids::<T>::get(&account).ok_or(Error::<T>::AssociationNotFound)?; ensure!(record.deposit.owner == who, Error::<T>::NotAuthorized); Self::remove_association(account) } /// Changes the deposit owner. /// /// The balance that is reserved by the current deposit owner will be /// freed and balance of the new deposit owner will get reserved. /// /// The subject of the call must be linked to the account. /// The sender of the call will be the new deposit owner. #[pallet::call_index(5)] #[pallet::weight(<T as Config>::WeightInfo::change_deposit_owner())] pub fn change_deposit_owner(origin: OriginFor<T>, account: AccountIdOf<T>) -> DispatchResult { let source = <T as Config>::EnsureOrigin::ensure_origin(origin)?; let subject = source.subject(); let record = ConnectedDids::<T>::get(&account).ok_or(Error::<T>::AssociationNotFound)?; ensure!(record.did == subject, Error::<T>::NotAuthorized); LinkableAccountDepositCollector::<T>::change_deposit_owner(&account, source.sender()) } /// Updates the deposit amount to the current deposit rate. /// /// The sender must be the deposit owner. #[pallet::call_index(6)] #[pallet::weight(<T as Config>::WeightInfo::update_deposit())] pub fn update_deposit(origin: OriginFor<T>, account: AccountIdOf<T>) -> DispatchResult { let source = ensure_signed(origin)?; let record = ConnectedDids::<T>::get(&account).ok_or(Error::<T>::AssociationNotFound)?; ensure!(record.deposit.owner == source, Error::<T>::NotAuthorized); LinkableAccountDepositCollector::<T>::update_deposit(&account) } } impl<T: Config> Pallet<T> { pub(crate) fn add_association( sender: AccountIdOf<T>, did_identifier: DidIdentifierOf<T>, account: AccountIdOf<T>, ) -> DispatchResult { let deposit = Deposit { owner: sender, amount: T::Deposit::get(), }; let record = ConnectionRecord { deposit, did: did_identifier.clone(), }; // *** NO FAILURE beyond the reserve call *** CurrencyOf::<T>::reserve(&record.deposit.owner, record.deposit.amount)?; ConnectedDids::<T>::mutate(&account, |did_entry| { if let Some(old_connection) = did_entry.replace(record) { ConnectedAccounts::<T>::remove(&old_connection.did, &account); Self::deposit_event(Event::<T>::AssociationRemoved(account.clone(), old_connection.did)); kilt_support::free_deposit::<AccountIdOf<T>, CurrencyOf<T>>(&old_connection.deposit); } }); ConnectedAccounts::<T>::insert(&did_identifier, &account, ()); Self::deposit_event(Event::AssociationEstablished(account, did_identifier)); Ok(()) } pub(crate) fn remove_association(account: AccountIdOf<T>) -> DispatchResult { if let Some(connection) = ConnectedDids::<T>::take(&account) { ConnectedAccounts::<T>::remove(&connection.did, &account); kilt_support::free_deposit::<AccountIdOf<T>, CurrencyOf<T>>(&connection.deposit); Self::deposit_event(Event::AssociationRemoved(account, connection.did)); Ok(()) } else { Err(Error::<T>::AssociationNotFound.into()) } } } struct LinkableAccountDepositCollector<T: Config>(PhantomData<T>); impl<T: Config> StorageDepositCollector<AccountIdOf<T>, AccountIdOf<T>> for LinkableAccountDepositCollector<T> { type Currency = T::Currency; fn deposit( key: &AccountIdOf<T>, ) -> Result<Deposit<AccountIdOf<T>, <Self::Currency as Currency<AccountIdOf<T>>>::Balance>, DispatchError> { let record = ConnectedDids::<T>::get(key).ok_or(Error::<T>::AssociationNotFound)?; Ok(record.deposit) } fn deposit_amount(_key: &AccountIdOf<T>) -> <Self::Currency as Currency<AccountIdOf<T>>>::Balance { T::Deposit::get() } fn store_deposit( key: &AccountIdOf<T>, deposit: Deposit<AccountIdOf<T>, <Self::Currency as Currency<AccountIdOf<T>>>::Balance>, ) -> Result<(), DispatchError> { let record = ConnectedDids::<T>::get(key).ok_or(Error::<T>::AssociationNotFound)?; ConnectedDids::<T>::insert(key, ConnectionRecord { deposit, ..record }); Ok(()) } } }
// Copyright 2018-2023 Sophos Limited. All rights reserved. #pragma once #include "SulDownloader/suldownloaderdata/DownloadedProduct.h" #include "SulDownloader/suldownloaderdata/IRepository.h" #include <map> #include <string> #include <vector> namespace SulDownloader { class ProductUninstaller { public: ProductUninstaller() = default; ~ProductUninstaller() = default; /** * @brief This function will run the uninstall scripts for any product installed that is not in * the list of downloaded products. * @param downloadedProducts * @return List of products that have been uninstalled */ std::vector<suldownloaderdata::DownloadedProduct> removeProductsNotDownloaded( const std::vector<suldownloaderdata::DownloadedProduct>& downloadedProducts, suldownloaderdata::IRepository& iRepository); /*** * @brief This function will run the provided uninstall script passing in the hardcoded flag --downgrade * to the uninstall script, this will instruct the script to perform any require tasks needed to ensure * a successful downgrade can occur. * * @return true if successful */ bool prepareProductForDowngrade(const std::string& uninstallScript); private: std::vector<std::string> getInstalledProductPathsList(); std::vector<suldownloaderdata::DownloadedProduct> removeProducts( std::map<std::string, suldownloaderdata::DownloadedProduct> uninstallProductInfo); }; } // namespace SulDownloader
import * as PIXI from 'pixi.js'; import { PixiMap } from './PixiMap'; import { PixiInternalLayer } from './PixiInternalLayer'; import { MapLayer } from './layers/MapLayer'; import { IPosition } from './MercatorMap'; import { Vector2 } from './Vector2'; import { ILatLong } from '@/cottno/lib/interfaces/ILatLong'; /** * Responsible for managing the layers of the map and ensuring that function calls are passed through to each layer. */ export class PixiLayerManager { public layers: PixiInternalLayer[] = []; private map: PixiMap; private initialPosition: IPosition; private idCounter: number = 0; constructor(map: PixiMap) { this.map = map; this.initialPosition = { lat: 0, long: 0, zoom: 3 }; } public refresh(): void { this.layers.forEach((layer) => layer.refresh()); } public resize(height: number, width: number): void { this.layers.forEach((layer) => layer.resize(height, width)); } public setPosition(position: IPosition): void { if (this.layers.length === 0) { this.initialPosition = position; } this.layers.forEach((layer) => layer.setPosition(position)); } public getPosition(): IPosition { return this.layers[0].getPosition(); } public refreshTile(tileKey: number): void { this.layers.forEach((layer) => layer.revalidateTile(tileKey)); } public getLatLongFromGlobal(x: number, y: number): ILatLong { return this.layers[0].getLatLongFromGlobal(x, y); } /** * Adds a layer to the tiles. * @param mapLayer The layer to add. * @param index The index of the layer. */ public addLayer(mapLayer: MapLayer, index?: number): void { if (index && index > this.layers.length) { throw new Error(`Index out out of range adding new layer in PixiTileManager.`); } mapLayer.id = this.idCounter++; const position = this.layers.length === 0 ? this.initialPosition : this.layers[0].getPosition(); const layer = new PixiInternalLayer(this.map, mapLayer, position); if (index) { this.layers.splice(index, 0, layer); } else { this.layers.push(layer); } } public getLayers(): MapLayer[] { return this.layers.map((layer) => layer.layer); } public panPx(moveVector: Vector2): void { this.layers.forEach((layer) => layer.panPx(moveVector)); } public zoom(deltaZ: number, zoomOrigin: Vector2): void { this.layers.forEach((layer) => layer.zoom(deltaZ, zoomOrigin)); } }
import React, { useState, useEffect } from "react" import { Breadcrumb } from 'antd'; import { HomeOutlined } from '@ant-design/icons'; import { useLocation } from "react-router-dom"; export default function Bread() { const [breadName, setbreadName] = useState() const { pathname } = useLocation(); useEffect(() => { switch (pathname) { case "/list": setbreadName('查看可选课程') break case "/courses": setbreadName('已选课程') break case "/means": setbreadName('修改资料') break case "/teacher/list": setbreadName('所授课程') break case "/teacher/addCourse": setbreadName('增加课程') break case "/teacher/means": setbreadName('修改资料') break case "/jwc/list": setbreadName('所有课程信息') break case "/jwc/roomList": setbreadName('教室课程信息') break case "/jwc/means": setbreadName('修改资料') break default: break } }, [pathname]) return ( <Breadcrumb style={{ height: "30px", lineHeight: "30px" }}> <Breadcrumb.Item href='/'> <HomeOutlined /> </Breadcrumb.Item> <Breadcrumb.Item >{breadName}</Breadcrumb.Item> </Breadcrumb> ) }
import React, { useState } from "react"; interface FilterProps { onFilterChange: (filters: { name?: string; status?: string; species?: string; type?: string; gender?: string; }) => void; } const Filter: React.FC<FilterProps> = ({ onFilterChange }) => { const [name, setName] = useState(""); const [status, setStatus] = useState(""); const [species, setSpecies] = useState(""); const [type, setType] = useState(""); const [gender, setGender] = useState(""); const handleFilterChange = () => { onFilterChange({ name, status, species, type, gender }); }; const handleResetFilters = () => { setName(""); setStatus(""); setSpecies(""); setType(""); setGender(""); onFilterChange({}); }; return ( <div className="mb-4"> <input type="text" placeholder="Name" value={name} onChange={(e) => setName(e.target.value)} className="border p-2 mr-2" /> <select value={status} onChange={(e) => setStatus(e.target.value)} className="border p-2 mr-2" > <option value="">Status</option> <option value="alive">Alive</option> <option value="dead">Dead</option> <option value="unknown">Unknown</option> </select> <input type="text" placeholder="Species" value={species} onChange={(e) => setSpecies(e.target.value)} className="border p-2 mr-2" /> <input type="text" placeholder="Type" value={type} onChange={(e) => setType(e.target.value)} className="border p-2 mr-2" /> <select value={gender} onChange={(e) => setGender(e.target.value)} className="border p-2 mr-2" > <option value="">Gender</option> <option value="male">Male</option> <option value="female">Female</option> <option value="genderless">Genderless</option> <option value="unknown">Unknown</option> </select> <button onClick={handleFilterChange} className="bg-blue-500 text-white p-2 mr-2" > Filter </button> <button onClick={handleResetFilters} className="bg-gray-500 text-white p-2" > Reset </button> </div> ); }; export default Filter;
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title><?php wp_title(); ?> <?php bloginfo( 'name' ); ?></title> <!-- Framework CSS --> <link rel="stylesheet" href="http://www.blueprintcss.org/blueprint/screen.css" type="text/css" media="screen, projection"> <link rel="stylesheet" href="http://www.blueprintcss.org/blueprint/print.css" type="text/css" media="print"> <!--[if lt IE 8]><link rel="stylesheet" href="http://www.blueprintcss.org/blueprint/ie.css" type="text/css" media="screen, projection"><![endif]--> <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>"> <?php if ( is_singular() && get_option( 'thread_comments' ) ) wp_enqueue_script( 'comment-reply' ); ?> <?php wp_head(); ?> <style type="text/css"> .entry-post { display: block; margin-top: 1.5em; margin-bottom: 1.5em; padding: 1em; border-bottom: dotted 1px #ccc; } .entry-title {font-size: 1.8em; border-bottom: solid 2px #ecfefc;} .entry-meta { font-size: 0.9em; } .entry-content { font-size: 1.2em; margin: 1em; dispaly: block;} .entry-utility { font-size: 0.9em; } .pagination { margin: 1em; padding: 2px; display: block; } .left { text-align: left; } .right { text-align: right; } .center { text-align: center; } </style> </head> <body> <div class="container"> <div>Menu</div> <h2>Tairan's Story</h2> <h4 class="alt">subtitle</h4> <hr><!-- end of header --> <div class="span-16 append-1 colborder"> <?php if(have_posts()): while (have_posts()): the_post(); ?> <div class="entry-post"> <div class="entry-title"><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a></div> <div class="entry-meta">Posted by<?php the_author(); ?> at <small><?php the_time('F jS, Y'); ?></div> <div class="entry-content"> <?php the_content(); ?> </div> <div class="entry-utility"><?php comments_popup_link('No Comments »', '1 Comment »', '% Comments »'); ?> | <?php the_tags('Tags:', ','); ?> | Categories: <?php the_category(', ') ?> </div> </div> <?php endwhile; endif; ?> <div class="pagination"> <div class="span-2 left"><?php posts_nav_link('','','&laquo; Previous Entries') ?></div> <div class="span-6 prepend-2 append-2">&nbsp;</div> <div class="span-2 last right"><a href=""><?php posts_nav_link('','Next Entries &raquo;','') ?></a></div> </div><!-- pagination --> </div> <div class="span-7 last"> <div class="widget"> <div class="widget-title">Douban</div> <div class="widget-container">My douban list</div> </div> <?php get_siderbar(); ?> </div> <!-- end of content --> <?php wp_footer(); ?> </body> </html>
import threading import requests # Использование неинициализированных данных def use_uninitialized_data(): var = None # должно быть инициализировано print(var + 1) # TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' # Утечки ресурсов def resource_leak(): file = open('some_file.txt', 'w') # Файл не закрывается file.write('Hello, world!') # Неправильное использование API def incorrect_api_usage(): # Неправильный URL вызовет исключение requests.exceptions.MissingSchema response = requests.get('htp://example.com') # Опечатка в 'http' print(response.text) # Проблемы с управлением потоком выполнения def control_flow_issue(): x = 10 if x > 5: raise Exception("Just an error") print(x) # Этот код никогда не выполнится из-за исключения выше # Ошибки обработки ошибок def error_handling_issue(): try: 1 / 0 except ZeroDivisionError: pass # Неправильно игнорировать ошибку без логгирования или обработки # Некорректные выражения def incorrect_expressions(): print("Sum of 1 and None is", 1 + None) # TypeError # Проблемы согласованности данных из-за параллелизма balance = 0 def update_balance(): global balance for _ in range(100000): balance += 1 # Race condition # Запуск примеров threads = [threading.Thread(target=update_balance) for _ in range(2)] for thread in threads: thread.start() for thread in threads: thread.join() print("Final balance (expected 200000):", balance) use_uninitialized_data() # Используется для демонстрации resource_leak() incorrect_api_usage() control_flow_issue() error_handling_issue() incorrect_expressions()
<mat-dialog-actions align="end"> <button mat-button mat-dialog-close> X </button> </mat-dialog-actions> <div class="container"> <h2 mat-dialog-title align="center">Registration Form</h2> <br> <mat-stepper [linear]="isLinear" #stepper> <mat-step [stepControl]="Form1" label="Personal Details"> <form [formGroup]="Form1" > <div class="names"> <mat-form-field> <mat-label>First Name:</mat-label> <input matInput type="text" placeholder="First Name" formControlName="FirstName"> </mat-form-field> | <mat-form-field > <mat-label>Middle Name:</mat-label> <input matInput type="text" placeholder="Middle Name" formControlName="MiddleName"> </mat-form-field > | <mat-form-field > <mat-label>Last Name:</mat-label> <input matInput type="text" placeholder="Last Name" formControlName="LastName"> </mat-form-field > </div> <div class="ContactDetails"> <mat-form-field > <mat-label>Email:</mat-label> <input matInput type="email" placeholder="Ex: jhon@gmail.com" formControlName="Email"> </mat-form-field > | <mat-form-field > <mat-label>phone No:</mat-label> <input matInput type="tel" placeholder="Ex: +91 12345 09876" formControlName="PhoneNo"> </mat-form-field > <br> <mat-form-field > <mat-label>Firm Name/Compnay Name:</mat-label> <input matInput type="text" placeholder="Ex: Coign pvt.Ltd" formControlName="FirmName"> </mat-form-field > <br> <mat-form-field> <mat-label>Address:</mat-label> <textarea matInput placeholder="Ex: Enter Address.." formControlName="Address"></textarea> </mat-form-field> <br> </div> <mat-dialog-actions align="end"> <button mat-button matStepperNext>Next</button> <button mat-button matStepperPrevious>Back</button> </mat-dialog-actions> </form> </mat-step> <mat-step [stepControl]="Form2" label="BankDetails"> <form [formGroup]="Form2"> <div class="bankDetails"> <mat-label > TIN (Taxpayer Identification Number): </mat-label> <mat-form-field> <mat-label for="TINno">TIN (Taxpayer Identification Number): </mat-label> <input matInput type="text" placeholder="1234 XXXX XXXX 6789" formControlName="TINNo"> </mat-form-field> <br> <mat-label > PAN No: </mat-label> <mat-form-field> <mat-label for="panNo">PAN No: </mat-label> <input matInput type="text" placeholder="ABCX XXXX D " formControlName="PANNo"> </mat-form-field> <br> <mat-label > Bank IFSC Code: </mat-label> <mat-form-field> <mat-label for="Ifsc">Bank IFSC Code:</mat-label> <input matInput type="text" placeholder="Ex:- SBI012345678 " formControlName="IFSC"> </mat-form-field> <br> <mat-label > Bank Account No: </mat-label> <mat-form-field> <mat-label for="BankAcNo">Bank Account No:</mat-label> <input matInput type="text" placeholder="Ex:- 1234 1234 1234 1234 " formControlName="BankAcNo"> </mat-form-field> </div> <div> <mat-dialog-actions align="end"> <button mat-button matStepperNext>Next</button> <button mat-button matStepperPrevious>Back</button> </mat-dialog-actions> </div> </form> </mat-step> <mat-step [stepControl]="Form3" label="Login Details"> <form [formGroup]="Form3"> <div> <mat-form-field> <mat-icon matPrefix>account_circle</mat-icon> <mat-label for="UserName"> Username:</mat-label> <input matInput type="text" placeholder="Ex: Epson@123" formControlName="UserName"> </mat-form-field> </div> <div> <mat-form-field> <mat-icon matPrefix>visibility_off</mat-icon> <mat-label for="Password">Password:</mat-label> <input matInput type="password" placeholder="Ex: Password#321" formControlName="Password"> </mat-form-field> </div> <div> <mat-form-field> <mat-icon matPrefix>visibility</mat-icon> <mat-label >Confirm Password:</mat-label> <input matInput type="text" formControlName="Password"> </mat-form-field> </div> <div> <mat-form-field> <mat-icon matPrefix> vpn_key</mat-icon> <mat-label >Security Question ?</mat-label> <mat-select formControlName="SecurityQuestion"> <mat-option value="what is your favourite Bike ?">what is your favourite Bike ?</mat-option> <mat-option value="what is your father Name ?">what is your father Name ?</mat-option> <mat-option value="who is your favourite person ?">who is your favourite person ?</mat-option> <mat-option value="what is your favourite flower ?">what is your favourite flower ?</mat-option> <mat-option value="what is your favourite Colour ?">what is your favourite Colour ?</mat-option> </mat-select> </mat-form-field> </div> <div> <mat-form-field> <mat-label >Security Answer :</mat-label> <input matInput type="text" placeholder="Ex:" formControlName="SecurityAns"> </mat-form-field> </div> <div class="btns"> <button mat-raised-button (click)="Registration()"> Submit </button> | <button mat-raised-button type="reset"> Reset </button> </div> </form> </mat-step> </mat-stepper> </div>
<template> <o-modal v-model:active="computedValue" role="dialog" :full-screen="fullScreen" :aria-label="title" aria-modal auto-focus trap-focus :can-cancel="['escape', 'outside']" @close="emit('close')" > <header class="modal-card-header"> <slot name="header"> <h1 class="text-3xl font-light"> {{ title }} </h1> <span class="ml-3 text-2xl cursor-pointer" role="button" tabindex="0" @click="doClose" @keydown.enter="doClose" @keydown.space="doClose" ><o-icon icon="times"></o-icon ></span> </slot> </header> <section class="flex-1 p-4 overflow-y-scroll border-t-2 border-b-2 border-gray-300" > <slot /> </section> <footer class="modal-card-footer"> <slot name="footer"> <o-button @click="doClose" @keydown.space="doClose" @keydown.enter="doClose" role="button" tabindex="0" >Close</o-button > </slot> </footer> </o-modal> </template> <style scoped> .modal-card-header, .modal-card-footer { @apply flex; @apply flex-row; @apply justify-between; @apply px-4; @apply py-3; @apply items-center; } </style> <script setup lang="ts"> import { useComputedValue } from 'conductorr-lib'; const props = defineProps<{ title: string, fullScreen?: boolean modelValue: boolean }>() const emit = defineEmits<{ (e: "close"): void (e: "update:modelValue", newVal: boolean): void }>() const computedValue = useComputedValue<boolean>(props, emit) const doClose = () => { emit("close") computedValue.value = false; } </script>
// src/pages/Sedes.jsx import React, { useState, useEffect } from 'react'; import axios from '../services/axiosConfig'; import SedesModal from '../components/SedesModal'; import ToggleSwitch from '../components/ToggleSwitch'; import Card from '../components/Card'; const Sedes = () => { const [sedes, setSedes] = useState([]); const [modalOpen, setModalOpen] = useState(false); const [selectedSede, setSelectedSede] = useState(null); const [isMegatlon, setIsMegatlon] = useState(true); useEffect(() => { fetchSedes(); }, [isMegatlon]); const fetchSedes = async () => { try { const response = await axios.get('/sedes'); const filteredSedes = response.data.filter(sede => isMegatlon ? sede.Empresa.nombre === 'Megatlon' : sede.Empresa.nombre === 'Fiter' ); setSedes(filteredSedes); } catch (error) { console.error('Error al obtener las sedes', error); } }; const handleOpenModal = (sede = null) => { setSelectedSede(sede); setModalOpen(true); }; const handleCloseModal = () => { setSelectedSede(null); setModalOpen(false); fetchSedes(); }; const handleToggle = () => { setIsMegatlon(prevState => !prevState); }; return ( <div className="container mx-auto"> <h1 className="text-4xl font-bold mb-4">Sedes</h1> <div className="mb-4 flex items-center justify-between"> <button onClick={() => handleOpenModal()} className="bg-blue-500 text-white py-2 px-4 rounded" > Crear Sede </button> <ToggleSwitch isChecked={!isMegatlon} onChange={handleToggle} label1="Megatlon" label2="Fiter" /> </div> <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5"> {sedes.map(sede => ( <Card key={sede.id_sede} sede={sede} isMegatlon={isMegatlon} onEdit={handleOpenModal} /> ))} </div> {modalOpen && ( <SedesModal isOpen={modalOpen} onClose={handleCloseModal} sede={selectedSede} /> )} </div> ); }; export default Sedes;
import {Injectable} from '@angular/core'; import {Observable, of} from "rxjs"; import {HttpClient} from "@angular/common/http"; import {Country} from "../common/country"; import {map} from "rxjs/operators"; import {State} from "../common/state"; class GetResponseStates { } @Injectable({ providedIn: 'root' }) export class BlazeFormServiceService { private countriesUrl='http://localhost:8080/api/countries'; private statesUrl='http://localhost:8080/api/states'; constructor(private httpClient: HttpClient) {} getCountries():Observable<Country[]>{ return this.httpClient.get<GetResponseCountries>(this.countriesUrl).pipe( map(response => response._embedded.countries) ); } getStates(theCountryCode:string):Observable<State[]>{ const searchStatesUrl=`${this.statesUrl}/search/findByCountryCode?code=${theCountryCode}`; return this.httpClient.get<GetResponseStates>(searchStatesUrl).pipe( map(response => response._embedded.states) ); } getCreditCardMonth(startMonth: number): Observable<number[]> { let data: number[] = []; //build an array for month dropdown list // start at current month and loop until month 12 for (let theMonth = startMonth; theMonth <= 12; theMonth++) { data.push(theMonth); } return of(data); } getCreditCardYears(): Observable<number[]> { let data: number[] = []; //build an array for Year dropdown list // start at current year and loop until the next 10 years const startYear: number = new Date().getFullYear(); const endYear: number = startYear + 10; for (let theYear = startYear; theYear <= endYear; theYear++) { data.push(theYear); } return of(data); } } interface GetResponseCountries { _embedded:{ countries:Country[]; } } interface GetResponseStates { _embedded:{ states:State[]; } }
const express = require('express'); const cors = require('cors'); const app = express(); const mongoose = require('mongoose'); require('dotenv').config(); const register = require('./api/register'); const login = require('./api/login'); const productRouter = require('./api/products'); app.use(cors()); app.use(express.json()); app.use('/api/login', login); app.use('/api/register', register); app.get('/', (req, res) => { res.send('Hello world!'); }); app.use('/api/products', productRouter); const port = process.env.PORT || 8080; const uri = process.env.DB_URI; app.listen(port, () => { console.log(`Server started on port ${port}`); }); mongoose .connect(uri, { useNewUrlParser: true, useUnifiedTopology: true, }) .then(() => { console.log('Connected to database'); }) .catch(err => { console.log('Connection failed', err.message); });
import LogEntry from '../../../components/LogEntry/LogEntry' import './user-logs.scss' import LoadingSpinner from '../../../components/Loading/LoadingSpinner/LoadingSpinner' import ErrorText from '../../../components/Error/ErrorText' import { useSectionsQuery, useUserLogsQuery, } from '../../../graphql/hooks/graphql' import InfiniteScroll from 'react-infinite-scroller' import { useEffect, useState } from 'react' export default function UserLogs() { const { data: userLogs, loading: userLogsLoading, error: userLogsError, fetchMore, } = useUserLogsQuery({ variables: { limit: 20, offset: 0 } }) const { data: sections, loading: sectionsLoading, error: sectionsError, } = useSectionsQuery() const [logsPerSection, setLogsPerSection] = useState([]) const [selectedSection, setSelectedSection] = useState('') const [hasMore, setHasMore] = useState(true) const loadMoreHandle = (page) => { fetchMore({ variables: { limit: 10, offset: userLogs.userLogs.length }, updateQuery: (prev, { fetchMoreResult }) => { if (!fetchMoreResult) return if (fetchMoreResult.userLogs.length === 0) { setHasMore(false) return } return { userLogs: prev.userLogs.concat(fetchMoreResult.userLogs), } }, }) } const handleChange = (e) => { setSelectedSection(e.target.value) } useEffect(() => { const filterLogs = userLogs?.userLogs.filter( (userlog) => userlog.section === selectedSection ) setLogsPerSection(filterLogs) }, [userLogs, selectedSection]) if (userLogsLoading) return <LoadingSpinner /> if (userLogsError) return <ErrorText>Something went wrong</ErrorText> if (sectionsLoading) return <LoadingSpinner /> if (sectionsError) return <ErrorText>Something went wrong</ErrorText> return ( <div className="user-logs"> <p className="user-logs__heading fw-bold">User Logs</p> <div className="user-logs__drop-down__container"> <label className="fw-bold fs-500" htmlFor="filter-logs"> Filter by section:{' '} </label> <select id="filter-logs" onChange={handleChange}> <option value={''}>{''}</option> {sections.sections.map((section) => ( <option key={section.id} value={section.section_name}> {section.section_name} </option> ))} </select> </div> <div className="user-logs-container control-panel__card"> <InfiniteScroll pageStart={0} loadMore={loadMoreHandle} hasMore={hasMore} loader={<LoadingSpinner key={0} />} threshold={50} > {selectedSection === '' ? userLogs.userLogs.map((log, index) => ( <LogEntry key={index} createdAt={Intl.DateTimeFormat('en-US', { dateStyle: 'medium', timeStyle: 'short', }).format(new Date(log.createdAt))} actionDescription={log.action_description} fullName={log.full_name} section={log.section} userId={log.user_id} /> )) : logsPerSection.map((log, index) => ( <LogEntry key={index} createdAt={Intl.DateTimeFormat('en-US', { dateStyle: 'medium', timeStyle: 'short', }).format(new Date(log.createdAt))} actionDescription={log.action_description} fullName={log.full_name} section={log.section} userId={log.user_id} /> ))} </InfiniteScroll> </div> </div> ) }
%FILE internal/type-05.html %LASTMOD %KEY pgsql-type05 %TITLE 日付/時刻表示形式とタイムゾーンの設定 %CHAPTER 日付/時刻表示形式の切り替え <p> SET datestyle文で日付/時刻表示形式を切替えます。書式は次のとおりです。 </p> [<書式>] <pre> SET datestyle TO 'DATESTYLE[, DATESTYLE, ...]' </pre> <br> <table><tr bgcolor="#cccccc"> <th>DATESTYLE</th> <th>説明                     </th> </tr><tr> <td>ISO</td> <td>ISO 8601 形式(yyyy-mm-dd HH:MM:SS)。デフォルト</td> </tr><tr> <td>SQL </td> <td>Oracle/Ingres 様式</td> </tr><tr> <td>PostgreSQL</td> <td>PostgreSQL独自形式(Ex.The 4 Nov 12:15:01 2011 JST) </td> </tr><tr> <td>German</td> <td>dd.mm.yyyy 形式</td> </tr><tr> <td>European</td> <td>dd/mm/yyyy形式。"DMY"</td> </tr><tr> <td>NonEuropean, US</td> <td>mm/dd/yyyy 形式。"MDY"</td> </tr></table> <br> <p> ・日付表示形式の切り替え <br> ヨーロッパ式、米国式に切り替えます。現在の日付/時間表示形式はSHOW datestyle文でわかります。 </p> <pre> sampledb=# SHOW datestyle; DateStyle ----------- ISO, YMD (1 row) sampledb=# SELECT DATE '2012-11-04'; date ------------ 2012-11-04 (1 row) sampledb=# SET datestyle TO SQL,European; SELECT DATE '2012-11-04'; SET date ------------ 04/11/2012 (1 row) sampledb=# SET datestyle TO SQL,DMY; SELECT DATE '2012-11-04'; SET date ------------ 04/11/2012 (1 row) </pre> <br> %CHAPTER タイムゾーンの切り替え <p> SET TIME ZONE文でタイムゾーンを設定します。書式は次のとおりです。 </p> [<書式>] <pre> SET TIME ZONE TIMEZONE_STYLE </pre> <br> <p> TIMEZONE_STYLEに設定できる値はOSやディストリビューションによって異なります。 Linux、MacOSX、FreeBSD は/usr/share/zoneinfo以下にタイムゾーンのデータベースがあります。 </p> <p> ・タイムゾーンの設定 <br> タイムゾーン"GMT+9"を設定します。現在のタイムゾーンはSHOW TIME ZONE文でわかります。 </p> <pre> sampledb=# SHOW TIME ZONE; TimeZone ---------- Japan (1 row) sampledb=# SET TIME ZONE 'GMT+9'; SHOW TIME ZONE; SET TimeZone ---------- GMT+9 (1 row) </pre> <br>
/* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2002-2008, Open Source Geospatial Foundation (OSGeo) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package org.geotools.graph.structure.basic; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import org.geotools.graph.structure.DirectedEdge; import org.geotools.graph.structure.DirectedNode; import org.geotools.graph.structure.Edge; import org.geotools.graph.structure.Node; /** * Basic implementation of DirectedEdge. * * @author Justin Deoliveira, Refractions Research Inc, jdeolive@refractions.net * * * * @source $URL$ */ public class BasicDirectedEdge extends BasicGraphable implements DirectedEdge { /** in node **/ private DirectedNode m_in; /** out node **/ private DirectedNode m_out; /** Contstructs a new DirectedEdge. * * @param in The in node of the edge. * @param out The out node of the edge. */ public BasicDirectedEdge(DirectedNode in, DirectedNode out) { super(); m_in = in; m_out = out; } /** * @see DirectedEdge#getInNode() */ public DirectedNode getInNode() { return(m_in); } /** * @see DirectedEdge#getOutNode() */ public DirectedNode getOutNode() { return(m_out); } /** * Returns the in node. * * @see Edge#getNodeA() */ public Node getNodeA() { return(m_in); } /** * Returns the out node. * * @see Edge#getNodeB() */ public Node getNodeB() { return(m_out); } /** * @see Edge#getOtherNode(Node) */ public Node getOtherNode(Node node) { return(m_in.equals(node) ? m_out : m_out.equals(node) ? m_in : null); } /** * Removes the edge from the out list of the in node and from the in list of * the out node. Nodes are switched and then the edge is added to the in list * of the new out node, and to the out list of the new in node. * * @see Edge#reverse() * */ public void reverse() { //remove edge from adjacent nodes m_in.removeOut(this); m_out.removeIn(this); //swap nodes DirectedNode tmp = m_in; m_in = m_out; m_out = tmp; //re add nodes m_in.addOut(this); m_out.addIn(this); } /** * Returns an iterator over all edges incident to both the in and out nodes. * * @see org.geotools.graph.structure.Graphable#getRelated() */ public Iterator getRelated() { HashSet related = new HashSet(); //add all edges incident to both nodes related.addAll(m_in.getEdges()); related.addAll(m_out.getEdges()); //remove this edge related.remove(this); return(related.iterator()); // // ArrayList related = new ArrayList(); // // related.addAll(m_in.getInEdges()); // // //add out edges, look for an opposite edge, it will have already // // been added so dont add it // for (Iterator itr = m_out.getOutEdges().iterator(); itr.hasNext();) { // DirectedEdge de = (DirectedEdge)itr.next(); // switch(de.compareNodes(this)) { // case OPPOSITE_NODE_ORIENTATION: continue; // } // related.add(de); // } // // //look for duplicate edges (same direction) if not equal add // // dont add opposite edges // // dont add loops // for (Iterator itr = m_in.getOutEdges().iterator(); itr.hasNext();) { // DirectedEdge de = (DirectedEdge)itr.next(); // switch(de.compareNodes(this)) { // case EQUAL_NODE_ORIENTATION: // if (!de.equals(this)) // related.add(de); // continue; // case OPPOSITE_NODE_ORIENTATION: // continue; // case UNEQUAL_NODE_ORIENTATION: // if (de.getNodeA().equals(de.getNodeB())) continue; // related.add(de); // } // } // // return(related.iterator()); } /** * Returns an iterator over the in edges of the in node. * * @see org.geotools.graph.structure.DirectedGraphable#getInRelated() */ public Iterator getInRelated() { ArrayList in = new ArrayList(); for (Iterator itr = m_in.getInEdges().iterator(); itr.hasNext();) { DirectedEdge de = (DirectedEdge)itr.next(); //this check has to be because the edge could be a loop in which case // it is in related to itself if (!de.equals(this)) in.add(de); } return(in.iterator()); } /** * Returns an iterator over the out edges of the out node. * * @see org.geotools.graph.structure.DirectedGraphable#getOutRelated() */ public Iterator getOutRelated() { ArrayList out = new ArrayList(); for (Iterator itr = m_out.getOutEdges().iterator(); itr.hasNext();) { DirectedEdge de = (DirectedEdge)itr.next(); //this check has to be because the edge could be a loop in which case // it is in related to itself if (!de.equals(this)) out.add(de); } return(out.iterator()); } /** * @see Edge#compareNodes(Edge) */ public int compareNodes(Edge other) { if (other instanceof DirectedEdge) { DirectedEdge de = (DirectedEdge)other; if (de.getInNode().equals(m_in) && de.getOutNode().equals(m_out)) return(EQUAL_NODE_ORIENTATION); if (de.getInNode().equals(m_out) && de.getOutNode().equals(m_in)) return(OPPOSITE_NODE_ORIENTATION); } return(UNEQUAL_NODE_ORIENTATION); } }
% region Filename parsing. % Provides macros manipulating strings of tokens. \RequirePackage{xstring} % Store the jobname as a string with category 11 characters. \edef\normaljobname{\expandafter\scantokens\expandafter{\jobname\noexpand}} \StrBetween{\normaljobname}{hw-}{-q}[\homeworknumber] \StrBehind{\normaljobname}{-q-}[\questionnumber] % endregion \documentclass[ coursecode={MTHE 418}, assignmentname={Homework \homeworknumber}, studentnumber=20053722, name={Bryan Hoang}, draft, % final, ]{ ltxanswer% } \usepackage{bch-style} \date{2022-02-28} \begin{document} \begin{questions} \setcounter{question}{\questionnumber} \addtocounter{question}{-1} \question[10]\ \begin{parts} \part{} \begin{solution} To solve \(11^{x} = 21\) in \(\mathbb{F}_{71}\), we first note that 11 has order 70 in \(\mathbb{F}_{71}\). Let \(n = 1 + \lfloor 70 \rfloor = 9\). After writing code to implement the algorithm, we find that \(\boxed{x = 37}\). \end{solution} \part{} \begin{solution} To solve \(156^{x} = 116\) in \(\mathbb{F}_{593}\), we first note that 156 has order 148 in \(\mathbb{F}_{593}\). Let \(n = 1 + \lfloor 148 \rfloor = 13\). After writing code to implement the algorithm, we find that \(\boxed{x = 59}\). \end{solution} \part{} \begin{solution} To solve \(650^{x} = 2213\) in \(\mathbb{F}_{3571}\), we first note that 650 has order 510 in \(\mathbb{F}_{3571}\). Let \(n = 1 + \lfloor 510 \rfloor = 23\). After writing code to implement the algorithm, we find that \(\boxed{x = 319}\). \end{solution} \end{parts} \end{questions} \end{document}
package adapters import ( "context" "fmt" "time" "google.golang.org/grpc/codes" "gitlab.cmpayments.local/creditcard/authorization/internal/entity" "cloud.google.com/go/spanner" infraSpanner "gitlab.cmpayments.local/creditcard/authorization/internal/infrastructure/spanner" ) type reversalRepository struct { client *spanner.Client readTimeout time.Duration writeTimeout time.Duration } func NewReversalRepository( client *spanner.Client, readTimeout time.Duration, writeTimeout time.Duration) *reversalRepository { return &reversalRepository{ client: client, readTimeout: readTimeout, writeTimeout: writeTimeout, } } func (rr *reversalRepository) CreateReversal(ctx context.Context, r entity.Reversal) error { _, err := rr.client.ReadWriteTransaction(ctx, func(ctx context.Context, txn *spanner.ReadWriteTransaction) error { statement := spanner.Statement{ SQL: ` INSERT INTO authorization_reversals ( authorization_id, reversal_id, status, reason, created_at, amount ) VALUES ( @authorization_id, @reversal_id, @status, @reason, @created_at, @amount )`, Params: mapCreateReversalParams(r), } ctx, cancel := context.WithTimeout(ctx, rr.writeTimeout) defer cancel() _, err := txn.Update(ctx, statement) if spanner.ErrCode(err) == codes.AlreadyExists { return entity.ErrDupValOnIndex } return err }) return err } func mapCreateReversalParams(r entity.Reversal) map[string]interface{} { return map[string]interface{}{ "authorization_id": r.AuthorizationID.String(), "reversal_id": r.ID.String(), "created_at": time.Now(), "status": r.Status, "amount": r.Amount, "reason": infraSpanner.NewNullError(r.Reason), } } func (rr *reversalRepository) UpdateReversalResponse(ctx context.Context, r entity.Reversal) error { stmt := spanner.Statement{ SQL: `UPDATE authorization_reversals SET status = @status, stan = @stan, response_code = @response_code, processing_date = @processing_date WHERE reversal_id = @reversal_id`, Params: mapUpdateReversalResponseParams(r), } _, err := rr.client.ReadWriteTransaction(ctx, func(ctx context.Context, txn *spanner.ReadWriteTransaction) error { ctx, cancel := context.WithTimeout(ctx, rr.writeTimeout) defer cancel() rowCount, err := txn.Update(ctx, stmt) if err != nil { return fmt.Errorf("failed to update reversal: %w", err) } if rowCount != 1 { return fmt.Errorf("no record found with ID: %s", r.ID.String()) } return err }) return err } func mapUpdateReversalResponseParams(r entity.Reversal) map[string]interface{} { return map[string]interface{}{ "reversal_id": r.ID.String(), "status": r.Status, "stan": infraSpanner.NewNullInt64(r.Authorization.Stan), "response_code": infraSpanner.NewNullString(r.CardSchemeData.Response.ResponseCode.Value), "processing_date": infraSpanner.NewNullTime(r.ProcessingDate), } }
package objs; import flixel.FlxG; import flixel.FlxSprite; import flixel.math.FlxPoint; import flixel.path.FlxPath; import flixel.util.FlxDirectionFlags; import flixel.util.FlxTimer; import ui.TextPopup; import ui.TextTrigger; import util.Input; /** * ... * @author aeveis */ enum ObjType { Light; Krill; Other; } class Object extends FlxSprite { private var timer:Float = 0; public static inline var NONE:Int = 0; public static inline var BOUNCE:Int = 1; public static inline var RISEFADE:Int = 2; public static inline var HIDE:Int = 3; public var state:Int = 0; public var sineAmount:Float = 1; public var sineSpeed:Float = 3; public var startY:Float = 0; public var textTrigger:TextTrigger; public var name:String = ""; public var unique:String = ""; public var paths:Map<Int, Array<FlxPoint>>; public var pathIndex:Int = 0; public var moving:Bool = false; public function new(px:Float, py:Float, pname:String = "") { super(px, py); drag.set(10, 10); setup(px, py, pname); } public function setup(px:Float, py:Float, pname:String = "") { x = px; y = py; startY = py; setFacingFlip(FlxDirectionFlags.LEFT, true, false); setFacingFlip(FlxDirectionFlags.RIGHT, false, false); switch (pname) { case "bluebird" | "sprout": name = pname; loadGraphic(AssetPaths.npc__png, true, 8, 8); animation.add("bluebird", [0], 10, false); animation.add("sprout", [1], 10, false); animation.play(name); default: if (pname != "") { name = pname; loadGraphic(AssetPaths.getFile(pname)); } } // solid = true; timer = FlxG.random.float(0, 5); } public function setUnique(pUniqueName:String) { unique = pUniqueName; paths = new Map<Int, Array<FlxPoint>>(); animation.play(pUniqueName); } public override function update(elapsed:Float) { var textboxOn:Bool = PlayState.instance.textbox.visible; if (!textboxOn) { super.update(elapsed); } switch (state) { case BOUNCE: timer += elapsed * sineSpeed; if (moving) { y += (textboxOn ? 0.1 : 0.5) * sineAmount * Math.sin(timer); } else { y = startY + sineAmount * Math.sin(timer); } case RISEFADE: y -= elapsed * 5; alpha -= elapsed / 2; if (alpha <= 0) { visible = false; alpha = 1; y = startY; state = HIDE; } default: } if (textTrigger == null) return; /*if (Input.control.keys.get("select").justPressed) { if (PlayState.instance.bird.x < x) { facing = FlxDirectionFlags.LEFT; } else if (PlayState.instance.bird.x > x) { facing = FlxDirectionFlags.RIGHT; } }*/ if (!moving) return; if (velocity.x > 2) { facing = FlxDirectionFlags.RIGHT; } else if (velocity.x < -2) { facing = FlxDirectionFlags.LEFT; } if (textboxOn) return; textTrigger.setPosFromNPC(x, y); } public function nextPath() { if (paths == null) return; var points = paths.get(pathIndex); if (points == null) { trace("path missing index " + pathIndex); return; } if (moving) { for (pt in points) { path.addPoint(pt); } return; } if (path == null) { path = new FlxPath(); path.autoCenter = false; path.onComplete = onCompletePath; } moving = true; path.start(points, 75, FlxPathType.FORWARD); } public function onCompletePath(ppath:FlxPath) { attemptStopMoving(); } public function attemptStopMoving(?timer:FlxTimer) { startY = y; moving = false; pathIndex++; textTrigger.checkNotify(); } override function destroy() { if (path != null) { path.destroy(); } if (paths != null) { for (array in paths) { for (pt in array) { pt.put(); } } paths.clear(); paths = null; } super.destroy(); } }
class Plato { const baseCalorias = 100 const cocinero // necesario para el torneo method cocinero() = cocinero method cantidadAzucar() // Punto de entrada punto 1 method cantidadCalorias() = 3 * self.cantidadAzucar() + baseCalorias } class Entrada inherits Plato { method esBonito() = true override method cantidadAzucar() = 0 } class Principal inherits Plato { const esBonito const cantidadAzucar method esBonito() = esBonito override method cantidadAzucar() = cantidadAzucar } class Postre inherits Plato { const cantColores method esBonito() = cantColores > 3 override method cantidadAzucar() = 120 } class Cocinero { var especialidad // Punto de entrada punto 2. method calificacionPara(plato) = especialidad.catar(plato) // Punto de entrada punto 3. method cambiarEspecialidad(nuevaEspecialidad){ especialidad = nuevaEspecialidad } // Punto de entrada punto 5. method cocinar() = especialidad.cocinar(self) } class EspecialidadPastelero { var dulzorDeseado method catar(plato) = (5 * plato.cantidadAzucar() / dulzorDeseado).min(10) method cocinar(elCocinero) = new Postre(cocinero = elCocinero, cantColores = dulzorDeseado / 50) } class EspecialidadChef { var cantidadCaloriasDeseadas method platoCumpleExpectativa(plato) = plato.esBonito() and plato.cantidadCalorias() <= cantidadCaloriasDeseadas method catar(plato) = if (self.platoCumpleExpectativa(plato)) 10 else self.calificacionSiNoCumpleExpectativa(plato) method calificacionSiNoCumpleExpectativa(plato) = 0 method cocinar(elCocinero) = new Principal(cocinero = elCocinero, esBonito = true, cantidadAzucar = cantidadCaloriasDeseadas) } class EspecialidadSouschef inherits EspecialidadChef { override method calificacionSiNoCumpleExpectativa(plato) = (plato.cantidadCalorias() / 100).min(6) override method cocinar(elCocinero) = new Entrada(cocinero = elCocinero) } class Torneo{ const catadores = [] const platosParticipantes = [] // Punto de entrada punto 6a method sumarParticipacion(cocinero) { platosParticipantes.add(cocinero.cocinar()) } // Punto de entrada punto 6b method ganador() { if (platosParticipantes.isEmpty()) throw new DomainException(message = "No se puede definir el ganador de un torneo sin participantes") return platosParticipantes.max({plato => self.calificacionTotal(plato)}).cocinero() } method calificacionTotal(plato) = catadores.sum({catador => catador.catar(plato)}) }
<template> <div v-show="showFlag" class="food" transition="move" v-el:food> <div class="food-content"> <div class="image-header"> <img v-bind:src="food.image"> <div class="icon-top" @click="hide"> <i class="icon-arrow_lift"></i> </div> </div> <div class="content"> <h1 class="title">{{food.name}}</h1> <div class="detail"> <span class="sell-count">月售{{food.sellCount}}</span> <span class="rating">好评{{food.rating}}</span> </div> <div class="price"> <span class="now">¥{{food.price}}</span><span class="old" v-show="food.oldPrice">¥{{food.oldPrice}}</span> </div> <div class="cartcontrol-wrapper"> <cartcontrol v-bind:food="food"></cartcontrol> </div> <div class="buy" v-show="!food.count || food.count===0" @click="addFirst" transition="fade"> 加入购物车 </div> </div> <split v-show="food.info"></split> <div class="info" v-show="food.info"> <h1 class="title">商品信息</h1> <span class="text">{{food.info}}</span> </div> <split></split> <div class="rating"> <h1 class="title">商品评价</h1> <ratingselect :select-type="selectType" :only-content="onlycontent" :desc="desc" :ratings="food.ratings"></ratingselect> <div class="rating-wrapper"> <ul v-show="food.ratings && food.ratings.length"> <li v-show="needShow(rating.rateType,rating.text)" v-for="rating in food.ratings" class="rating-item"> <div class="user"> <span class="name">{{rating.username}}</span> <img class="avatar" width="12" heigth="12" :src="rating.avatar"> </div> <div class="time">{{rating.rateTime | formatDate}}</div> <p class="text"> <span :class="{'icon-thumb_up':rating.rateType===0, 'icon-thumb_down':rating.rateType===1}"></span>{{rating.text}} </p> </li> </ul> <div class="no-rating" v-show="!food.ratings || !food.ratings.length">暂无评价</div> </div> </div> </div> </div> </template> <script type="text/ecmascript-6"> import BScroll from 'better-scroll'; import Vue from 'vue'; import {formatDate} from 'common/js/date.js'; import cartcontrol from 'components/cartcontrol/cartcontrol'; import split from 'components/split/split'; import ratingselect from 'components/ratingselect/ratingselect'; // const POSITIVE = 0; // const NEGATIVE = 1; const ALL = 2; export default { props: { food: { type: Object } }, data() { return { showFlag: false, selectType: ALL, onlyContent: true, desc: { all: '全部', positive: '推荐', negative: '吐槽' } }; }, methods: { show() { this.showFlag = true; this.selectType = ALL; this.onlyContent = false; this.$nextTick(() => { if (!this.scroll) { this.scroll = new BScroll(this.$els.food, { click: true }); } else { this.scroll.refresh(); } }); }, hide() { this.showFlag = false; }, addFirst(event) { if (!event._constructed) { return; }; this.$dispatch('cart.add', event.target); Vue.set(this.food, 'count', 1); }, needShow(type, text) { if (this.onlyContent && !text) { return false; }; if (this.selectType === ALL) { return true; } else { return type === this.selectType; } } }, events: { 'ratingtype.select' (type) { this.selectType = type; this.$nextTick(() => { this.scroll.refresh(); }); }, 'content.toggle' (onlyContent) { this.onlyContent = onlyContent; this.$nextTick(() => { this.scroll.refresh(); }); } }, filters: { formatDate(time) { let date = new Date(time); return formatDate(date, 'yyyy-MM-dd hh:mm'); } }, components: { cartcontrol, split, ratingselect } }; </script> <style lang="stylus" rel="stylesheet/stylus"> .food position:fixed left:0 top:0 bottom:48px z-index:20 width:100% background:#fff &.move-transition transition:all 0.3s linear transform:translate3d(0,0,0) &.move-enter,&.move-leave transform:translate3d(100%,0,0) .image-header position:relative width:100% // paddings值100%相当于宽度100% height:0 padding-top:100% img position:absolute top:0 left:0 width:100% height:100% .icon-top position:absolute top:0 left:0 .icon-arrow_lift display:block padding:12px font-size:20px color:#fff .content padding:18px position:relative .title line-height:14px margin-bottom:8px font-size:14px font-weight:bold color:rgb(7,17,27) .detail height:10px margin-bottom:18px line-height:10px font-size:0 .sell-count,.rating font-size:10px color:rgb(147,153,159) .sell-count margin-right:12px .price font-weight:bold line-height:24px .now margin-right:8px font-size:14px color:rgb(240,20,20) .old text-decoration:line-through font-size:10px color:rgb(147,153,159) .cartcontrol-wrapper position:absolute right:12px bottom:12px .buy position:absolute right:18px bottom:18px z-index:10 height:24px line-height:24px padding: 0 12px box-sizing:border-box font-size:10px border-radius:12px color:#fff background:rgb(0,160,220) &.fade-transition opacity:1 transition:all 0.2s &.fade-enter,&.fade-leave opacity:0 .info padding:18px; .title line-height:14px margin-bottom:6px font-size:14px color:rgb(7,17,27) .text padding:0 8px line-height:24px font-size:12px color:rgb(77,85,93) .rating padding-top:18px .title line-height:14px margin-left:18px font-size:14px color:rgb(7,17,27) .rating-wrapper padding:0 18px .rating-item position:relative padding: 16px 0 border-bottom:1px solid rgba(7,17,27,0.2) .user position:absolute right:0 top:16px line-height:12px font-size:0 .name display:inline-block margin-right:6px vertical-align:top font-size:10px color:rgb(147,153,159) .avatar vertical-align:top border-radius:50% .time margin-bottom:6px line-height:12px font-size:10px color:rgb(147,153,159) .text line-height:16px font-size:12px color:rgb(7,17,27) .icon-thumb_up,.icon-thumb_down margin-right:4px line-height:16px font-size:12px .icon-thumb_up color:rgb(0,160,220) .icon-thumb_down color:rgb(147,153,159) .no-rating padding: 16px 0 font-size: 12px color: rgb(147, 153, 159) </style>
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF 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.apache.hadoop.fs.viewfs; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileContext; import org.apache.hadoop.fs.FileContextTestHelper; import org.apache.hadoop.fs.FsConstants; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.hdfs.MiniDFSNNTopology; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /** * Verify XAttrs through ViewFs functionality. */ public class TestViewFsWithXAttrs { private static MiniDFSCluster cluster; private static Configuration clusterConf = new Configuration(); private static FileContext fc, fc2; private FileContext fcView, fcTarget, fcTarget2; private Configuration fsViewConf; private Path targetTestRoot, targetTestRoot2, mountOnNn1, mountOnNn2; private FileContextTestHelper fileContextTestHelper = new FileContextTestHelper("/tmp/TestViewFsWithXAttrs"); // XAttrs protected static final String name1 = "user.a1"; protected static final byte[] value1 = {0x31, 0x32, 0x33}; protected static final String name2 = "user.a2"; protected static final byte[] value2 = {0x37, 0x38, 0x39}; @BeforeClass public static void clusterSetupAtBeginning() throws IOException { cluster = new MiniDFSCluster.Builder(clusterConf) .nnTopology(MiniDFSNNTopology.simpleFederatedTopology(2)) .numDataNodes(2) .build(); cluster.waitClusterUp(); fc = FileContext.getFileContext(cluster.getURI(0), clusterConf); fc2 = FileContext.getFileContext(cluster.getURI(1), clusterConf); } @AfterClass public static void ClusterShutdownAtEnd() throws Exception { if (cluster != null) { cluster.shutdown(); } } @Before public void setUp() throws Exception { fcTarget = fc; fcTarget2 = fc2; targetTestRoot = fileContextTestHelper.getAbsoluteTestRootPath(fc); targetTestRoot2 = fileContextTestHelper.getAbsoluteTestRootPath(fc2); fcTarget.delete(targetTestRoot, true); fcTarget2.delete(targetTestRoot2, true); fcTarget.mkdir(targetTestRoot, new FsPermission((short) 0750), true); fcTarget2.mkdir(targetTestRoot2, new FsPermission((short) 0750), true); fsViewConf = ViewFileSystemTestSetup.createConfig(); setupMountPoints(); fcView = FileContext.getFileContext(FsConstants.VIEWFS_URI, fsViewConf); } private void setupMountPoints() { mountOnNn1 = new Path("/mountOnNn1"); mountOnNn2 = new Path("/mountOnNn2"); ConfigUtil.addLink(fsViewConf, mountOnNn1.toString(), targetTestRoot.toUri()); ConfigUtil.addLink(fsViewConf, mountOnNn2.toString(), targetTestRoot2.toUri()); } @After public void tearDown() throws Exception { fcTarget.delete(fileContextTestHelper.getTestRootPath(fcTarget), true); fcTarget2.delete(fileContextTestHelper.getTestRootPath(fcTarget2), true); } /** * Verify a ViewFs wrapped over multiple federated NameNodes will * dispatch the XAttr operations to the correct NameNode. */ @Test public void testXAttrOnMountEntry() throws Exception { // Set XAttrs on the first namespace and verify they are correct fcView.setXAttr(mountOnNn1, name1, value1); fcView.setXAttr(mountOnNn1, name2, value2); assertEquals(2, fcView.getXAttrs(mountOnNn1).size()); assertArrayEquals(value1, fcView.getXAttr(mountOnNn1, name1)); assertArrayEquals(value2, fcView.getXAttr(mountOnNn1, name2)); // Double-check by getting the XAttrs using FileSystem // instead of ViewFs assertArrayEquals(value1, fc.getXAttr(targetTestRoot, name1)); assertArrayEquals(value2, fc.getXAttr(targetTestRoot, name2)); // Paranoid check: verify the other namespace does not // have XAttrs set on the same path. assertEquals(0, fcView.getXAttrs(mountOnNn2).size()); assertEquals(0, fc2.getXAttrs(targetTestRoot2).size()); // Remove the XAttr entries on the first namespace fcView.removeXAttr(mountOnNn1, name1); fcView.removeXAttr(mountOnNn1, name2); assertEquals(0, fcView.getXAttrs(mountOnNn1).size()); assertEquals(0, fc.getXAttrs(targetTestRoot).size()); // Now set XAttrs on the second namespace fcView.setXAttr(mountOnNn2, name1, value1); fcView.setXAttr(mountOnNn2, name2, value2); assertEquals(2, fcView.getXAttrs(mountOnNn2).size()); assertArrayEquals(value1, fcView.getXAttr(mountOnNn2, name1)); assertArrayEquals(value2, fcView.getXAttr(mountOnNn2, name2)); assertArrayEquals(value1, fc2.getXAttr(targetTestRoot2, name1)); assertArrayEquals(value2, fc2.getXAttr(targetTestRoot2, name2)); fcView.removeXAttr(mountOnNn2, name1); fcView.removeXAttr(mountOnNn2, name2); assertEquals(0, fcView.getXAttrs(mountOnNn2).size()); assertEquals(0, fc2.getXAttrs(targetTestRoot2).size()); } }
/*! * \file MIsScalar.hpp Traits meta-class that helps to check if given * type is a scalar type. * \brief Traits meta-class: scalar type checking trait. * \author Ivan Shynkarenka aka 4ekucT * \version 1.0 * \date 13.12.2006 */ /* FILE DESCRIPTION: Traits meta-class: scalar type checking trait. AUTHOR: Ivan Shynkarenka aka 4ekucT GROUP: The NULL workgroup PROJECT: The Depth PART: Type traits VERSION: 1.0 CREATED: 13.12.2006 22:23:53 EMAIL: chronoxor@gmail.com WWW: http://code.google.com/p/depth COPYRIGHT: (C) 2005-2010 The NULL workgroup. All Rights Reserved. */ /*--------------------------------------------------------------------------*/ /* Copyright (C) 2005-2010 The NULL workgroup. 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /*--------------------------------------------------------------------------*/ /* FILE ID: $Id$ CHANGE LOG: $Log$ */ #ifndef __MISSCALAR_HPP__ #define __MISSCALAR_HPP__ #include <Depth/include/traits/MIfThenElse.hpp> #include <Depth/include/traits/MIsArithmetic.hpp> #include <Depth/include/traits/MIsEnum.hpp> #include <Depth/include/traits/MIsPointer.hpp> #include <Depth/include/traits/MIsMemberPointerToObject.hpp> /* NAMESPACE DECLARATIONS */ namespace NDepth { /*--------------------------------------------------------------------------*/ namespace NTraits { /* META-CLASS DECLARATIONS */ //! Traits meta-class: scalar type checking trait. /*! Traits meta-class checks if template argument is a scalar type. This type is valid for: MIsArithmetic, MIsEnum, MIsPointer and MIsPointerToMember types. Here comes some examples of using this trait: Expression: Result type: MIsScalar<bool>::yes true MIsScalar<char*>::yes true MIsScalar<class>::yes false */ template <typename T_Type> class MIsScalar : public MIfThenElse<MIsOr<MIsArithmetic<T_Type>::yes, MIsEnum<T_Type>::yes, MIsPointer<T_Type>::yes, MIsMemberPointerToObject<T_Type>::yes>::yes, MTypeTrue, MTypeFalse>::type { }; } /*--------------------------------------------------------------------------*/ } #endif
package io.github.brenoepics.at4j.azure.lang; import com.fasterxml.jackson.databind.node.ObjectNode; /** Represents a language with its code, name, native name and direction. */ public class Language { private String code; private String name; private String nativeName; private LanguageDirection direction; /** * Constructs a new Language object. * * @param code the language code * @param name the language name * @param nativeName the native name of the language * @param direction the direction of the language */ public Language(String code, String name, String nativeName, LanguageDirection direction) { this.code = code; this.name = name; this.nativeName = nativeName; this.direction = direction; } /** * Constructs a new Language object from a JSON object. * * @param code the language code * @param json the JSON object containing language details * @return a new Language object */ public static Language ofJSON(String code, ObjectNode json) { return new Language( code, json.get("name").asText(), json.get("nativeName").asText(), LanguageDirection.fromString(json.get("dir").asText())); } /** * Returns a string representation of the Language object. * * @return a string representation of the Language object */ @Override public String toString() { return "Language{" + "code='" + code + '\'' + ", name='" + name + '\'' + ", nativeName='" + nativeName + '\'' + ", direction=" + direction + '}'; } /** * Returns the language code. * * @return the language code */ public String getCode() { return code; } /** * Sets the language code. * * @param value the new language code */ public void setCode(String value) { this.code = value; } /** * Returns the language name. * * @return the language name */ public String getName() { return name; } /** * Sets the language name. * * @param value the new language name */ public void setName(String value) { this.name = value; } /** * Returns the native name of the language. * * @return the native name of the language */ public String getNativeName() { return nativeName; } /** * Sets the native name of the language. * * @param value the new native name of the language */ public void setNativeName(String value) { this.nativeName = value; } /** * Returns the direction of the language. * * @return the direction of the language */ public LanguageDirection getDir() { return direction; } /** * Sets the direction of the language. * * @param value the new direction of the language */ public void setDir(LanguageDirection value) { this.direction = value; } }
import { SetStateAction, SyntheticEvent, useEffect, useState } from "react"; import { useFoodModalContext } from "./FoodModal"; import { Food } from "../../types/Food"; import { supabase } from "../../api/supabaseClient"; import { useAppDispatch } from "../../app/hooks"; import { addFood } from "../../features/data/dataSlice"; import { closeFoodModal } from "../../features/modals/modalsSlice"; import { motion } from "framer-motion"; import { Input } from "../shared/Input"; import { FaChevronLeft } from "react-icons/fa"; import { CgSpinnerTwo } from "react-icons/cg"; export const FoodModalForm = () => { const dispatch = useAppDispatch(); const { foodToAdd, setShowForm, setFoodToAdd } = useFoodModalContext(); const [cachedFood, setCachedFood] = useState<Food | null>(foodToAdd); const [food, setFood] = useState<Food | null>(foodToAdd); const [servingSize, setServingSize] = useState( foodToAdd?.serving_size_g || 1 ); const [servings, setServings] = useState(foodToAdd?.servings || 1); const [isAdding, setIsAdding] = useState(false); function closeForm() { setShowForm(false); setFoodToAdd(null); } function closeModal() { dispatch(closeFoodModal()); closeForm(); } function updatePropHandler(e: SyntheticEvent) { const element = e.target as HTMLInputElement; const name = element.name; const value = element.value; const newFood = { ...(food as Food), [name]: value, }; setFood(newFood); setCachedFood(newFood); } async function submitFormHandler(e: SyntheticEvent) { e.preventDefault(); if (!food) return; let { order_id, ...foodToAddClean } = food; setIsAdding(true); try { const { data, error } = await supabase .from("food") .insert([foodToAddClean]) .select() .single(); if (error) throw Error(error.message); const { data: historyData, error: historyError } = await supabase .from("food_history") .insert([foodToAddClean]); if (historyError) throw Error(historyError.message); dispatch(addFood(data as Food)); dispatch(closeFoodModal()); setShowForm(false); setFoodToAdd(null); setIsAdding(false); } catch (e) { console.log(e); setIsAdding(false); } } useEffect(() => { if (!cachedFood) return; let multiplier = isNaN(servingSize / cachedFood.serving_size_g) ? 1 : servingSize / cachedFood.serving_size_g; let protein = formatFloat(cachedFood?.protein * multiplier); let fats = formatFloat(cachedFood?.fats * multiplier); let carbs = formatFloat(cachedFood?.carbs * multiplier); let calories = formatFloat(cachedFood?.calories * multiplier); const newFood: Food = { ...(food as Food), protein, fats, carbs, calories, serving_size_g: servingSize, servings, }; setFood(newFood); }, [servingSize, servings]); return ( <motion.div initial={{ x: 100, opacity: 0 }} animate={{ x: 0, opacity: 1 }} exit={{ x: 100, opacity: 0 }} className="h-full w-full p-5 pb-0 flex flex-col" > <div className="text-center font-bold text-lg text-gray-800 uppercase"> Add food </div> <form onSubmit={submitFormHandler} className="flex-1 flex flex-col pb-2"> <div className="mb-2"> <label className="text-gray-700 font-bold capitalize" htmlFor="name"> Name </label> <Input required type="text" value={food?.name} name="name" id="name" onChange={updatePropHandler} /> </div> <div className="mb-2"> <label className="text-gray-700 font-bold capitalize" htmlFor="protein" > protein </label> <Input required rightIcon={ <span className="italic text-gray-700 font-bold">g</span> } type="number" value={food?.protein} name="protein" id="protein" onChange={updatePropHandler} /> </div> <div className="mb-2"> <label className="text-gray-700 font-bold capitalize" htmlFor="carbs"> carbs </label> <Input rightIcon={ <span className="italic text-gray-700 font-bold">g</span> } type="number" value={food?.carbs} name="carbs" id="carbs" onChange={updatePropHandler} /> </div> <div className="mb-2"> <label className="text-gray-700 font-bold capitalize" htmlFor="fats"> fats </label> <Input required rightIcon={ <span className="italic text-gray-700 font-bold">g</span> } type="number" value={food?.fats} name="fats" id="fats" onChange={updatePropHandler} /> </div> <div className="mb-2"> <label className="text-gray-700 font-bold capitalize" htmlFor="fats"> calories </label> <Input required rightIcon={ <span className="italic text-gray-700 font-bold">kcal</span> } type="number" value={food?.calories} name="calories" id="calories" onChange={updatePropHandler} /> </div> <div className="mb-2"> <label className="text-gray-700 font-bold capitalize" htmlFor="serving_size_g" > serving size </label> <Input required rightIcon={ <span className="italic text-gray-700 font-bold">g</span> } type="number" value={servingSize} name="serving_size_g" id="serving_size_g" onChange={(e: SyntheticEvent) => { const input = e.target as HTMLInputElement; setServingSize(parseInt(input.value)); }} /> </div> <div className="mb-2"> <label className="text-gray-700 font-bold capitalize" htmlFor="servings" > servings </label> <Input required type="number" value={food?.servings} name="servings" id="servings" onChange={updatePropHandler} /> </div> <button disabled={isAdding} type="submit" className="h-10 px-4 bg-emerald-400 hover:bg-emerald-500 active:bg-emerald-600 rounded-xl text-white font-bold flex items-center justify-center disabled:bg-slate-300 disabled:pointer-events-none" > {isAdding ? ( <CgSpinnerTwo className="animate-spin text-xl" /> ) : ( <span>ADD</span> )} </button> <div className="flex-1"></div> <div className="flex items-center py-4 justify-center space-x-2"> <button onClick={closeForm} type="button" className="flex items-center justify-center h-10 px-4 bg-slate-100 hover:bg-slate-200 active:bg-slate-300 rounded-xl text-gray-800 font-bold uppercase" > <FaChevronLeft /> <span className="ml-2">Back to search</span> </button> <button onClick={closeModal} type="button" className="flex items-center justify-center h-10 px-4 bg-slate-100 hover:bg-slate-200 active:bg-slate-300 rounded-xl text-gray-800 font-bold uppercase" > cancel </button> </div> </form> </motion.div> ); }; function formatFloat(n: number): number { return parseFloat(n.toFixed(1)); }
<script setup lang="ts"> import { TrashIcon, XMarkIcon } from "@heroicons/vue/24/outline"; import { vOnClickOutside } from "@vueuse/components"; import { onKeyStroke } from "@vueuse/core"; import { defineProps } from "vue"; import ButtonComponent from "../Button/ButtonComponent.vue"; import "./DeleteModal.scss"; const props = defineProps({ id: { type: [String, Number], required: true, }, showModal: { type: Boolean, default: false, required: true, }, deleteFunction: { type: Function, required: true, }, closeModal: { type: Function, required: true, }, }); const handleDelete = () => { props.deleteFunction(props.id); props.closeModal(); }; onKeyStroke("Escape", () => { if (props.showModal) { props.closeModal(); } }); </script> <template> <div v-if="props.showModal" class="modal"> <div class="modal__content" v-on-click-outside="props.closeModal as any"> <div class="modal__content__header"> <h2>Delete Note</h2> <p>Are you sure you want to delete this note?</p> </div> <div class="modal__content__body"> <ButtonComponent variant="primary" @click="$props.closeModal"> <XMarkIcon /> Cancel </ButtonComponent> <ButtonComponent variant="danger" @click="handleDelete"> <TrashIcon /> Delete </ButtonComponent> </div> </div> </div> </template> <style scoped></style>
# Update DNS server configuration on RHEL ## Add DNS A Records To update the DNS server configuration on RHEL (Red Hat Enterprise Linux) and add new A records, you can follow these general steps: 1. Log in to your RHEL server with administrative privileges (such as the root user or a user with sudo access). 2. Determine which DNS server software you are using. RHEL typically uses BIND (Berkeley Internet Name Domain) as the default DNS server. However, there are alternative DNS server options like dnsmasq or PowerDNS. The specific steps may vary slightly depending on the DNS server software you have installed. 3. Locate the configuration file for your DNS server. For BIND, the configuration file is typically located at `/etc/named.conf`. For dnsmasq, it is `/etc/dnsmasq.conf`. 4. Open the configuration file using a text editor. For example, you can use the `vi` editor by running the following command: ```sh sudo vi /etc/named.conf ``` 5. Within the configuration file, find the zone section that corresponds to the domain for which you want to add A records. The zone section typically begins with a line similar to: ``` zone "example.com" IN { ``` 6. Inside the zone section, locate the resource or record directive. This directive is used to define A records. It might look like this: ``` example.com. IN A 192.168.1.100 ``` 7. Add a new line for each A record you want to add. The format is typically: ``` hostname IN A IP_address ``` Replace `hostname` with the desired host or subdomain name and `IP_address` with the corresponding IP address. 8. Save the changes and exit the text editor. 9. Restart the DNS server to apply the new configuration. The command to restart the DNS server will depend on the software you are using. For BIND, you can use the following command: ```sh sudo systemctl restart named ``` If you are using dnsmasq, the command would be: ```sh sudo systemctl restart dnsmasq ``` 10. Verify that the A records have been added successfully by using a DNS lookup tool like `nslookup` or `dig`. For example, you can run: ```sh nslookup hostname.example.com ``` Replace hostname.example.com with the specific hostname or subdomain you added. That's it! You have now updated the DNS server configuration on RHEL to add new A records. Remember to adjust the steps if you are using a different DNS server software. ## Create new DNS zone If you want to create a brand new zone in your /etc/named.conf file on RHEL, follow these steps: 1. Open the /etc/named.conf file using a text editor with administrative privileges. For example: ```sh sudo vi /etc/named.conf ``` 2. Inside the file, locate the `options` section. This section contains global configuration options for the BIND DNS server. 3. Within the `options` section, add a new zone definition by using the following syntax: ``` zone "example.com" { type master; file "/var/named/example.com.zone"; }; ``` Replace `example.com` with the name of your desired domain or subdomain. Modify the `file` directive to specify the path and filename where you want to store the zone file. In this example, the zone file will be stored at `/var/named/example.com.zone`. 4. Save the changes and exit the text editor. 5. Create the zone file at the specified location (`/var/named/example.com.zone` in the example above). The zone file contains the DNS records for the zone you created. You can use a text editor to create and edit the zone file. Here's an example of a basic zone file for reference: ``` $TTL 86400 @ IN SOA ns1.example.com. admin.example.com. ( 2023060101 ; Serial number 3600 ; Refresh 1800 ; Retry 604800 ; Expire 86400 ; Minimum TTL ) @ IN NS ns1.example.com. @ IN NS ns2.example.com. ns1 IN A 192.168.1.10 ns2 IN A 192.168.1.11 ``` Modify the records according to your specific requirements, including the SOA (Start of Authority) record, NS (Name Server) records, and A (Address) records. 6. Save the zone file. 7. Restart the BIND DNS server to apply the changes: ```sh sudo systemctl restart named ``` 8. Verify that the new zone is functioning correctly by performing DNS lookups or using DNS testing tools. That's it! You have now created a new zone in your `/etc/named.conf` file on RHEL and defined the corresponding zone file.
import clsx from "clsx"; import type { ButtonHTMLAttributes, DetailedHTMLProps, ReactNode } from "react"; import React, { forwardRef } from "react"; import { Loader } from "./Loader"; export type ButtonVariants = "primary" | "secondary" | "danger" | "material"; interface Props extends DetailedHTMLProps< ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement > { size?: "sm" | "md" | "lg" | "xl"; variant?: ButtonVariants; loading?: boolean; children?: ReactNode; icon?: ReactNode; className?: string; } export const Button = forwardRef<HTMLButtonElement, Props>(function Button( { className = "", size = "md", variant = "primary", loading, children, icon, ...rest }, ref ) { return ( <button ref={ref} className={clsx( "relative inline-block disabled:opacity-50 rounded-lg md:rounded-xl group", { "px-4 py-1.5 text-xs": size === "sm", "px-5 md:py-2 py-1.5 text-sm": size === "md", "px-6 py-3 text-base": size === "lg", "px-8 py-4 text-lg": size === "xl", }, className )} disabled={loading} {...rest} > <span className={clsx( "absolute focus:outline-none inset-0 w-full h-full transition duration-200 ease-in-out transform rounded-md md:rounded-md", { "border border-sky-500": variant === "primary", "bg-transparent": variant === "secondary", "bg-opacity-25 dark:group-hover:bg-indigo-900 group-hover:bg-indigo-100 !transition-none": variant === "material", "border-red-500 border": variant === "danger", "group-hover:translate-x-0.5 group-hover:translate-y-0.5": !rest.disabled && variant !== "material", } )} /> <span className={clsx("absolute inset-0 w-full h-full rounded-md", { "bg-sky-500 border border-sky-500 md:rounded-md": variant === "primary", "bg-transparent md:rounded-md": variant === "secondary", "bg-red-500 border border-red-500 md:rounded-md": variant === "danger", "md:rounded-md": size === "sm", })} /> <span className={clsx("relative flex items-center justify-center space-x-2", { "text-white": variant !== "secondary" && variant !== "material", })} > {icon} {loading && <Loader size="sm" />} <span className={clsx("whitespace-nowrap", { "font-medium": variant !== "secondary", })} > {children} </span> </span> </button> ); });
<?php if ( ! defined( 'ABSPATH' ) ) { exit; } /** * WC_Stripe_Customer class. * * Represents a Stripe Customer. */ class WC_Stripe_Customer { /** * Stripe customer ID * @var string */ private $id = ''; /** * WP User ID * @var integer */ private $user_id = 0; /** * Data from API * @var array */ private $customer_data = array(); /** * Constructor * @param int $user_id The WP user ID */ public function __construct( $user_id = 0 ) { if ( $user_id ) { $this->set_user_id( $user_id ); $this->set_id( $this->get_id_from_meta( $user_id ) ); } } /** * Get Stripe customer ID. * @return string */ public function get_id() { return $this->id; } /** * Set Stripe customer ID. * @param [type] $id [description] */ public function set_id( $id ) { // Backwards compat for customer ID stored in array format. (Pre 3.0) if ( is_array( $id ) && isset( $id['customer_id'] ) ) { $id = $id['customer_id']; $this->update_id_in_meta( $id ); } $this->id = wc_clean( $id ); } /** * User ID in WordPress. * @return int */ public function get_user_id() { return absint( $this->user_id ); } /** * Set User ID used by WordPress. * @param int $user_id */ public function set_user_id( $user_id ) { $this->user_id = absint( $user_id ); } /** * Get user object. * @return WP_User */ protected function get_user() { return $this->get_user_id() ? get_user_by( 'id', $this->get_user_id() ) : false; } /** * Store data from the Stripe API about this customer */ public function set_customer_data( $data ) { $this->customer_data = $data; } /** * Generates the customer request, used for both creating and updating customers. * * @param array $args Additional arguments (optional). * @return array */ protected function generate_customer_request( $args = array() ) { $billing_email = isset( $_POST['billing_email'] ) ? filter_var( $_POST['billing_email'], FILTER_SANITIZE_EMAIL ) : ''; $user = $this->get_user(); if ( $user ) { $billing_first_name = get_user_meta( $user->ID, 'billing_first_name', true ); $billing_last_name = get_user_meta( $user->ID, 'billing_last_name', true ); // If billing first name does not exists try the user first name. if ( empty( $billing_first_name ) ) { $billing_first_name = get_user_meta( $user->ID, 'first_name', true ); } // If billing last name does not exists try the user last name. if ( empty( $billing_last_name ) ) { $billing_last_name = get_user_meta( $user->ID, 'last_name', true ); } // translators: %1$s First name, %2$s Second name, %3$s Username. $description = sprintf( __( 'Name: %1$s %2$s, Username: %s', 'woocommerce-gateway-stripe' ), $billing_first_name, $billing_last_name, $user->user_login ); $defaults = array( 'email' => $user->user_email, 'description' => $description, ); } else { $billing_first_name = isset( $_POST['billing_first_name'] ) ? filter_var( wp_unslash( $_POST['billing_first_name'] ), FILTER_SANITIZE_STRING ) : ''; // phpcs:ignore WordPress.Security.NonceVerification $billing_last_name = isset( $_POST['billing_last_name'] ) ? filter_var( wp_unslash( $_POST['billing_last_name'] ), FILTER_SANITIZE_STRING ) : ''; // phpcs:ignore WordPress.Security.NonceVerification // translators: %1$s First name, %2$s Second name. $description = sprintf( __( 'Name: %1$s %2$s, Guest', 'woocommerce-gateway-stripe' ), $billing_first_name, $billing_last_name ); $defaults = array( 'email' => $billing_email, 'description' => $description, ); } $metadata = array(); $defaults['metadata'] = apply_filters( 'wc_stripe_customer_metadata', $metadata, $user ); return wp_parse_args( $args, $defaults ); } /** * Create a customer via API. * @param array $args * @return WP_Error|int */ public function create_customer( $args = array() ) { $args = $this->generate_customer_request( $args ); $response = WC_Stripe_API::request( apply_filters( 'wc_stripe_create_customer_args', $args ), 'customers' ); if ( ! empty( $response->error ) ) { throw new WC_Stripe_Exception( print_r( $response, true ), $response->error->message ); } $this->set_id( $response->id ); $this->clear_cache(); $this->set_customer_data( $response ); if ( $this->get_user_id() ) { $this->update_id_in_meta( $response->id ); } do_action( 'woocommerce_stripe_add_customer', $args, $response ); return $response->id; } /** * Updates the Stripe customer through the API. * * @param array $args Additional arguments for the request (optional). */ public function update_customer( $args = array() ) { if ( empty( $this->get_id() ) ) { throw new WC_Stripe_Exception( 'id_required_to_update_user', __( 'Attempting to update a Stripe customer without a customer ID.', 'woocommerce-gateway-stripe' ) ); } $args = $this->generate_customer_request( $args ); $args = apply_filters( 'wc_stripe_update_customer_args', $args ); $response = WC_Stripe_API::request( $args, 'customers/' . $this->get_id() ); if ( ! empty( $response->error ) ) { if ( $this->is_no_such_customer_error( $response->error ) ) { $message = $response->error->message; if ( ! preg_match( '/similar object exists/i', $message ) ) { $options = get_option( 'woocommerce_stripe_settings' ); $testmode = isset( $options['testmode'] ) && 'yes' === $options['testmode']; $message = sprintf( ( $testmode // Translators: %s is a message, which states that no such customer exists, without a full stop at the end. ? __( '%s. Was the customer created in live mode? ', 'woocommerce-gateway-stripe' ) // Translators: %s is a message, which states that no such customer exists, without a full stop at the end. : __( '%s. Was the customer created in test mode? ', 'woocommerce-gateway-stripe' ) ), $message ); } throw new WC_Stripe_Exception( print_r( $response, true ), $message ); } throw new WC_Stripe_Exception( print_r( $response, true ), $response->error->message ); } $this->clear_cache(); $this->set_customer_data( $response ); do_action( 'woocommerce_stripe_update_customer', $args, $response ); } /** * Checks to see if error is of invalid request * error and it is no such customer. * * @since 4.1.2 * @param array $error */ public function is_no_such_customer_error( $error ) { return ( $error && 'invalid_request_error' === $error->type && preg_match( '/No such customer/i', $error->message ) ); } /** * Add a source for this stripe customer. * @param string $source_id * @return WP_Error|int */ public function add_source( $source_id ) { if ( ! $this->get_id() ) { $this->set_id( $this->create_customer() ); } $response = WC_Stripe_API::request( array( 'source' => $source_id, ), 'customers/' . $this->get_id() . '/sources' ); $wc_token = false; if ( ! empty( $response->error ) ) { // It is possible the WC user once was linked to a customer on Stripe // but no longer exists. Instead of failing, lets try to create a // new customer. if ( $this->is_no_such_customer_error( $response->error ) ) { $this->delete_id_from_meta(); $this->create_customer(); return $this->add_source( $source_id ); } else { return $response; } } elseif ( empty( $response->id ) ) { return new WP_Error( 'error', __( 'Unable to add payment source.', 'woocommerce-gateway-stripe' ) ); } // Add token to WooCommerce. if ( $this->get_user_id() && class_exists( 'WC_Payment_Token_CC' ) ) { if ( ! empty( $response->type ) ) { switch ( $response->type ) { case 'alipay': break; case 'sepa_debit': $wc_token = new WC_Payment_Token_SEPA(); $wc_token->set_token( $response->id ); $wc_token->set_gateway_id( 'stripe_sepa' ); $wc_token->set_last4( $response->sepa_debit->last4 ); break; default: if ( 'source' === $response->object && 'card' === $response->type ) { $wc_token = new WC_Payment_Token_CC(); $wc_token->set_token( $response->id ); $wc_token->set_gateway_id( 'stripe' ); $wc_token->set_card_type( strtolower( $response->card->brand ) ); $wc_token->set_last4( $response->card->last4 ); $wc_token->set_expiry_month( $response->card->exp_month ); $wc_token->set_expiry_year( $response->card->exp_year ); } break; } } else { // Legacy. $wc_token = new WC_Payment_Token_CC(); $wc_token->set_token( $response->id ); $wc_token->set_gateway_id( 'stripe' ); $wc_token->set_card_type( strtolower( $response->brand ) ); $wc_token->set_last4( $response->last4 ); $wc_token->set_expiry_month( $response->exp_month ); $wc_token->set_expiry_year( $response->exp_year ); } $wc_token->set_user_id( $this->get_user_id() ); $wc_token->save(); } $this->clear_cache(); do_action( 'woocommerce_stripe_add_source', $this->get_id(), $wc_token, $response, $source_id ); return $response->id; } /** * Get a customers saved sources using their Stripe ID. * * @param string $customer_id * @return array */ public function get_sources() { if ( ! $this->get_id() ) { return array(); } $sources = get_transient( 'stripe_sources_' . $this->get_id() ); $response = WC_Stripe_API::request( array( 'limit' => 100, ), 'customers/' . $this->get_id() . '/sources', 'GET' ); if ( ! empty( $response->error ) ) { return array(); } if ( is_array( $response->data ) ) { $sources = $response->data; } return empty( $sources ) ? array() : $sources; } /** * Delete a source from stripe. * @param string $source_id */ public function delete_source( $source_id ) { if ( ! $this->get_id() ) { return false; } $response = WC_Stripe_API::request( array(), 'customers/' . $this->get_id() . '/sources/' . sanitize_text_field( $source_id ), 'DELETE' ); $this->clear_cache(); if ( empty( $response->error ) ) { do_action( 'wc_stripe_delete_source', $this->get_id(), $response ); return true; } return false; } /** * Set default source in Stripe * @param string $source_id */ public function set_default_source( $source_id ) { $response = WC_Stripe_API::request( array( 'default_source' => sanitize_text_field( $source_id ), ), 'customers/' . $this->get_id(), 'POST' ); $this->clear_cache(); if ( empty( $response->error ) ) { do_action( 'wc_stripe_set_default_source', $this->get_id(), $response ); return true; } return false; } /** * Deletes caches for this users cards. */ public function clear_cache() { delete_transient( 'stripe_sources_' . $this->get_id() ); delete_transient( 'stripe_customer_' . $this->get_id() ); $this->customer_data = array(); } /** * Retrieves the Stripe Customer ID from the user meta. * * @param int $user_id The ID of the WordPress user. * @return string|bool Either the Stripe ID or false. */ public function get_id_from_meta( $user_id ) { return get_user_option( '_stripe_customer_id', $user_id ); } /** * Updates the current user with the right Stripe ID in the meta table. * * @param string $id The Stripe customer ID. */ public function update_id_in_meta( $id ) { update_user_option( $this->get_user_id(), '_stripe_customer_id', $id, false ); } /** * Deletes the user ID from the meta table with the right key. */ public function delete_id_from_meta() { delete_user_option( $this->get_user_id(), '_stripe_customer_id', false ); } }
import { fireEvent, render, screen } from "@testing-library/react"; import { App } from "./App"; const getButtonElementByText = (text: string) => screen.getByRole("button", { name: text }); describe("5種類の商品購入ボタン", () => { describe("コーヒー 480 円 のボタン", () => { it("ボタンが表示される", () => { render(<App />); expect(getButtonElementByText("コーヒー 480 円")).toBeInTheDocument(); }); it("注文回数の初期値が0回であること", () => { render(<App />); expect(screen.getByTestId("coffee-count")).toHaveTextContent("0"); }); it("ボタンをクリックすると注文回数のカウントが1回増加する", () => { render(<App />); expect(screen.getByTestId("coffee-count")).toHaveTextContent("0"); fireEvent.click(getButtonElementByText("コーヒー 480 円")); expect(screen.getByTestId("coffee-count")).toHaveTextContent("1"); }); }); describe("紅茶 280 円 のボタン", () => { it("ボタンが表示される", () => { render(<App />); expect(getButtonElementByText("紅茶 280 円")).toBeInTheDocument(); }); it("注文回数の初期値が0回であること", () => { render(<App />); expect(screen.getByTestId("tea-count")).toHaveTextContent("0"); }); it("ボタンをクリックすると注文回数のカウントが1回増加する", () => { render(<App />); expect(screen.getByTestId("tea-count")).toHaveTextContent("0"); fireEvent.click(getButtonElementByText("紅茶 280 円")); expect(screen.getByTestId("tea-count")).toHaveTextContent("1"); }); }); describe("ミルク 180 円 のボタン", () => { it("ボタンが表示される", () => { render(<App />); expect(getButtonElementByText("ミルク 180 円")).toBeInTheDocument(); }); it("注文回数の初期値が0回であること", () => { render(<App />); expect(screen.getByTestId("milk-count")).toHaveTextContent("0"); }); it("ボタンをクリックすると注文回数のカウントが1回増加する", () => { render(<App />); expect(screen.getByTestId("milk-count")).toHaveTextContent("0"); fireEvent.click(getButtonElementByText("ミルク 180 円")); expect(screen.getByTestId("milk-count")).toHaveTextContent("1"); }); }); describe("コーラ 190 円 のボタン", () => { it("ボタンが表示される", () => { render(<App />); expect(getButtonElementByText("コーラ 190 円")).toBeInTheDocument(); }); it("注文回数の初期値が0回であること", () => { render(<App />); expect(screen.getByTestId("coke-count")).toHaveTextContent("0"); }); it("ボタンをクリックすると注文回数のカウントが1回増加する", () => { render(<App />); expect(screen.getByTestId("coke-count")).toHaveTextContent("0"); fireEvent.click(getButtonElementByText("コーラ 190 円")); expect(screen.getByTestId("coke-count")).toHaveTextContent("1"); }); }); describe("ビール 580 円 のボタン", () => { it("ボタンが表示される", () => { render(<App />); expect(getButtonElementByText("ビール 580 円")).toBeInTheDocument(); }); it("注文回数の初期値が0回であること", () => { render(<App />); expect(screen.getByTestId("beer-count")).toHaveTextContent("0"); }); it("ボタンをクリックすると注文回数のカウントが1回増加する", () => { render(<App />); expect(screen.getByTestId("beer-count")).toHaveTextContent("0"); fireEvent.click(getButtonElementByText("ビール 580 円")); expect(screen.getByTestId("beer-count")).toHaveTextContent("1"); }); }); it("ボタンをクリックすると対象商品の注文回数のカウントのみが1回増加する", () => { render(<App />); // 対象商品 expect(screen.getByTestId("coffee-count")).toHaveTextContent("0"); // それ以外 expect(screen.getByTestId("milk-count")).toHaveTextContent("0"); expect(screen.getByTestId("tea-count")).toHaveTextContent("0"); expect(screen.getByTestId("coke-count")).toHaveTextContent("0"); expect(screen.getByTestId("beer-count")).toHaveTextContent("0"); fireEvent.click(getButtonElementByText("コーヒー 480 円")); // 対象商品 expect(screen.getByTestId("coffee-count")).toHaveTextContent("1"); // それ以外 expect(screen.getByTestId("milk-count")).toHaveTextContent("0"); expect(screen.getByTestId("tea-count")).toHaveTextContent("0"); expect(screen.getByTestId("coke-count")).toHaveTextContent("0"); expect(screen.getByTestId("beer-count")).toHaveTextContent("0"); }); });
#ifndef TACHYON_BASE_BUFFER_VECTOR_BUFFER_H_ #define TACHYON_BASE_BUFFER_VECTOR_BUFFER_H_ #include <utility> #include <vector> #include "tachyon/base/buffer/buffer.h" namespace tachyon::base { template <typename T> class VectorBuffer : public Buffer { public: static_assert(sizeof(T) == 1); VectorBuffer() = default; explicit VectorBuffer(const std::vector<T>& owned_buffer) : owned_buffer_(owned_buffer) { UpdateBuffer(); } explicit VectorBuffer(std::vector<T>&& owned_buffer) : owned_buffer_(std::move(owned_buffer)) { UpdateBuffer(); } VectorBuffer(const VectorBuffer& other) = delete; VectorBuffer& operator=(const VectorBuffer& other) = delete; VectorBuffer(VectorBuffer&& other) : Buffer(std::move(other)), owned_buffer_(std::move(other.owned_buffer_)) {} VectorBuffer& operator=(VectorBuffer&& other) { Buffer::operator=(std::move(other)); owned_buffer_ = std::move(other.owned_buffer_); return *this; } ~VectorBuffer() override = default; const std::vector<T>& owned_buffer() const { return owned_buffer_; } std::vector<T>&& TakeOwnedBuffer() && { return std::move(owned_buffer_); } [[nodiscard]] bool Grow(size_t size) override { owned_buffer_.resize(size); UpdateBuffer(); return true; } protected: void UpdateBuffer() { buffer_ = owned_buffer_.data(); buffer_len_ = owned_buffer_.size(); } std::vector<T> owned_buffer_; }; using CharVectorBuffer = VectorBuffer<char>; using Uint8VectorBuffer = VectorBuffer<uint8_t>; extern template class TACHYON_EXPORT VectorBuffer<char>; extern template class TACHYON_EXPORT VectorBuffer<uint8_t>; } // namespace tachyon::base #endif // TACHYON_BASE_BUFFER_VECTOR_BUFFER_H_
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Laravel\Sanctum\HasApiTokens; use Tymon\JWTAuth\Contracts\JWTSubject; class users extends Authenticatable implements JWTSubject { use HasApiTokens, HasFactory, Notifiable; /** * The attributes that are mass assignable. * * @var array<int, string> */ protected $fillable = [ 'username', 'fullname', 'email', 'phone', 'address', 'password', 'birthday', 'role', 'remember_token', 'token', ]; /** * The attributes that should be hidden for serialization. * * @var array<int, string> */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast. * * @var array<string, string> */ protected $casts = [ 'email_verified_at' => 'datetime', ]; public function getJWTIdentifier() { return $this->getKey(); } /** * Return a key value array, containing any custom claims to be added to the JWT. * * @return array */ public function getJWTCustomClaims() { return []; } protected $table = 'users'; protected $primaryKey = 'id'; public function ratings() { return $this->hasMany('App\Models\ratings', 'user_id')->onDelete('cascade'); } public function contract() { return $this->hasMany('App\Models\contracts', 'user_id')->onDelete('cascade'); } public function apartment() { return $this->hasMany('App\Models\apartments', 'user_id')->onDelete('cascade'); } public function book_apartment() { return $this->hasMany('App\Models\book_apartments', 'user_id')->onDelete('cascade'); } public function appointment() { return $this->hasMany('App\Models\appointments', 'user_id')->onDelete('cascade'); } public function apartmentIssue() { return $this->hasMany('App\Models\apartmentIssue', 'user_id')->onDelete('cascade'); } }
import numbers from copy import deepcopy import numpy as np import qutip as qt from qutip.cy.spconvert import arr_coo2fast, cy_index_permute from qutip.permute import _permute # To support the _permute2 function class NQobj(qt.Qobj): """ The NQobj (Named Qobj) class is an extension of the QuTip's Qobj class. It is designed to enable the use of symbolic names to represent and index modes in a quantum object, as opposed to using numerical indices. One of the primary motivations behind the NQobj is to facilitate mathematical operations (+, -, *) between different NQobj instances by automatically matching modes based on their symbolic names. This is particularly useful when working with multi-partite quantum systems where the tensor structure can be complex. In addition to the standard attributes and methods inherited from the Qobj class, NQobj introduces an additional attribute, `names`, which is structured similarly to the `dims` attribute of Qobj. The `names` attribute is a list that provides symbolic names to each mode, making it easier to identify and operate on specific modes. Parameters ---------- The NQobj takes the arguments and kwarg of QuTiP Qobj, and names. names: str, list of str or list of two lists of str if names is str : names = "A" -> names = [["A"], ["A"]] if names is list of str : names = ["A", "B"] -> names = [["A", "B"], ["A", "B"]] if names is list of two list of str : names = names names for the modes: the shape has to match dims after the above correction. Attributes ---------- Same as for QuTiP Qobj, including: names: List of the names of dimensions for keeping track of the tensor structure. """ def __init__(self, *args, **kwargs): """ NQobj constructor. Parameters: - args: Arguments for the parent Qobj class - kwargs: Keyword arguments for the parent Qobj class, and additional `names` and `kind` arguments for NQobj """ # Extract names and kind from kwargs, if present names = kwargs.pop("names", None) kind = kwargs.pop("kind", None) # If a NQobj is supplied as input and no new names are given, use the existing ones. try: if isinstance(args[0], NQobj) and names is None: names = (args[0]).names except IndexError: pass # Initialize the Qobj without the names. super().__init__(*args, **kwargs) # Check and validate the format of names, then add them as an attribute to the instance. if names is None: raise AttributeError("names is a compulsary attribute.") # Handle cases where names is a list if isinstance(names, list): # Ensure proper structure for the 2D list format if len(names) == 2 and isinstance(names[0], list) and isinstance(names[1], list): # Check if all names are strings and unique if not all(isinstance(i, str) for i in names[0] + names[1]): raise ValueError("A name must be a string.") if len(names[0]) != len(set(names[0])) or len(names[1]) != len(set(names[1])): raise ValueError("Do not use duplicate names.") if (len(names[0]), len(names[1])) != self.shape_dims: raise ValueError("The number of names must match the shape_dims.") self.names = names else: # Ensure all names are strings and unique for 1D list format if not all(isinstance(i, str) for i in names): raise ValueError("A name must be a string.") if len(names) != len(set(names)): raise ValueError("Do not use duplicate names.") if not (len(names) == self.shape_dims[0] and len(names) == self.shape_dims[1]): raise ValueError("The number of names must match the shape_dims.") self.names = [names, names] # Handle case where names is a string elif isinstance(names, str): if self.shape_dims != (1, 1): raise ValueError("Names can only be a string if there shape_dims is (1, 1).") self.names = [[names], [names]] else: raise TypeError("names should be a string or 1d or 2d list ") # Assign the type of NQobj (operator or state) if kind in ("oper", "state"): self.kind = kind elif kind is None: # If kind is not give, try to extract it from the Qobj form if self.isket or self.isbra: self.kind = "state" if self.isoper: if ( set(self.names[0]) == set(self.names[1]) and sorted(self.dims[0]) == sorted(self.dims[1]) and self.isherm ): raise ValueError( 'The kind cannot be determined automatically and should be provedid as kw ("oper" or "state")' ) self.kind = "oper" else: raise ValueError('kind can only be "oper", "state", None') def copy(self): """Create an identical copy of the NQobj.""" q = super().copy() return NQobj(q, names=deepcopy(self.names), kind=self.kind) def __add__(self, other): """ Define addition for the NQobj when it's on the left side (e.g., Qobj + 4). """ # Check if the other operand is also an NQobj if isinstance(other, NQobj): # Ensure the types and kinds of both NQobj are the same for addition if not self.type == other.type: raise ValueError("Addition and substraction are only allowed for two NQobj of the same type.") if not self.kind == other.kind: raise ValueError("Addition and substraction are only allowed for two NQobj of the same kind.") # Handle specific cases where the NQobj is a ket, bra, or operator if self.isket or self.isbra or self.isoper: names = _add_find_required_names(self, other) if not names == self.names or not names == other.names: missing_self = _find_missing_names(self.names, names) missing_other = _find_missing_names(other.names, names) missing_dict_self = _find_missing_dict(missing_self, other, transpose=False) missing_dict_other = _find_missing_dict(missing_other, self, transpose=False) self = _adding_missing_modes(self, missing_dict_self, kind=self.kind) self = self.permute(names) other = _adding_missing_modes(other, missing_dict_other, kind=other.kind) other = other.permute(names) Qobj_result = super(NQobj, self).__add__(other) return NQobj(Qobj_result, names=names, kind=self.kind) else: raise NotImplementedError else: raise NotImplementedError def __mul__(self, other): """ Define multiplication for the NQobj when it's on the left side (e.g., NQobj * 4). """ # Check if the other operand is also an NQobj if isinstance(other, NQobj): # Identify the required names for multiplication and find any missing names in both NQobjs names_self, names_other = _mul_find_required_names(self, other) if not names_self == self.names or not names_other == other.names: # Find missing names and prepare for multiplication missing_self = _find_missing_names(self.names, names_self) missing_other = _find_missing_names(other.names, names_other) missing_dict_self = _find_missing_dict(missing_self, other, transpose=True) missing_dict_other = _find_missing_dict(missing_other, self, transpose=True) self = _adding_missing_modes(self, missing_dict_self, kind=self.kind) self = self.permute(names_self) other = _adding_missing_modes(other, missing_dict_other, kind=other.kind) other = other.permute(names_other) # Perform the multiplication operation Qobj_result = super(NQobj, self).__mul__(other) # Handle special case where the result is a scalar (Return a scalar as Qobj and not as NQobj). if Qobj_result.shape == (1, 1): return qt.Qobj(Qobj_result) else: names = [names_self[0], names_other[1]] # Modes with size (1, 1) are reduced to scalars and don't need names for name in names[0].copy(): if self._dim_of_name(name)[0] == 1 and other._dim_of_name(name)[1] == 1: names[0].remove(name) names[1].remove(name) # Determine the kind of the result based on the kinds of the operands if self.kind == "oper" and other.kind == "oper": kind = "oper" elif self.kind == "state" and other.kind == "state": kind = "oper" else: kind = "state" return NQobj(Qobj_result, names=names, kind=kind) # Handle multiplication with a number elif isinstance(other, numbers.Number): return NQobj(super().__mul__(other), names=self.names, kind=self.kind) # Handle multiplication with a plain Qobj elif isinstance(other, qt.Qobj): return super().__mul__(other) else: raise NotImplementedError def __rmul__(self, other): """ Define multiplication for the NQobj when it's on the right side (e.g., 4 * NQobj). """ # Handle multiplication with a number if isinstance(other, numbers.Number): # Use the multiplication method defined for NQobj return self.__mul__(other) # Handle multiplication with a plain Qobj elif isinstance(other, qt.Qobj): # Perform multiplication from the perspective of the Qobj, putting NQobj on the right return other.__mul__(self) def __div__(self, other): """ Division operation, intended for division by numbers only. Returns a new NQobj with the result of the division. """ return NQobj(super().__div__(other), names=self.names, kind=self.kind) def __neg__(self): """ Negation operation. Returns a new NQobj with the negated values. """ return NQobj(super().__neg__(), names=self.names, kind=self.kind) def __eq__(self, other): """ Equality operator to compare two NQobj instances. Compares both the Qobj content and the names attribute. """ same_Qobj = super().__eq__(other) same_names = self.names == other.names return same_Qobj and same_names def __pow__(self, n, m=None): """ Power operation for raising the NQobj to a certain power. Returns a new NQobj with the result. """ return NQobj(super().__pow__(n, m=m), names=self.names, kind=self.kind) def __str__(self): """ String representation of the NQobj. Appends the names and kind attributes to the Qobj's string representation. """ return super().__str__() + "\nnames: " + self.names.__str__() + "\nkind: " + self.kind.__str__() def _repr_latex_(self): """ Generate a LaTeX representation of the NQobj instance. Useful for formatted output in IPython notebooks. """ string = super()._repr_latex_() string += r" $\\$ " string += f"names = {self.names}" string += f", kind = {self.kind}" return string def dag(self): """ Returns the adjoint (dagger) of the NQobj. Also swaps the names of the ket and bra dimensions. """ out = super().dag() names = [self.names[1], self.names[0]] return NQobj(out, names=names, kind=self.kind) def proj(self): """ Form the projector from a given ket or bra vector of the NQobj. Returns a new NQobj that represents the projector. """ return NQobj(super().proj(), names=self.names, kind="oper") def unit(self, *args, **kwargs): """ Normalize the NQobj to unity, either as an operator or state. Returns a new NQobj that is normalized. """ return NQobj(super().unit(*args, **kwargs), names=self.names, kind=self.kind) def ptrace(self, sel, keep=True): if self.dims[0] != self.dims[1]: ValueError("ptrace works only on a square oper") if self.names[0] != self.names[1]: ValueError("Names of both axis are not the same") if isinstance(sel, list): if all(isinstance(i, int) for i in sel): pass elif all(isinstance(i, str) for i in sel): sel = [self.names[0].index(name) for name in sel] else: raise ValueError("sel must be list of only int or str") elif isinstance(sel, str): sel = [self.names[0].index(sel)] else: raise TypeError("sel needs to be a list with int or str") if not keep: sel = [i for i in range(self.shape_dims[0]) if not i in sel] names = [name for i, name in enumerate(self.names[0]) if i in sel] return NQobj(super().ptrace(sel), names=[names, names], kind=self.kind) def permute(self, order): if isinstance(order, list) and all(isinstance(i, str) for i in order): order_index = [] if self.names[0] == self.names[1]: for name in order: order_index.append(self.names[0].index(name)) order = order_index else: order = [order, order] if ( len(order) == 2 and all(isinstance(i, list) for i in order) and all(isinstance(i, str) for i in order[0] + order[1]) ): order_index = [[], []] for name in order[0]: order_index[0].append(self.names[0].index(name)) for name in order[1]: order_index[1].append(self.names[1].index(name)) order = order_index # Replicate working of permute of Qobj but with _permute2. q = qt.Qobj() q.data, q.dims = _permute2(self, order) q = q.tidyup() if qt.settings.auto_tidyup else q if isinstance(order, list) and all(isinstance(i, int) for i in order): order = [order, order] # Rearange the names names_0 = [self.names[0][i] for i in order[0]] names_1 = [self.names[1][i] for i in order[1]] names = [names_0, names_1] return NQobj(q, names=names, kind=self.kind) def rename(self, name, new_name): """Rename a mode called name to new_name.""" if name == new_name: pass elif new_name in self.names[0] + self.names[1]: raise ValueError("You cannot use a new_name which is already used.") elif name not in self.names[0] + self.names[1]: raise ValueError("The name you want to replace is not present in the NQobj.") else: for i in range(2): try: self.names[i][self.names[i].index(name)] = new_name except ValueError: pass def _dim_of_name(self, name): """Return the shape of the submatrix with name.""" try: index_0 = self.names[0].index(name) dim_0 = self.dims[0][index_0] except ValueError: dim_0 = None try: index_1 = self.names[1].index(name) dim_1 = self.dims[1][index_1] except ValueError: dim_1 = None return (dim_0, dim_1) def expm(self): if self.names[0] == self.names[1] and self.dims[0] == self.dims[1]: return NQobj(super().expm(), names=self.names, kind=self.kind) else: new_self = self.expand() new_self.permute([new_self.names[0], new_self.names[0]]) if new_self.names[0] == new_self.names[1] and new_self.dims[0] == new_self.dims[1]: return NQobj( super(NQobj, new_self).expm(), names=new_self.names, kind=new_self.kind, ) else: raise ValueError("For exponentiation the matrix should have square submatrixes.") @property def shape_dims(self): """ Compute and return the shape dimensions of the NQobj based on the dims attribute. Returns: - Tuple of integers representing the number of dimensions in the row (0th) and column (1st) direction. """ shape_dims_0 = len(self.dims[0]) shape_dims_1 = len(self.dims[1]) return (shape_dims_0, shape_dims_1) def trans(self): """ Compute the transpose of the NQobj. Returns: - A new NQobj which is the transpose of the current NQobj, with the names of bra and ket swapped. """ return NQobj(super().trans(), names=[self.names[1], self.names[0]], kind=self.kind) def expand(self): """ Expand the NQobj to include all modes present in both rows and columns. Returns: - A new NQobj which is expanded to include all modes. """ # If the names in rows and columns are the same, no expansion needed if self.names[0] == self.names[1]: return self # Copy the kind of the current NQobj kind = self.kind # Determine the set of all names required for expansion required_names = self.names[0] + self.names[1] required_names = list(dict.fromkeys(required_names)) # Remove duplicates while keeping order (Python 3.7+) # Identify which names are missing from the current NQobj missing = _find_missing_names(self.names, [required_names, required_names]) # Construct a dictionary of the missing names and their corresponding dimensions missing_dict = {name: self._dim_of_name(name) for name in missing[0] + missing[1]} # Deep copy the current names to avoid modifying the original names = deepcopy(self.names) # Iterate over the missing names and their dimensions for name, dims in missing_dict.items(): if dims[0] is None: names[0].append(name) self = qt.tensor(self, qt.basis(dims[1])) self.dims[1].pop() elif dims[1] is None: names[1].append(name) self = qt.tensor(self, qt.basis(dims[0]).dag()) self.dims[0].pop() # Return the expanded NQobj, permuted to have the required names in order return NQobj(self, names=names, kind=kind).permute(required_names) def tensor(*args): """Perform tensor product between multiple NQobj, similar to tensor from qutip.""" names = [[], []] for arg in args: names[0] += arg.names[0] names[1] += arg.names[1] q = qt.tensor(*args) kinds = np.array([q.kind for q in args]) if not np.all(kinds == kinds[0]): raise AttributeError("For tensor product the kind of all NQobj should be the same.") out = NQobj(q, names=names, kind=kinds[0]) return out def ket2dm(Q): return NQobj(qt.ket2dm(Q), names=Q.names, kind="state") def name(Q, names, kind=None): return NQobj(Q, names=names, kind=kind) def fidelity(A, B): if not ((A.isket or A.isbra or A.isoper) and (B.isket or B.isbra or B.isoper)): raise TypeError("fidelity can only be calculated for ket, bra or oper.") if not set(A.names[0]) == set(A.names[1]) or not set(B.names[0]) == set(B.names[1]): raise TypeError("Names of colums and rows need to be the same.") if not set(A.names[0]) == set(B.names[0]): raise TypeError("fidelity needs both objects to have the same names.") return qt.fidelity(A, B.permute(A.names)) def _permute2(Q, order): """ Similar function as _permute from qutip but this allows for permutation of non-square matrixes. In this case order needs to be a list of two list with the permutation for each axis. e.g. [[1,0], [1,2,0]] """ equal_dims = Q.dims[0] == Q.dims[1] if isinstance(order, list): if Q.isoper: if equal_dims and all(isinstance(i, int) for i in order): use_qutip = True elif ( len(order) == 2 and all(isinstance(i, list) for i in order) and all(isinstance(i, int) for i in order[0] + order[1]) ): use_qutip = False else: raise TypeError("Order should be a list of int or a list of two list with int.") elif Q.isbra or Q.isket: if all(isinstance(i, int) for i in order): use_qutip = True elif ( len(order) == 2 and all(isinstance(i, list) for i in order) and all(isinstance(i, int) for i in order[0] + order[1]) ): use_qutip = False else: use_qutip = True # Make sure that it works if [order, order] is supplied for a different object type then oper. if ( len(order) == 2 and all(isinstance(i, list) for i in order) and all(isinstance(i, int) for i in order[0] + order[1]) and order[0] == order[1] ): order = order[0] if use_qutip: return _permute(Q, order) else: # Copy the functionality from qutip but allow for different order for rows and collums. Qcoo = Q.data.tocoo() cy_index_permute( Qcoo.row, np.array(Q.dims[0], dtype=np.int32), np.array(order[0], dtype=np.int32), ) cy_index_permute( Qcoo.col, np.array(Q.dims[1], dtype=np.int32), np.array(order[1], dtype=np.int32), ) new_dims = [[Q.dims[0][i] for i in order[0]], [Q.dims[1][i] for i in order[1]]] return ( arr_coo2fast(Qcoo.data, Qcoo.row, Qcoo.col, Qcoo.shape[0], Qcoo.shape[1]), new_dims, ) ######################### Function to support __mul__ and __add__ functions ############################# def _mul_find_required_names(Q_left, Q_right): """ Identify the required mode names for multiplication between two NQobjs. """ # If a mode has the form of a ket in Q_left or a bra in Q_right they don't have to be matched between the objects # Identify modes in Q_left and Q_right that don't need to be matched for multiplication names_Q_right_for_overlap = [name for name in Q_right.names[0] if not Q_right._dim_of_name(name)[0] == 1] names_Q_left_for_overlap = [name for name in Q_left.names[1] if not Q_left._dim_of_name(name)[1] == 1] # Goal: to get a list with modes that need to appear in both objects to perform the multiplication, the overlap. # Determine the overlapping mode names between the two NQobjs based on their kinds if Q_right.kind == "state" and Q_left.kind == "oper": overlap = names_Q_right_for_overlap + names_Q_left_for_overlap else: overlap = names_Q_left_for_overlap + names_Q_right_for_overlap overlap = list(dict.fromkeys(overlap)) # Remove duplicates while keeping order (Python 3.7+) # Reorder mode names to match multiplication requirements names_Q_left = [overlap + names for names in Q_left.names] names_Q_left = [ list(dict.fromkeys(names)) for names in names_Q_left ] # Remove duplicates while keeping order (Python 3.7+) names_Q_right = [overlap + names for names in Q_right.names] names_Q_right = [ list(dict.fromkeys(names)) for names in names_Q_right ] # Remove duplicates while keeping order (Python 3.7+) return names_Q_left, names_Q_right def _add_find_required_names(Q_left, Q_right): """ Identify the required mode names for the addition of two NQobjs. """ names = [Q_left.names[i] + Q_right.names[i] for i in range(2)] names = [ list(dict.fromkeys(name_list)) for name_list in names ] # Remove duplicates while keeping order (Python 3.7+) return names def _find_missing_names(names, required_names): """ Determine which mode names are missing when comparing two lists of names """ missing = [list(set(required_names[i]) - set(names[i])) for i in range(2)] return missing def _find_missing_dict(missing_names, Q_other, transpose=False): """ Map the missing mode names to their corresponding dimensions in another NQobj. """ missing_dict = {} for name in set(missing_names[0] + missing_names[1]): dims = list(Q_other._dim_of_name(name)) if name not in missing_names[0]: dims[0] = None if name not in missing_names[1]: dims[1] = None if transpose: dims.reverse() missing_dict[name] = dims return missing_dict def _adding_missing_modes(Q, dict_missing_modes, kind="oper"): """ Add missing modes to an NQobj based on the missing modes dictionary. Parameters: - Q: The NQobj to which missing modes are added. - dict_missing_modes: A dictionary mapping missing mode names to their dimensions. - kind: Type of the NQobj ("oper" for operators or "state" for quantum states). Default is "oper". Returns: - The NQobj with missing modes added. """ modes = [] # List to collect modes that need to be added to the NQobj # Iterate through each missing mode and its dimensions for name, dims in dict_missing_modes.items(): # If the NQobj kind is an operator if kind == "oper": assert dims[0] == dims[1], "For adding eye matrixes they need to be square" modes.append(NQobj(qt.qeye(dims[0]), names=name, kind="oper")) # If the NQobj kind is a quantum state if kind == "state": if not None in dims: modes.append( NQobj( qt.basis(dims[0], 0) * qt.basis(dims[1], 0).dag(), names=name, kind="state", ) ) elif dims[0] is None: modes.append(NQobj(qt.basis(dims[1], 0).dag(), names=[[], [name]], kind="state")) elif dims[1] is None: modes.append(NQobj(qt.basis(dims[0], 0), names=name, kind="state")) # Return a tensor product of the original NQobj with the added modes return tensor(Q, *modes)
# encoding: utf-8 # Copyright (c) 2012-2014, Jungwacht Blauring Schweiz. This file is part of # hitobito and licensed under the Affero General Public License version 3 # or later. See the COPYING file at the top-level directory or at # https://github.com/hitobito/hitobito. class ApplicationController < ActionController::Base include DecoratesBeforeRendering include Userstamp include Translatable include Stampable include Localizable include Authenticatable include ERB::Util include Sentry # protect with null_session only in specific api controllers protect_from_forgery with: :exception helper_method :person_home_path before_action :set_no_cache before_action :set_paper_trail_whodunnit class_attribute :skip_translate_inheritable alias decorate __decorator_for__ if Rails.env.production? rescue_from CanCan::AccessDenied do |_exception| redirect_to root_path, alert: I18n.t('devise.failure.not_permitted_to_view_page') end rescue_from ActionController::UnknownFormat, ActionView::MissingTemplate, with: :not_found end def person_home_path(person, options = {}) group_person_path(person.default_group_id, person, options) end private def not_found raise ActionController::RoutingError, 'Not Found' end def set_no_cache response.headers['Cache-Control'] = 'no-cache, no-store, max-age=0, must-revalidate' response.headers['Pragma'] = 'no-cache' response.headers['Expires'] = 'Fri, 01 Jan 1990 00:00:00 GMT' end def html_request? request.formats.any? { |f| f.html? || f == Mime::ALL } end def user_for_paper_trail origin_user_id = session[:origin_user] origin_user_id ? origin_user_id : super end def current_ability @current_ability ||= if current_user Ability.new(current_user) else TokenAbility.new(current_service_token) end end def after_sign_in_path_for(resource) stored_location_for(resource) || root_path end end
import { NotAllowedError } from "@/core/errors/not-allowed-error"; import { EditUserUseCase } from "@/domain/account/application/use-cases/edit-user"; import { CurrentUser } from "@/infra/auth/current-user-decorator"; import { UserPayload } from "@/infra/auth/jwt.strategy"; import { BadRequestException, Body, Controller, HttpCode, Param, Put, UnauthorizedException, } from "@nestjs/common"; import { ApiBearerAuth, ApiTags } from "@nestjs/swagger"; import { EditUserBodyDto, editUserBodyPipe, } from "../../dtos/account/edit-user.dto"; @ApiTags("users") @ApiBearerAuth("token") @Controller({ path: "/users/:id", version: "v1" }) export class EditUserController { constructor(private editUser: EditUserUseCase) {} @Put() @HttpCode(204) async handle( @Body(editUserBodyPipe) body: EditUserBodyDto, @CurrentUser() user: UserPayload, @Param("id") userId: string, ) { const { name, cpf, role } = body; const result = await this.editUser.execute({ userId, name, cpf, role, administratorId: user.sub, }); if (result.isError()) { const error = result.value; switch (error.constructor) { case NotAllowedError: throw new UnauthorizedException(error.message); default: throw new BadRequestException(error.message); } } } }
/** * pauli_osg.h * * @copyright Copyright (c) 2023 Austrian Academy of Sciences * @author Andrew J. P. Garner */ #pragma once #include "dictionary/operator_sequence_generator.h" #include "scenarios/pauli/indices/nearest_neighbour_index.h" namespace Moment::Pauli { class PauliContext; /** * Generates operator sequences of up to a desired length for the Pauli scenario. * Can be constrained to only generate series whose operators are nearest neighbours, or N-nearest neighbours. */ class PauliSequenceGenerator : public OperatorSequenceGenerator { public: const PauliContext& pauli_context; /** * The index labelling this OSG (NPA level, and nearest neighbour filter). */ const NearestNeighbourIndex nearest_neighbour_index; public: /** * Generate all operators up to word length. */ PauliSequenceGenerator(const PauliContext& context, size_t word_length); /** * Generate only nearest neighbour operators up to word length. */ PauliSequenceGenerator(const PauliContext& context, const NearestNeighbourIndex& index); /** * Generate only nearest neighbour operators up to word length. */ PauliSequenceGenerator(const PauliContext& context, const size_t word_length, const size_t neighbours) : PauliSequenceGenerator{context, NearestNeighbourIndex{word_length, neighbours}} { } /** True, if only a limited subset of sequences are considered (i.e. nearest neighbour mode). */ [[nodiscard]] constexpr bool limited() const noexcept { return this->nearest_neighbour_index.neighbours != 0; } private: /** Calculates everything for OSG */ void compute_all_sequences(); /** Calculates nearest-neighbours for OSG */ void compute_nearest_neighbour_sequences(); /** Adds identity. */ void add_length_zero_sequence(); /** Adds all one-operator terms. */ void add_length_one_sequences(); }; }
<?php namespace App\Controller; use App\Entity\CartaAutorizacionInventario; use App\Entity\Inventario; use App\Entity\OrdenInventario; use App\Form\InventarioType; use App\Repository\InventarioRepository; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\HttpFoundation\Request; /** * @Route("/user/inventario") */ class InventarioController extends AbstractController { /** * @Route("/", name="inventario_index", methods={"GET"}) */ public function index(InventarioRepository $inventarioRepository): Response { if ($inventarioRepository->findAll() == null) { $flashBag = $this->get('session')->getFlashBag(); $flashBag->add('app_warning','No hay Inventarios almacenados en la Base de Datos!!!'); } return $this->render('inventario/index.html.twig', [ 'invent' => $inventarioRepository->findAll(), ]); } /** * @Route("/new", name="inventario_new", methods={"GET","POST"}) */ public function new(Request $request): Response { $invent = new Inventario(); $form = $this->createForm(InventarioType::class, $invent); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $ordeninventario = $form->get('ordeninventario')->getData(); foreach($ordeninventario as $orden){ $fichier = md5(uniqid()) . '.' . $orden->guessExtension(); $orden->move( $this->getParameter('ordeninventario_directory'), $fichier ); $ord = new OrdenInventario(); $ord->setLink($fichier); $invent->addOrdeninventario($ord); } $cartaautorizacioninventario = $form->get('cartaautorizacioninventario')->getData(); foreach($cartaautorizacioninventario as $cart){ $fichier = md5(uniqid()) . '.' . $cart->guessExtension(); $cart->move( $this->getParameter('cartaautorizacioninventario_directory'), $fichier ); $carta = new CartaAutorizacionInventario(); $carta->setLink($fichier); $invent->addCartaautorizacioninventario($carta); } $entityManager = $this->getDoctrine()->getManager(); $entityManager->persist($invent); $entityManager->flush(); $flashBag = $this->get('session')->getFlashBag(); $flashBag->add('app_success','Se ha creado un Inventario satisfactoriamente!!!'); $flashBag->add('app_success', sprintf('Inventario : %s', $invent->getCodInventario())); return $this->redirectToRoute('inventario_index'); } return $this->render('inventario/new.html.twig', [ 'invent' => $invent, 'form' => $form->createView(), ]); } /** * @Route("/{id}/edit", name="inventario_edit", methods={"GET","POST"}) */ public function edit(Request $request, Inventario $inventario): Response { $form = $this->createForm(InventarioType::class, $inventario); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $ordeninventario = $form->get('ordeninventario')->getData(); foreach($ordeninventario as $orden){ $fichier = md5(uniqid()) . '.' . $orden->guessExtension(); $orden->move( $this->getParameter('ordeninventario_directory'), $fichier ); $ord = new OrdenInventario(); $ord->setLink($fichier); $inventario->addOrdeninventario($ord); } $cartaautorizacioninventario = $form->get('cartaautorizacioninventario')->getData(); foreach($cartaautorizacioninventario as $cart){ $fichier = md5(uniqid()) . '.' . $cart->guessExtension(); $cart->move( $this->getParameter('cartaautorizacioninventario_directory'), $fichier ); $carta = new CartaAutorizacionInventario(); $carta->setLink($fichier); $inventario->addCartaautorizacioninventario($carta); } $this->getDoctrine()->getManager()->flush(); $flashBag = $this->get('session')->getFlashBag(); $flashBag->add('app_warning','Se ha actualizado un Inventario satisfactoriamente!!!'); $flashBag->add('app_warning', sprintf('Inventario : %s', $inventario->getCodInventario())); return $this->redirectToRoute('inventario_index'); } return $this->render('inventario/edit.html.twig', [ 'invent' => $inventario, 'form' => $form->createView(), ]); } /** * @Route("/{id}/show", name="inventario_show", methods={"GET"}) */ public function show($id): Response { $em = $this->getDoctrine()->getManager(); $entities = $em->getRepository('App:Inventario')->find($id); $form = $this->createForm(InventarioType::class, $entities); return $this->render('inventario/show.html.twig', array( 'entities' => $entities, 'form' => $form->createView() )); } /** * @Route("inventario/remove/{id}", name="removerinventario") */ public function remove(Request $request, $id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository(Inventario::class)->find($id); if (!$entity) { $flashBag = $this->get('session')->getFlashBag(); $flashBag->add('app_warning','No se encuentra este Inventario!!!'); } else { $em->remove($entity); $em->flush(); $flashBag = $this->get('session')->getFlashBag(); $flashBag->add('app_error','Se ha eliminado un Inventario satisfactoriamente!!!'); } return $this->redirectToRoute('inventario_index'); } /** * @Route("/eliminarordeninventario/{id}", name="objeto_delete_ordeninv", methods={"DELETE", "GET", "POST"}) */ public function deleteOrdenInventario(OrdenInventario $ordenInventario, Request $request){ $data = json_decode($request->getContent(), true); if($this->isCsrfTokenValid('delete'.$ordenInventario->getId(), $data['_token'])){ $nom = $ordenInventario->getLink(); unlink($this->getParameter('ordeninventario_directory').'/'.$nom); $em = $this->getDoctrine()->getManager(); $em->remove($ordenInventario); $em->flush(); return new JsonResponse(['success' => 1]); }else{ return new JsonResponse(['error' => 'Token Invalido'], 400); } } /** * @Route("/eliminarcartaautorizacioninventario/{id}", name="objeto_delete_cartainventario", methods={"DELETE", "GET", "POST"}) */ public function deleteCartaInventario(CartaAutorizacionInventario $cartaAutorizacionInventario, Request $request){ $data = json_decode($request->getContent(), true); if($this->isCsrfTokenValid('delete'.$cartaAutorizacionInventario->getId(), $data['_token'])){ $nom = $cartaAutorizacionInventario->getLink(); unlink($this->getParameter('cartaautorizacioninventario_directory').'/'.$nom); $em = $this->getDoctrine()->getManager(); $em->remove($cartaAutorizacionInventario); $em->flush(); return new JsonResponse(['success' => 1]); }else{ return new JsonResponse(['error' => 'Token Invalido'], 400); } } /** * @Route("/getobjetoxsitioinvpre", name="objetos_x_sitiosinvpre", methods={"GET","POST"}) */ public function getObjetosxSitiosinvpre(Request $request) { $em = $this->getDoctrine()->getManager(); $sitiopatrimonial_id = $request->get('sitiopatrimonial_id'); $fichaobjeto = $em->getRepository('App:FichaObjetoPatrimonial')->findBySitioInvpre($sitiopatrimonial_id); return new JsonResponse($fichaobjeto); } /** * @Route("/getobjetoxsitioinv", name="objetos_x_sitiosinv", methods={"GET","POST"}) */ public function getObjetosxSitiosinv(Request $request) { $em = $this->getDoctrine()->getManager(); $sitiopatrimonial_id = $request->get('sitiopatrimonial_id'); $fichaobjeto = $em->getRepository('App:FichaObjetoPatrimonial')->findBySitioInv($sitiopatrimonial_id); return new JsonResponse($fichaobjeto); } }
import { useEffect, useState } from 'react' import { type AppState, appStateSchema } from '~/types/AppState' export const useAppState = (): [AppState, (newAppState: AppState) => void] => { const [appState, setAppState] = useState<AppState>({ reactChallenge: { completedLowBlocks: [], }, }) useEffect(() => { const storedAppState = localStorage.getItem('appState') if (storedAppState) { try { const parsedState = JSON.parse(storedAppState) const appState = appStateSchema.parse(parsedState) setAppState(appState) } catch (e) { console.warn('can not parse appState', e) } } }, []) return [ appState, (newAppState: AppState) => { localStorage.setItem('appState', JSON.stringify(newAppState)) setAppState(newAppState) }, ] }
<!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <link href="https://fonts.googleapis.com/css2?family=Noto+Serif:wght@700&display=swap" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script> </head> <body> <style type="text/css"> input[type="file"] { position: absolute; left: 0; opacity: 0; top: 0; bottom: 0; width: 100%; } #divv { position: absolute; top: 0; bottom: 0; width: 100%; margin:0; display: flex; align-items: center; justify-content: center; background: #0F2027; /* fallback for old browsers */ background: -webkit-linear-gradient(to right, #2C5364, #203A43, #0F2027); /* Chrome 10-25, Safari 5.1-6 */ background: linear-gradient(to right, #2C5364, #203A43, #0F2027); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */ border: 3px dotted #bebebe; border-radius: 10px; } label { display: inline-block; position: relative; height: 100px; width: 400px; color:white; font-family: 'Noto Serif', serif; } div.dragover { background-color: #aaa; } #nombreMuestra{ font-size: 30px; } </style> <!-- Image and text --> {% raw %} <div class="container" id="app"> <nav class="navbar navbar-dark bg-dark"> <a class="navbar-brand" href="#"> <img src="/docs/4.5/assets/brand/bootstrap-solid.svg" width="30" height="30" class="d-inline-block align-top" alt="" loading="lazy"> HUELLITAS---- JOSE PASTOR---- FRANKLIN HUICHI </a> </nav> <br> <br> <label for="test"> <div id="divv">CLICK OR DRAG YOUR IMAGE</div> <input type="file" accept=".bmp" @change="onFileSelected" name="myfile" id="test"> </label> <p id="filename"></p> <br><br><br><br> <p id="nombreMuestra">Muestra: {{ nombre }}</p> <br><br><br><br> <table class="table"> <thead class="thead-dark"> <tr> <th scope="col">#</th> <th scope="col">Database</th> <th scope="col">Muestra</th> <th scope="col">Mensaje</th> </tr> </thead> <tbody> <tr v-for="(mensaje,indice) in mensajes"> <td> {{ indice+1 }}</td> <td> {{ mensaje.Nombre }} </td> <td> {{ mensaje.usuario }} </td> <td> {{ mensaje.resultado }} </td> </tr> </tbody> </table> </div> {% endraw %} <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> <script type="text/javascript"> var fileInput = document.querySelector('input[type=file]'); var filenameContainer = document.querySelector('#filename'); var dropzone = document.querySelector('div'); fileInput.addEventListener('change', function() { filenameContainer.innerText = fileInput.value.split('\\').pop(); }); fileInput.addEventListener('dragenter', function() { dropzone.classList.add('dragover'); }); fileInput.addEventListener('dragleave', function() { dropzone.classList.remove('dragover'); }); </script> <script type="text/javascript"> var app= new Vue({ el: "#app", data:{ mensajes:[] , nombre:"" }, methods:{ match:function(){ Swal.fire('MATCH ENCONTRADO') }, procesar:function(nombre){ var nombres=[]; var comparacion=[]; axios.post('/api/v1/procesar', {name:nombre }).then(response=> { console.log(response.data); this.mensajes=response.data['resultados']; for (var i = 0; i < this.mensajes.length; i++) { if (this.mensajes[i].estado==1) { this.match(); } } }); }, foo:function(){ console.log(this.nombres) console.log(this.comparacion) }, onFileSelected (event) { const file = event.target.files[0]; const formData = new FormData(); formData.append("myfile", file); console.log(formData); axios({ method: 'post', url: '/api/v1/subir', data: formData, headers: {'Content-Type': 'multipart/form-data' } }) .then(response=> { //handle success console.log(response); this.nombre=response.data.nombre console.log(this.nombre) this.procesar(this.nombre) }) .catch(function (response) { //handle error console.log(response); }); } }, created:function(){ } }) </script> </body> </html>
pragma solidity ^0.4.11; contract smartVoting { // maps candidates (bytes32) with number of votes recived (uint8) mapping (bytes32 => uint8) public votesReceived; // a separate array of candidate names, since Solidity lacks a .keys method bytes32[] public candidateList; // constructor function function smartVoting(bytes32[] candidateNames) { candidateList = candidateNames; } function totalVotesFor(bytes32 candidate) returns (uint8) { require(validCandidate(candidate)); return votesReceived[candidate]; } function voteForCandidate(bytes32 candidate) { require(validCandidate(candidate)); votesReceived[candidate] += 1; } function validCandidate(bytes32 candidate) returns (bool) { for(uint i = 0; i < candidateList.length; i++) { if (candidateList[i] == candidate) return true; } return false; } }
import { Site } from '../entries/Site' import { Timestamp } from 'firebase/firestore' describe('Site', () => { it('Supports base fields', () => { const site = new Site({ name: 'fwafawfa', description: 'faefaefa bdbmper odcöoabuw', lovesCount: 24, }) expect(site.name).toBe('fwafawfa') expect(site.description).toBe('faefaefa bdbmper odcöoabuw') expect(site.docData.name).toBe('fwafawfa') expect(site.docData.description).toBe('faefaefa bdbmper odcöoabuw') expect(site.lovesCount).toBe(24) expect(site.docData.lovesCount).toBe(24) }) it('Forces --- as a name instead of empty name for orderby and where support on firebase', () => { const site = new Site() expect(site.docData.name).toBe('---') }) it('Supports systemBadge', () => { const site = new Site({ systemBadge: 'fawefaefa' }) expect(site.systemBadge).toBe('fawefaefa') expect(site.docData.systemBadge).toBe('fawefaefa') }) it('Supports system', () => { const site = new Site({ system: 'fawefaefa' }) expect(site.system).toBe('fawefaefa') expect(site.docData.system).toBe('fawefaefa') }) it('Supports hidden', () => { const site = new Site({ hidden: true }) expect(site.hidden).toBe(true) expect(site.docData.hidden).toBe(true) }) it('Supports pageCategories', () => { const site = new Site({ pageCategories: [ { slug: 'fawefsdfaefa', name: 'fawefaefsfsdfa' }, { slug: 'fawefsdfaefa_2', name: 'fawefaefsfsdfa_2' } ] }) expect(site.pageCategories).toContainEqual({ slug: 'fawefsdfaefa', name: 'fawefaefsfsdfa' }) expect(site.pageCategories).toContainEqual({ slug: 'fawefsdfaefa_2', name: 'fawefaefsfsdfa_2' }) expect(site.docData.pageCategories).toContainEqual({ slug: 'fawefsdfaefa', name: 'fawefaefsfsdfa' }) }) it('Supports players', () => { const site = new Site({ players: ['player_1'], owners: ['owner_2', 'owner_3'] }) expect(site.players).toContain('player_1') expect(site.members).toContain('player_1') expect(site.members).toContain('owner_2') expect(site.members).toContain('owner_3') expect(site.docData.players).toContain('player_1') expect(site.docData.owners).toContain('owner_2') }) it('Supports avatar and poster', () => { const site = new Site({ avatarURL: 'avatar_url', posterURL: 'avatar_2' }) expect(site.avatarURL).toBe('avatar_url') expect(site.posterURL).toBe('avatar_2') expect(site.docData.avatarURL).toBe('avatar_url') expect(site.docData.posterURL).toBe('avatar_2') }) it('Supports legacy dates', () => { const ts = Timestamp.fromDate(new Date()) const site = new Site({ lastUpdate: ts }) expect(site.createdAt).toBe(ts) expect(site.updatedAt).toBe(ts) expect(site.flowTime).toBe(Math.floor(ts.toMillis())) expect(site.docData.createdAt).toBe(ts) }), it('provides a collectionName', () => { expect(Site.collectionName).toBe('sites') }) it('supports setting a license', () => { const site = new Site( { license: 'license' }, 'site_id_123' ) expect(site.license).toBe('license') expect(site.docData.license).toBe('license') site.license = 'a' expect(site.license).toBe('a') expect(site.docData.license).toBe('a') }) it('supports FirestoreEntry', () => { const site = new Site( { name: 'fwafawfa', description: 'faefaefa bdbmper odcöoabuw' }, 'site_id_123' ) expect(site.key).toBe('site_id_123') expect(site.getFirestorePath().join('/')).toBe('sites/site_id_123') }) it('supports setting a sort order', () => { const site = new Site( { sortOrder: Site.SORT_BY_MANUAL }, 'site_id_123' ) expect(site.sortOrder).toBe(Site.SORT_BY_MANUAL) expect(site.docData.sortOrder).toBe(Site.SORT_BY_MANUAL) site.sortOrder = Site.SORT_BY_NAME expect(site.sortOrder).toBe(Site.SORT_BY_NAME) expect(site.docData.sortOrder).toBe(Site.SORT_BY_NAME) }) it('supports dehydrating to JSON', () => { const site = new Site( { name: 'fwafawfa', description: 'faefaefa bdbmper odcöoabuw', lovesCount: 24, systemBadge: 'fawefaefa', system: 'fasfa_system', pageCategories: [ 'a', 'b' ] }, 'site_id_123' ) expect(site.toJSON()).toEqual({ key: 'site_id_123', name: 'fwafawfa', description: 'faefaefa bdbmper odcöoabuw', flowTime: -1, sortOrder: Site.SORT_BY_NAME, createdAt: undefined, updatedAt: undefined, lovesCount: 24, systemBadge: 'fawefaefa', system: 'fasfa_system', pageCategories: [ 'a', 'b' ] }) }) it('supports hydrating from JSON', () => { const json = { key: 'site_id_123', name: 'fwafawfa', description: 'faefaefa bdbmper odcöoabuw', flowTime: 24513523236, } const site = Site.fromJSON(json) expect(site.key).toBe('site_id_123') expect(site.name).toBe('fwafawfa') expect(site.description).toBe('faefaefa bdbmper odcöoabuw') expect(site.flowTime).toBe(24513523236) }) // Site supports setting a set of tags, and saving them to the db it('supports tags', () => { const site = new Site({ key: 'site_id_123' }) site.tags = ['tag1', 'tag2'] expect(site.tags).toEqual(['tag1', 'tag2']) expect(site.docData.tags).toEqual(['tag1', 'tag2']) }) // Site supports setting a set of links, and saving them to the db it('supports links', () => { const site = new Site({ key: 'site_id_123' }) site.links = [ { name: 'title', url: 'url' } ] expect(site.links).toEqual([ { name: 'title', url: 'url' } ]) expect(site.docData.links).toEqual([ { name: 'title', url: 'url' } ]) }), it('Has a collection name', () => { expect(Site.collectionName).toEqual('sites') }) it('Has a firestore path', () => { const site = new Site({ key: 'site_id_123' }) expect(site.getFirestorePath()).toEqual(['sites', 'site_id_123']) }) it('Has a setting for vanity page-ids', () => { const site = new Site({ key: 'site_id_123' }) expect(site.customPageKeys).toEqual(false) site.customPageKeys = true expect(site.customPageKeys).toEqual(true) expect(site.docData.customPageKeys).toEqual(true) }) })
import React from "react"; export interface PreSaveDataValue { dataElementId: string; optionComboId: string; fieldId: string; feedbackId: string | undefined; oldValue: string; } export interface DataValue { dataElementId: string; categoryOptionComboId: string; value: string; } interface AfterSaveDataValue { cc: string; co: string; cp: string; de: string; ds: string; ou: string; pe: string; value: string; } type DataValueSavedMsg = { type: "dataValueSavedFromIframe"; dataValue: AfterSaveDataValue }; type PreSaveDataValueMsg = { type: "preSaveDataValueFromIframe"; dataValue: PreSaveDataValue }; type MsgFromIframe = DataValueSavedMsg | PreSaveDataValueMsg; export type InputMsg = | { type: "preSaveDataValue"; dataValue: DataValue } | { type: "dataValueSaved"; dataValue: DataValue }; type SaveDataValueMsg = { type: "saveDataValueToIframe"; dataValue: PreSaveDataValue }; export type OutputMsg = SaveDataValueMsg; const inputMsgFromIframeTypes: MsgFromIframe["type"][] = [ "dataValueSavedFromIframe", "preSaveDataValueFromIframe", ]; export function useDhis2EntryEvents( iframeRef: React.RefObject<HTMLIFrameElement>, onMessage: (inputMsg: InputMsg) => Promise<boolean> | undefined, options: Options = {}, iframeKey: object ): void { const onMessageFromIframe = React.useCallback( async ev => { const iwindow = iframeRef.current && (iframeRef.current.contentWindow as DataEntryWindow); if (!iwindow) return; const { data } = ev; if (!isInputMsgFromIframe(data)) return; console.debug("|parent|<-", data); switch (data.type) { case "preSaveDataValueFromIframe": { const { fieldId } = data.dataValue; const value = iwindow.eval<string>(`$("#${fieldId}").val()`); const dataValue: DataValue = { dataElementId: data.dataValue.dataElementId, categoryOptionComboId: data.dataValue.optionComboId, value, }; const inputMsg: InputMsg = { type: "preSaveDataValue", dataValue }; const continueSaving = await onMessage(inputMsg); if (continueSaving === false) { console.debug("[data-entry:preSaveDataValueFromIframe] skip save"); const { oldValue } = data.dataValue; // Restore old value + show temporal yellow background const fadeColorTimeout = 10000; iwindow.eval(` $("#${fieldId}").val(${JSON.stringify(oldValue)}); $("#${fieldId}").css({ backgroundColor: "#fffe8c", }); window.setTimeout(() => { $("#${fieldId}").css({ backgroundColor: "#ffffff", transition: "background-color 1000ms linear", }); }, ${fadeColorTimeout}); `); } else { const saveDataValueMsg: SaveDataValueMsg = { type: "saveDataValueToIframe", dataValue: data.dataValue, }; console.debug("|parent|->", saveDataValueMsg); iwindow.postMessage(saveDataValueMsg, window.location.origin); } break; } case "dataValueSavedFromIframe": { const dv = data.dataValue; const dataValue: DataValue = { dataElementId: dv.de, categoryOptionComboId: dv.co, value: dv.value, }; const inputMsg: InputMsg = { type: "dataValueSaved", dataValue }; onMessage(inputMsg); break; } } }, [iframeRef, onMessage] ); React.useEffect(() => { const iwindow = getIframeWindow(iframeRef); if (!iwindow || !onMessage) return; window.addEventListener("message", onMessageFromIframe); return () => { window.removeEventListener("message", onMessageFromIframe); }; }, [iframeRef, onMessage, options, onMessageFromIframe]); React.useEffect(() => { const iwindow = getIframeWindow(iframeRef); if (!iwindow) return; iwindow.addEventListener("load", () => { const init = setupDataEntryInterceptors.toString(); iwindow.eval(`(${init})(${JSON.stringify(options)});`); }); }, [iframeRef, options, iframeKey]); } function getIframeWindow(iframeRef: React.RefObject<HTMLIFrameElement>) { const iframe = iframeRef.current; return iframe ? (iframe.contentWindow as DataEntryWindow) : undefined; } function isInputMsgFromIframe(msg: any): msg is MsgFromIframe { return typeof msg === "object" && inputMsgFromIframeTypes.includes(msg.type); } interface DataEntryWindow extends Window { eval<T>(code: string): T; dataEntryHooksInit: boolean; dhis2: { de: { currentExistingValue: string } }; saveVal( dataElementId: string, optionComboId: string, fieldId: string, feedbackId: string | undefined ): void; } export interface Options { interceptSave?: boolean; getOnSaveEvent?: boolean; } /* Function to eval within the iframe to send/receive events to/from the parent page */ function setupDataEntryInterceptors(options: Options = {}) { const iframeWindow = window as unknown as DataEntryWindow; console.debug("|data-entry|:setup-interceptors", iframeWindow.dataEntryHooksInit, options); if (iframeWindow.dataEntryHooksInit) return; if (options.getOnSaveEvent) { iframeWindow .jQuery(iframeWindow) .on( "dhis2.de.event.dataValueSaved", function (_ev: unknown, _dataSetId: string, dataValue: AfterSaveDataValue) { const msg: DataValueSavedMsg = { type: "dataValueSavedFromIframe", dataValue: dataValue, }; console.debug("<-|data-entry|", msg); iframeWindow.parent.postMessage(msg, window.location.origin); } ); } const saveValOld = iframeWindow.saveVal; if (options.interceptSave) { // Wrap saveVal (dhis-web-dataentry/javascript/entry.js) iframeWindow.saveVal = function (dataElementId, optionComboId, fieldId, feedbackId) { const preSaveDataValue: PreSaveDataValue = { dataElementId, optionComboId, fieldId, feedbackId, oldValue: iframeWindow.dhis2.de.currentExistingValue, }; const msg: PreSaveDataValueMsg = { type: "preSaveDataValueFromIframe", dataValue: preSaveDataValue, }; console.debug("<-|data-entry|", msg); iframeWindow.parent.postMessage(msg, window.location.origin); }; } window.addEventListener("message", function (ev) { const data = ev.data as SaveDataValueMsg; console.debug("->|data-entry|", data); if (typeof data !== "object") return; if (data.type === "saveDataValueToIframe") { const { dataElementId, optionComboId, fieldId, feedbackId } = data.dataValue; saveValOld(dataElementId, optionComboId, fieldId, feedbackId); } }); iframeWindow.dataEntryHooksInit = true; }
import { Rarity } from "../../../shared/port/rarity"; import { CharacterClass } from "./character-class"; import { Skill } from "./skill"; import { Stat } from "./stat"; interface ICharacterProps { id: number; class: CharacterClass; mutation: number; rarity: Rarity; image: string; name: string; skills: Skill[]; pastTransactions: string[]; stats: Stat[]; } export class Character { constructor(private props: ICharacterProps) {} get id() { return this.props.id; } get image() { return this.props.image; } get class() { return this.props.class; } get mutation() { return this.props.mutation; } get name() { return this.props.name; } get rarity() { return this.props.rarity; } get skills() { return this.props.skills; } get stats() { return this.props.stats; } get pastTransactions() { return this.props.pastTransactions; } }
# OpenSearch Since testcontainers-go <a href="https://github.com/testcontainers/testcontainers-go/releases/tag/v0.29.0"><span class="tc-version">:material-tag: v0.29.0</span></a> ## Introduction The Testcontainers module for OpenSearch. ## Adding this module to your project dependencies Please run the following command to add the OpenSearch module to your Go dependencies: ``` go get github.com/testcontainers/testcontainers-go/modules/opensearch ``` ## Usage example <!--codeinclude--> [Creating a OpenSearch container](../../modules/opensearch/examples_test.go) inside_block:runOpenSearchContainer <!--/codeinclude--> ## Module reference The OpenSearch module exposes one entrypoint function to create the OpenSearch container, and this function receives two parameters: ```golang func RunContainer(ctx context.Context, opts ...testcontainers.ContainerCustomizer) (*OpenSearchContainer, error) ``` - `context.Context`, the Go context. - `testcontainers.ContainerCustomizer`, a variadic argument for passing options. ### Container Options When starting the OpenSearch container, you can pass options in a variadic way to configure it. #### Image If you need to set a different OpenSearch Docker image, you can use `testcontainers.WithImage` with a valid Docker image for OpenSearch. E.g. `testcontainers.WithImage("opensearchproject/opensearch:2.11.1")`. {% include "../features/common_functional_options.md" %} #### User and password If you need to set a different password to request authorization when performing HTTP requests to the container, you can use the `WithUsername` and `WithPassword` options. By default, the username is set to `admin`, and the password is set to `admin`. <!--codeinclude--> [Custom Credentials](../../modules/opensearch/examples_test.go) inside_block:runOpenSearchContainer <!--/codeinclude--> ### Container Methods The OpenSearch container exposes the following methods: #### Address The `Address` method returns the location where the OpenSearch container is listening. It returns a string with the format `http://<host>:<port>`. !!!warning TLS is not supported at the moment. <!--codeinclude--> [Connecting using HTTP](../../modules/opensearch/opensearch_test.go) inside_block:httpConnection <!--/codeinclude-->