text
stringlengths
184
4.48M
<?php namespace App\Http\Controllers; use App\Models\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; class RegisterController extends Controller { // public function index(){ return view('register.index',[ 'title' => 'Register', 'active' => 'register' ]); } public function store(Request $request){ $validateData = $request->validate([ 'name' => 'required|max:225', 'username' => 'required|min:5|unique:users|max:225', 'email' => 'required|email:dns|unique:users', 'password' =>'required|min:5|max:255', ]); $validateData['password'] = Hash::make($validateData['password']); User::create($validateData); $request->session()->flash('success','Registration Successfull! Please Login.'); return redirect('/'); } }
import React, { useCallback, useEffect, useMemo, useState } from "react"; import useForceUpdate from "@hooks/useForceUpdate"; import useSocketContext from "@hooks/useSocketContext"; import useClientDeviceContext from "@hooks/useClientDeviceContext"; import useDocumentTitle from "@hooks/useDocumentTitle"; import useObjectState from "@hooks/useObjectState"; import useLocalStorage from "@hooks/useLocalStorage"; import { KEY_TRANSCODER_DID_MANUALLY_LOGOUT } from "@local/localStorageKeys"; import { fetch } from "@shared/SocketAPIClient"; import { SOCKET_API_ROUTE_INIT_TRANSCODER_SESSION, SOCKET_API_ROUTE_CAPTURE_NETWORK_TOTAL_PARTICIPANTS, SOCKET_API_ROUTE_END_TRANSCODER_SESSION, } from "@shared/socketAPIRoutes"; import TranscoderZenRTCManager, { EVT_DESTROYED, EVT_PEER_UPDATED, EVT_PEER_CONNECTED, EVT_PEER_DISCONNECTED, EVT_PEER_DESTROYED, } from "../subClasses/TranscoderZenRTCManager"; import useSplitAppMessageBus, { TRANSCODER_EVT_CONNECTED, TRANSCODER_EVT_DISCONNECTED, } from "@hooks/useSplitAppMessageBus"; export const TranscoderPhantomSessionContext = React.createContext({}); export default function TranscoderPhantomSessionProvider({ children }) { const mainAppMessageBus = useSplitAppMessageBus(); const { socket, deviceAddress, isConnected: isSocketConnected, // connect: connectSocket, // disconnect: disconnectSocket, } = useSocketContext(); const { setItem } = useLocalStorage(); const forceUpdate = useForceUpdate(); const [ { networkName, realmId, channelId, networkDescription, transcoderManager }, setState, ] = useObjectState({ networkName: null, realmId: null, channelId: null, networkDescription: null, transcoderManager: null, }); useTranscoderDocumentTitle({ realmId, channelId, isSocketConnected }); const { peers } = useTranscoderManager(transcoderManager, { networkName, networkDescription, }); const { userAgent, coreCount } = useClientDeviceContext(); /** * Starts transcoding servicing for this network. * * @return {Promise<void>} */ const login = useCallback( async ({ realmId, channelId, networkName, networkDescription, isPublic, }) => { await fetch(SOCKET_API_ROUTE_INIT_TRANSCODER_SESSION, { deviceAddress, userAgent, coreCount, buildHash: process.env.REACT_APP_GIT_HASH, networkName, realmId, channelId, networkDescription, isPublic, }); setState({ networkName, realmId, channelId, networkDescription, }); setItem(KEY_TRANSCODER_DID_MANUALLY_LOGOUT, false); }, [coreCount, deviceAddress, userAgent, setState, setItem] ); /** * Stops transcoding servicing for this network. * * @return {Promise<void>} */ const logout = useCallback(async () => { await fetch(SOCKET_API_ROUTE_END_TRANSCODER_SESSION, { realmId, channelId, }); transcoderManager && transcoderManager.destroy(); setItem(KEY_TRANSCODER_DID_MANUALLY_LOGOUT, true); // Handle window close or redirect try { window.close(); } catch (err) { console.debug("Caught", err); } finally { window.location.href = "/"; } }, [realmId, channelId, transcoderManager, setItem]); useEffect(() => { if (socket && realmId && channelId && isSocketConnected) { const transcoderManager = new TranscoderZenRTCManager({ socket, realmId, channelId, hostDeviceAddress: deviceAddress, }); transcoderManager.on(EVT_PEER_UPDATED, forceUpdate); setState({ transcoderManager }); // Emit to main app that we've connected mainAppMessageBus.sendEvent(TRANSCODER_EVT_CONNECTED); transcoderManager.once(EVT_DESTROYED, () => { // TODO: Implement reset state setState({ transcoderManager: null, networkName: null, realmId: null, channelId: null, networkDescription: null, }); // Emit to main app that we've disconnected mainAppMessageBus.sendEvent(TRANSCODER_EVT_DISCONNECTED); }); return function unmount() { transcoderManager.destroy(); }; } }, [ socket, realmId, channelId, forceUpdate, isSocketConnected, setState, deviceAddress, mainAppMessageBus, ]); // Handle manual window close useEffect(() => { if (mainAppMessageBus) { const handleBeforeUnload = () => { mainAppMessageBus.sendEvent(TRANSCODER_EVT_DISCONNECTED); }; window.addEventListener("beforeunload", handleBeforeUnload); return function unmount() { window.removeEventListener("beforeunload", handleBeforeUnload); }; } }, [mainAppMessageBus]); // Whether or not the session is currently active const isConnected = useMemo(() => Boolean(transcoderManager), [ transcoderManager, ]); /** * @return {number} */ const getSessionUptime = useCallback( () => (transcoderManager ? transcoderManager.getInstanceUptime() : 0), [transcoderManager] ); return ( <TranscoderPhantomSessionContext.Provider value={{ isConnected, networkName, realmId, channelId, networkDescription, login, logout, peers, getSessionUptime, }} > {children} </TranscoderPhantomSessionContext.Provider> ); } // TODO: Split into separate file function useTranscoderDocumentTitle({ realmId, channelId, isSocketConnected }) { const documentTitle = useMemo(() => { return ( (isSocketConnected && realmId && channelId && `${realmId} / ${channelId}`) || null ); }, [realmId, channelId, isSocketConnected]); useDocumentTitle(documentTitle, "speaker.app transcoder"); } // TODO: Split into separate file function useTranscoderManager( transcoderManager, { networkName, networkDescription } ) { const [peers, _setPeers] = useState([]); useEffect(() => { if (transcoderManager) { const _handlePeerUpdate = () => { const peers = transcoderManager.getPeers(); _setPeers(peers); }; transcoderManager.on(EVT_PEER_CONNECTED, _handlePeerUpdate); transcoderManager.on(EVT_PEER_DISCONNECTED, _handlePeerUpdate); transcoderManager.on(EVT_PEER_DESTROYED, _handlePeerUpdate); return function unmount() { transcoderManager.off(EVT_PEER_CONNECTED, _handlePeerUpdate); transcoderManager.off(EVT_PEER_DISCONNECTED, _handlePeerUpdate); transcoderManager.on(EVT_PEER_DESTROYED, _handlePeerUpdate); }; } else { _setPeers([]); } }, [transcoderManager]); useEffect(() => { if (transcoderManager) { transcoderManager.setNetworkData({ networkName, networkDescription }); } }, [transcoderManager, networkName, networkDescription]); const peerLength = peers.length; useEffect(() => { if (transcoderManager) { // TODO: Sync this to server fetch(SOCKET_API_ROUTE_CAPTURE_NETWORK_TOTAL_PARTICIPANTS, peerLength); } }, [transcoderManager, peerLength]); return { peers, }; }
package com.mcartagena.learnjava.io; import java.io.*; class Bird { protected transient String name; public void setName(String name) { this.name = name; } public String getName() { return name; } public Bird() { this.name = "Matt"; } } public class Eagle extends Bird implements Serializable { { this.name = "Olivia"; } public Eagle() { this.name = "Bridget"; } public static void main(String[] args) throws Exception { var e = new Eagle(); e.name = "Adeline"; System.out.println(e.name); // Adeline FileOutputStream fos = new FileOutputStream("Eagle.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(e); FileInputStream fis = new FileInputStream("Eagle.ser"); ObjectInputStream ois = new ObjectInputStream(fis); Eagle e2 = (Eagle) ois.readObject(); System.out.println(e2.name); // Matt } }
<?php namespace App\Http\Controllers; use App\Models\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; class UserController extends Controller { /** * Display a listing of the resource. */ public function index() { return User::all(); } /** * Store a newly created resource in storage. */ public function store(Request $request) { $inputs = $request->input(); $inputs["password"] = Hash::make(trim($request->password)); $e = User::create($inputs); return response()->json([ 'data'=>$e, 'mensaje'=>'Registrado con éxito.' ]); } /** * Display the specified resource. */ public function show(string $id) { $e = User::find($id); if (isset($e)){ return response()->json([ 'data'=>$e, 'mensaje'=>'Encontrado con éxito.', ]); }else{ return response()->json([ 'error'=>true, 'mensaje'=>'No esxiste.' , ]); } } /** * Update the specified resource in storage. */ public function update(Request $request, string $id) { $e = User::find($id); if(isset($e)){ $e->name = $request->name; $e->email = $request->email; $e->password = Hash::make($request->password); if ($e->save()){ return response()->json([ 'data'=>$e, 'mensaje'=>'Actualizado con éxito.', ]); }else{ return response()->json([ 'error'=>true, 'mensaje'=>'No se se pudo actualizar.' , ]); } }else{ return response()->json([ 'error'=>true, 'mensaje'=>'No esxiste.' , ]); } } /** * Remove the specified resource from storage. */ public function destroy(string $id) { $e = User::find($id); if (isset($e)){ $res=User::destroy($id); if ($res){ return response()->json([ // 'data'=>$e, 'mensaje'=>'Eliminado con éxito.', ], 201); }else{ return response()->json([ 'error'=>true, 'mensaje'=>'Error al eliminar el usuario.' , ]); } }else{ return response()->json([ 'data'=>$e, 'mensaje'=>'No existe el usuario.', ]); } } }
package com.chejet.cloud.controller; import com.chejet.cloud.common.ErrorCodeEnum; import com.chejet.cloud.exception.BaseException; import com.chejet.cloud.po.Attach; import com.chejet.cloud.response.ApiResp; import com.chejet.cloud.response.ResultBuilder; import com.chejet.cloud.service.AttachService; import com.chejet.cloud.util.ImageUtil; import org.apache.commons.io.IOUtils; import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.util.Objects; /** * @author Neo.fang * @creatTime 2018/10/15 0015 */ @CrossOrigin(origins = "*", maxAge = 3600) @RestController @RequestMapping(value = "/file") public class FileUploadController { // @Autowired // private FileUploadConfig fileUploadConfig; private static final String GET_SERVICE_DIR = "/public/image/"; //服务器请求文件的路由(与请求保持一致,可加入随机字符串干扰) private static final String STORE_FILE_DIR = "/usr/local/image/"; // LINUX文件保存的路径 private static final String STORE_FILE_DIR_BASE = "D:"; //WINDOWS文件仓库目录 private static String BUCKETNAME = "united-centre"; // 存储空间(仓库中的分类目录) @Autowired private AttachService attachService; @RequestMapping(value = "/upload/{type}", method = RequestMethod.POST) public ApiResp upload(HttpServletRequest request, @PathVariable Integer type) throws Exception { // 判断enctype属性是否为multipart/form-data boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { throw new BaseException(ErrorCodeEnum.MULTIPART_TYPE_ERROR); } MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile file = multipartRequest.getFile("file"); if (file == null || file.getSize() <= 0) { throw new BaseException(ErrorCodeEnum.FILE_IS_EMPTY); } String imageFormat = ImageUtil.getImageFormat(file.getInputStream()); if (!("jpg".equalsIgnoreCase(imageFormat) || "png".equalsIgnoreCase(imageFormat) || "jpeg".equalsIgnoreCase(imageFormat))){ throw new BaseException(ErrorCodeEnum.PICTURE_FORMAT_IS_NOT_SUPPORTED); } InputStream in = file.getInputStream(); String originalFilename = file.getOriginalFilename(); String sub = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase(); String name = System.currentTimeMillis() + sub; String filePath = STORE_FILE_DIR + File.separator + BUCKETNAME + File.separator + name; try { //写入文件到当前服务器磁盘 File uploadedFile = new File(filePath); FileOutputStream out = new FileOutputStream(uploadedFile); //BufferedOutputStream bos = new BufferedOutputStream(out); //使用IOUtils工具输出, 也就是copy文件 IOUtils.copy(in, out); in.close(); out.close(); }catch (Exception e){ throw new BaseException(ErrorCodeEnum.STORAGE_PATH_ERROR); } // String hostAddress = InetAddress.getLocalHost().getHostAddress(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath(); String link = basePath + GET_SERVICE_DIR + BUCKETNAME + "/" + name; /** * 存入文件附件管理 */ Attach attach = attachService.saveAttach(link, type); return ResultBuilder.buildDateSuccess(attach); } }
# HW of Fama-Macbeth ## So WTF is Fama-Macbeth reg??? - 1973年由这两个人提出,目的是检验CAPM - 两步**截面**回归,which可以排除残差在截面上的相关性对标准误的影响 - 所以这句话是什么意思,什么的标准误,什么的的残差?? - 在金融领域,这个回归常被用于在多因子模型中分析投资标的截面预期收益率与因子暴露的关系 - 这又是什么意思,什么叫截面预期收益率,是不考虑历史因子值,只考虑当期因子值的意思吗 - Two- pass regression estimate ## Show me formula!! ### Step1 对单个股票的时间序列做如下回归,得到个股收益率在因子上的暴露$\beta_i$ d s s s s s s s s s s s $$ R_{it}=\alpha_i+\beta_i'f_t+\varepsilon_{it} $$ 这里的因子 $f$ 可以是随便什么东西,可以是某个特殊组合的收益率,也可以是宏观指标等。 上面这个回归有些比较显然的事实: - 第一步回归的残差是与$i,t$有关的,说的是$i$股票回归后在$t$时刻的残差 - 然后回归出来的$\alpha_i,\beta_i$都是与时间无关的,简直可以看作是股票$i$的一个固有属性啊,太厉害了 ### Step2 第二步做了如下的截面回归: $$ R_{it}=\beta_i'\lambda_t+\alpha_{it}\\ 矩阵形式:\\ R_t=\beta'\lambda_t+\alpha_t\\ R_t:N\times1,\quad \beta:K\times N,\quad \lambda:K\times1,\quad \alpha_t: N\times1 \\ \hat{\lambda}=\frac{1}{T}\sum\limits_ {t=1}^T\hat{\lambda_t}\\ \hat{\alpha}_i=\hat{\lambda}=\frac{1}{T}\sum\limits_ {t=1}^T\hat{\alpha}_{it} $$ 这个回归注意下,Fama-Macbeth的这个回归是在每一个 t 都做了一次**截面**回归,也就是说每一个 t 时刻固定的情况下回归出一个 $\lambda_t$ 和 $\alpha_{it}$ ,然后在把他们取均值。 这要怎么理解呢,我的哥啊 - 先看做平均之前的估计出的estimators有啥含义吧嘻嘻^^ - 其这个回归的式子是拿 t 时刻截面上的100家公司的收益回归到他们的固有属性,which is因子暴露上 - 这里 t 时刻的$\lambda_t$表示的其实是一个斜率,什么的斜率呢?SML的斜率,怎么解释呢?其实我们知道在 t 时刻这个截面上,有很多支股票对吧,有个显然的事实是每个股票的 $\beta$ 都是不一样的,当然他们的收益也是不一样的,然后我们又假定了 $\beta$ 与收益的关系是线性的,那么这个回归出的 $\lambda_t$ 就会是个斜率,代表了在 t 时刻,收益率与 $\beta$ 的一个关系,虽然每个公司的 $\beta$ 都不一样,但是还是可以总结为有 K 种 $\beta$ ,所以相应的,会有 K 个 $\lambda_t$ 。
import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:the_meal_flutter/src/src.dart'; void main() { group('message_cubit_test.dart', () { group('Given: Show Normal Snackbar', () { blocTest<MessageCubit, Message?>( 'When: showSnackBar(isError: false) - Then: Message()', build: () => MessageCubit(), act: (cubit) => cubit.showSnackBar( message: 'Hello World!', timestamp: DateTime.now(), ), expect: () => [isA<Message>()], ); }); group('Given: Show Error Snackbar', () { blocTest<MessageCubit, Message?>( 'When: showSnackBar(isError: true) - Then: Message()', build: () => MessageCubit(), act: (cubit) => cubit.showSnackBar( isError: true, message: 'Hello World!', timestamp: DateTime.now(), ), expect: () => [isA<Message>()], ); }); }); }
// // SearchBar.swift // Owl // // Created by Denys Danyliuk on 18.04.2022. // import SwiftUI struct SearchBar: View { // MARK: - FocusedField enum FocusedField: Hashable { case search } // MARK: - Properties static let searchBarBackgroundColor = Color( red: 0.46, green: 0.46, blue: 0.5 ).opacity(0.12) @Binding var searchText: String @Binding var isSearching: Bool @FocusState var focusedField: FocusedField? let placeholder: String let onSubmit: () -> Void // MARK: - Lifecycle init( searchText: Binding<String>, isSearching: Binding<Bool> = .constant(false), placeholder: String, onSubmit: @escaping () -> Void ) { self._searchText = searchText self._isSearching = isSearching self.placeholder = placeholder self.onSubmit = onSubmit } var body: some View { ZStack { Rectangle() .foregroundColor(SearchBar.searchBarBackgroundColor) HStack { Image(systemName: "magnifyingglass") .foregroundColor(Color(uiColor: .secondaryLabel)) TextField( placeholder, text: $searchText, onEditingChanged: { isEditing in withAnimation { isSearching = isEditing } } ) .textFieldStyle(PlainTextFieldStyle()) .focused($focusedField, equals: .search) .toolbar { ToolbarItem(placement: .keyboard) { HStack { Button("Clear") { searchText = "" } Spacer() Button("Close") { focusedField = nil } } } } .submitLabel(.search) .onSubmit(of: .text) { withAnimation { isSearching = false } onSubmit() } } .padding(.leading, 13) } .frame(height: 40) .cornerRadius(13) .padding() } }
// // SecondSignupVC.swift // konnex-ios // // Created by Shavkat Khoshimov on 16/05/23. // Copyright © 2023 Achilov Bakhrom. All rights reserved. // import UIKit import Combine class SecondSignupVC: BaseViewController, UITextFieldDelegate, UIViewControllerTransitioningDelegate { var viewModel: SignUpViewModel var cancellables = Set<AnyCancellable>() var isToSignInVC = false var user: SignUpUser init(viewModel: SignUpViewModel, user: SignUpUser) { self.viewModel = viewModel self.user = user super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func bindViewModel() { viewModel.viewModelEvent.sink { [weak self] (value) in self?.handleViewModelEvent(state: value) }.store(in: &cancellables) viewModel.errorMessagePub.sink { [weak self] (value) in self?.showSnackBar(text: value) }.store(in: &cancellables) viewModel.isValidPasswordPub.receive(on: DispatchQueue.main).sink { [weak self] (value) in self?.newPasswordView.itemLabel.textColor = value ? UIColor.subtitleColorGrey() : .textRed() }.store(in: &cancellables) viewModel.isPasswordMatchesPub.receive(on: DispatchQueue.main).sink { [weak self] (value) in guard let self = self else { return } if self.newPasswordView.itemTextField.text.isNilOrEmpty { self.confirmPasswordView.itemLabel.textColor = .textRed() } else { self.confirmPasswordView.itemLabel.textColor = value ? UIColor.subtitleColorGrey() : .textRed() } self.validToSubmit = value }.store(in: &cancellables) viewModel.openConfirmationVC.receive(on: DispatchQueue.main).sink { [weak self] (value) in self?.show(ConfirmationVC(), sender: self) }.store(in: &cancellables) } func setupPublishers() { NotificationCenter.default .publisher(for: NSNotification.Name.UITextFieldTextDidChange, object: newPasswordView.itemTextField) .map { ($0.object as! UITextField).text ?? "" } .assign(to: \.password, on: viewModel) .store(in: &cancellables) NotificationCenter.default .publisher(for: NSNotification.Name.UITextFieldTextDidChange, object: confirmPasswordView.itemTextField) .map { ($0.object as! UITextField).text ?? "" } .assign(to: \.confirmPassword, on: viewModel) .store(in: &cancellables) } lazy var scrollView: UIScrollView = { let scrollV = UIScrollView() scrollV.backgroundColor = UIColor.lightBackgroundColor() return scrollV }() lazy var containerV: UIView = { let contentView = UIView(frame: .zero) contentView.backgroundColor = .clear return contentView }() lazy var backImageV: UIImageView = { let img = UIImageView(frame: UIScreen.main.bounds) img.image = UIImage(named: "signInBackImage") img.contentMode = .scaleAspectFill img.layer.masksToBounds = true return img }() lazy var stackView: UIStackView = { let stack = UIStackView() stack.axis = .vertical stack.spacing = 16 stack.distribution = .fill return stack }() lazy var logoImageView: UIImageView = { let logoImageView = UIImageView(frame: .zero) logoImageView.contentMode = .scaleAspectFit logoImageView.image = UIImage(named: "kennektNewLogo") return logoImageView }() lazy var titleLabel: UILabel = { let label = UILabel(frame: .zero) label.text = "Create an account" label.textAlignment = .center label.textColor = UIColor.blackDark() label.font = AppFont.font(type: .bold, size: 20) return label }() lazy var descrLabel: UILabel = { let label = UILabel(frame: .zero) label.text = "The most effective business management system" label.textAlignment = .center label.textColor = UIColor.subtitleColorGrey() label.font = AppFont.font(type: .regular, size: 14) return label }() lazy var newPasswordView: SignUpTextFieldView = { let password = SignUpTextFieldView(title: "Password*", placeholderText: "Create your password") password.itemTextField.isSecureTextEntry = true password.passwordViewOption.isHidden = false password.itemTextField.delegate = self return password }() lazy var confirmPasswordView: SignUpTextFieldView = { let confirm = SignUpTextFieldView(title: "Confirm Password*", placeholderText: "Confirm your password") confirm.passwordViewOption.isHidden = false confirm.itemTextField.isSecureTextEntry = true confirm.itemTextField.delegate = self return confirm }() lazy var signUpBtn: UIButton = { let btn = UIButton(type: .system) btn.setTitle("SIGN UP", for: .normal) btn.titleLabel?.font = AppFont.font(type: .bold, size: 14) btn.backgroundColor = UIColor.primare() btn.setTitleColor(UIColor.lightBackgroundColor(), for: .normal) btn.layer.cornerRadius = 8 btn.layer.masksToBounds = true btn.addTarget(self, action: #selector(signUpButtonClicked), for: .touchUpInside) return btn }() lazy var signingLabel: UILabel = { let label = UILabel(frame: .zero) label.text = "By signing in you agree to KENNEKT's" label.textAlignment = .center label.textColor = UIColor.subtitleColorGrey() label.font = AppFont.font(type: .regular, size: 12) label.translatesAutoresizingMaskIntoConstraints = false return label }() lazy var signInLabel: UILabel = { let label = UILabel(frame: .zero) label.text = "Already have an account? Sign In" label.textAlignment = .center label.textColor = UIColor.subtitleColorGrey() label.font = AppFont.font(type: .regular, size: 14) let tapgesture = UITapGestureRecognizer(target: self, action: #selector(signInLabelClicked)) label.isUserInteractionEnabled = true label.addGestureRecognizer(tapgesture) return label }() fileprivate func setSignupButtonState() { if validToSubmit { self.signUpBtn.isEnabled = true self.signUpBtn.backgroundColor = UIColor.primare() } else { self.signUpBtn.isEnabled = false self.signUpBtn.backgroundColor = UIColor.iconGray() } } var validToSubmit: Bool = false { didSet { setSignupButtonState() } } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { // Disallow whitespace input let whitespaceCharacterSet = CharacterSet.whitespaces let range = string.rangeOfCharacter(from: whitespaceCharacterSet) return range == nil } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.isHidden = true } override func viewWillDisappear(_ animated: Bool) { if isToSignInVC { super.viewWillDisappear(animated) self.navigationController?.setNavigationBarHidden(true, animated: true) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() view.clipsToBounds = true } override func viewDidLoad() { super.viewDidLoad() self.bindViewModel() self.setupPublishers() labelAttribute() self.configureSubViews() } func setUpStackViewItems() { stackView.addArrangedSubview(newPasswordView) stackView.addArrangedSubview(confirmPasswordView) } func labelAttribute() { var textArray = [String]() var fontArray = [UIFont]() var colorArray = [UIColor]() textArray.append("Already have an account?") textArray.append(" Sign In") fontArray.append(AppFont.font(type: .regular, size: 14)) fontArray.append(AppFont.font(type: .regular, size: 14)) colorArray.append(UIColor.subtitleColorGrey()) colorArray.append(UIColor.primare()) signInLabel.attributedText = getAttributedString(arrayText: textArray, arrayColors: colorArray, arrayFonts: fontArray) } func getAttributedString(arrayText:[String]?, arrayColors:[UIColor]?, arrayFonts:[UIFont]?) -> NSMutableAttributedString { let finalAttributedString = NSMutableAttributedString() for i in 0 ..< (arrayText?.count)! { let attributes = [NSAttributedString.Key.foregroundColor: arrayColors?[i], NSAttributedString.Key.font: arrayFonts?[i]] let attributedStr = (NSAttributedString.init(string: arrayText?[i] ?? "", attributes: attributes as [NSAttributedString.Key : Any])) if i != 0 { finalAttributedString.append(NSAttributedString.init(string: " ")) } finalAttributedString.append(attributedStr) } return finalAttributedString } @objc func signUpButtonClicked() { self.user.password = newPasswordView.itemTextField.text self.user.confirmPassword = confirmPasswordView.itemTextField.text closeKeyboard() viewModel.signup(newUser: self.user) } @objc private func signInLabelClicked() { closeKeyboard() guard let signInVC = self.navigationController?.viewControllers.first(where: {$0 is SignInVC}) as? SignInVC else { return } self.navigationController?.popToViewController(signInVC, animated: true) } } // MARK: Constraints extension SecondSignupVC { fileprivate func configureSubViews(){ setUpStackViewItems() konnex_ios.addSubviews(parentView: self.view, views: [scrollView]) konnex_ios.addSubviews(parentView: scrollView, views: [containerV]) konnex_ios.addSubviews(parentView: containerV, views: [ backImageV,logoImageView,titleLabel,descrLabel,stackView, signUpBtn,signingLabel,signInLabel ]) configureUI() } fileprivate func configureUI() { let padding: CGFloat = 25 scrollView.contentSize = containerV.frame.size scrollView.fillSuperview() containerV.fillSuperview() backImageV.fillSuperview() logoImageView.top(containerV.topAnchor, 120) logoImageView.centerX(containerV.centerXAnchor) titleLabel.top(logoImageView.bottomAnchor, padding) titleLabel.centerX(containerV.centerXAnchor) descrLabel.top(titleLabel.bottomAnchor, 16) descrLabel.left(containerV.leftAnchor, padding) descrLabel.right(containerV.rightAnchor, -padding) descrLabel.height(20) stackView.top(descrLabel.bottomAnchor, padding+padding) stackView.centerX(containerV.centerXAnchor) stackView.widthForLayout(containerV.widthAnchor, -32) signUpBtn.bottom(signingLabel.topAnchor, -padding) signUpBtn.left(containerV.leftAnchor, 16) signUpBtn.right(containerV.rightAnchor, -16) signUpBtn.height(50) signingLabel.bottom(signInLabel.topAnchor, -padding) signingLabel.centerX(containerV.centerXAnchor) signingLabel.left(containerV.leftAnchor, padding) signingLabel.right(containerV.rightAnchor, -padding) signInLabel.bottom(containerV.bottomAnchor, -10-safeAreaBottomHeight) signInLabel.centerX(containerV.centerXAnchor) signInLabel.left(containerV.leftAnchor, padding) signInLabel.right(containerV.rightAnchor, -padding) } }
import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "orm_skeleton.settings") django.setup() from main_app.models import Pet, Artifact, Location, Car, Task def create_pet(name, species): Pet.objects.create( name=name, species=species ) return f"{name} is a very cute {species}!" def create_artifact(name, origin, age, description, is_magical): Artifact.objects.create( name=name, origin=origin, age=age, description=description, is_magical=is_magical, ) def delete_all_artifacts(): Artifact.objects.all().delete() def show_all_locations(): locations = Location.objects.all().order_by('-id') return '\n'.join(str(l) for l in locations) def new_capital(): Location.objects.filter(pk=1).update(is_capital=True) # locations = Location.objects.first() # locations.is_capital = True # locations.save() def get_capitals(): return Location.objects.filter(is_capital=True).values("name") def delete_first_location(): Location.objects.first().delete() def apply_discount(): cars = Car.objects.all() for car in cars: percentage_off = sum(int(d) for d in str(car.year)) / 100 discount = float(car.price) * percentage_off car.price_with_discount = float(car.price) - discount car.save() def get_recent_cars(): return Car.objects.filter(year__gte=2020).values("model", "price_with_discount") def delete_last_car(): Car.objects.last().delete() def show_unfinished_tasks(): unfinished_tasks = Task.objects.all().filter(is_finished=False) return '\n'.join(str(t) for t in unfinished_tasks) def complete_odd_tasks(): for task in Task.objects.all(): if task.id % 2 != 0: task.is_finished = True task.save() def encode_and_replace(text, task_title): decoding_text = ''.join(chr(ord(x) - 3) for x in text) Task.objects.filter(title=task_title).update(description=decoding_text) # task_matching = Task.objects.filter(title=task_title) # decoding_text = ''.join(chr(ord(x) - 3) for x in text) # # for task in task_matching: # task.description = decoding_text # task.save()
/*! * Copyright 2022 - Swiss Data Science Center (SDSC) * A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and * Eidgenössische Technische Hochschule Zürich (ETHZ). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { EntityCreator } from "../../components/entities/Creators"; import { SessionStatus } from "../../features/session/sessions.types"; export interface NotebookAnnotations { branch: string; "commit-sha": string; default_image_used: boolean; namespace: string; gitlabProjectId: number; projectName: string; repository: string; resourceClassId: string; hibernation: Record<string, unknown>; hibernationBranch: string; hibernationCommitSha: string; hibernationDate: string; hibernationDirty: boolean; hibernationSynchronized: boolean; hibernatedSecondsThreshold: string; // Annotations for Renku 2.0 renkuVersion?: string; projectId?: string; launcherId?: string; [key: string]: unknown; } interface LogsData { [key: string]: string; } export interface SessionHandlers { // eslint-disable-next-line @typescript-eslint/ban-types fetchLogs: Function; // eslint-disable-next-line @typescript-eslint/ban-types stopNotebook: Function; } export interface Notebook { data: { annotations: NotebookAnnotations; resources: { requests: { cpu: number; memory: string; storage: string; }; }; started: string; // eslint-disable-next-line @typescript-eslint/no-explicit-any commits?: any; image: string; name: string; status: SessionStatus; url: string; }; logs: { data: LogsData; fetched?: string; fetching: boolean; }; available: boolean; // eslint-disable-next-line @typescript-eslint/no-explicit-any fetched: any; // eslint-disable-next-line @typescript-eslint/no-explicit-any fetching: any; } export interface ProjectMetadata { accessLevel: number; avatarUrl?: string; defaultBranch: string; description: string; externalUrl?: string; lastActivityAt: string; owner?: EntityCreator; pathWithNamespace?: string; path_with_namespace?: string; tagList: string[]; title: string; visibility: "public" | "internal" | "private"; } export interface ProjectStatistics { lfs_objects_size?: number | null | undefined; repository_size?: number | null | undefined; }
/* eslint-disable import/prefer-default-export */ import type { Knex } from "knex"; import type { InteractionStepWithChildren } from "../../../api/interaction-step"; import { r } from "../../models"; import type { CampaignRecord } from "../types"; export const persistInteractionStepNode = async ( campaignId: number, rootInteractionStep: InteractionStepWithChildren, knexTrx: Knex, temporaryIdMap: Record<string, string> = {} ): Promise<number[]> => { let rootStepId = parseInt(rootInteractionStep.id, 10); // Bail on deleted steps -- they will be dealt with by persistInteractionStepTree if (rootInteractionStep.isDeleted) return []; // Update the parent interaction step ID if this step has a reference to a temporary ID // and the parent has since been inserted const { parentInteractionId } = rootInteractionStep; if (parentInteractionId && temporaryIdMap[parentInteractionId]) { rootInteractionStep.parentInteractionId = temporaryIdMap[parentInteractionId]; } const payload = { question: rootInteractionStep.questionText, script_options: rootInteractionStep.scriptOptions, answer_option: rootInteractionStep.answerOption, answer_actions: rootInteractionStep.answerActions }; if (rootInteractionStep.id.indexOf("new") !== -1) { // Insert new interaction steps const [{ id: newId }] = await knexTrx("interaction_step") .insert({ ...payload, parent_interaction_id: rootInteractionStep.parentInteractionId || null, campaign_id: campaignId, is_deleted: false }) .returning("id"); // Update the mapping of temporary IDs temporaryIdMap[rootInteractionStep.id] = newId; rootStepId = newId; } else { // Update the interaction step record await knexTrx("interaction_step") .where({ id: rootInteractionStep.id }) .update(payload) .returning("id"); } // Persist child interaction steps const childStepIds = await Promise.all( rootInteractionStep.interactionSteps.map((childStep) => persistInteractionStepNode(campaignId, childStep, knexTrx, temporaryIdMap) ) ).then((childResults) => childResults.reduce((acc, childIds) => acc.concat(childIds), []) ); return childStepIds.concat([rootStepId]); }; export const persistInteractionStepTree = async ( campaignId: number, rootInteractionStep: InteractionStepWithChildren, origCampaignRecord: Pick<CampaignRecord, "is_started">, knexTrx?: Knex, temporaryIdMap: Record<string, string> = {} ): Promise<void> => { if (!knexTrx) { return r.knex.transaction((trx) => persistInteractionStepTree( campaignId, rootInteractionStep, origCampaignRecord, trx, temporaryIdMap ) ); } const stepIds: number[] = await persistInteractionStepNode( campaignId, rootInteractionStep, knexTrx, temporaryIdMap ); const delQuery = knexTrx.raw( ` with steps_to_delete as ( select id, (exists(select 1 from question_response where interaction_step_id = ins.id) or exists(select 1 from all_external_sync_question_response_configuration where interaction_step_id = ins.id) ) for_update from interaction_step ins where campaign_id = ? and id <> all (?) ), delete_steps as ( delete from interaction_step ins using steps_to_delete del where ins.id = del.id and not for_update returning * ), update_steps as ( update interaction_step ins set is_deleted = true from steps_to_delete del where ins.id = del.id and for_update returning * ) select count(*) from delete_steps union select count(*) from update_steps `, [campaignId, stepIds] ); await delQuery; };
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale"> <meta name="description" content="An article about lorem ipsum"> <link rel="apple-touch-icon" href="icon.png"> <title> Project no. 1 | Article</title> <link href="https://fonts.googleapis.com/css2?family=Heebo:wght@100;400;700&family=Merriweather:wght@300;400;900&display=swap" rel="stylesheet"> <link rel="stylesheet" href="reset.css" /> <link rel="stylesheet" href="style.css" /> </head> <body> <div class="container"> <header class="header-main"> <div class="wrapper"> <section class="logo"> <img src="assets/icons/logo.png" alt="webpage logo" width="20px"> <h1>Project</h1> </section> <nav > <ul class="nav-horizontal"> <li> <a href="landing.html">Home</a> </li> <li> <a href="#">Categories</a> </li> <li> <a href="#">Contact</a> </li> <li> <button aria-label="Click to search"><img class="icon" src="assets/images/search.png" alt="a magnifying glass depicting search" /></button> </li> </ul> </nav> </div> </header> <main> <article class="article-one"> <header class="article-header"> <div class="wrapper"> <h1>Article about Lorem Ipsum</h1> <a href="#" class="category">Info</a> <div class="article-info"> <img src="assets/images/profilepicture.png" width="50px" /> <a href="#" rel="author">John Doe</a> <time datatime="2022-02-04">2022/02/04</time> </div> </div> </header> <div class="article-body wrapper"> <h2>What is Lorem ipsum?</h2> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. </p> <h3>Why do we use it?</h3> <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. </p> <h4>What you need to know about lorem ipsum</h4> <p> There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. </p> </div> </article> </main> <footer class="footer-main"> <div class="wrapper"> <p>&copy; Copyright 2023 Project</p> <nav class="nav-horizontal"> <a href="#">Privacy Policy</a> <a href="#">Terms & Condition</a> </nav> <section> <a class="icon" href="https://www.twitter.com" aria-label="Follow Us On Twitter" target="_blank"> <img src="assets/icons/twitter.png" alt="twitter logo" width="20px" /> </a> <a class="icon" href="https://www.facebook.com" aria-label="Befriend Us On Facebook" target="_blank"> <img src="assets/icons/facebook.png" alt="facebook logo" width="20px" /> </a> <a class="icon" href="https://www.instagram.com" aria-label="Follow Us On Instagram" target="_blank"> <img src="assets/icons/instagram.png" alt="instagram logo" width="20px" /> </a> </section> </div> </footer> </div><!-- container--> </body> </html>
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:p="http://primefaces.org/ui" xmlns:a="http://xmlns.jcp.org/jsf/passthrough"> <h:head> <meta charset="utf-8" /> <h:outputScript library="js" name="jquery-2.1.4.min.js" /> <h:outputScript library="js" name="bootstrap.js" /> <h:outputScript library="js" name="tablepagination.js" /> <h:outputStylesheet library="css" name="mainstyle.css" /> <h:outputStylesheet library="css" name="bootstrap.css" /> <title>Plataforma de Emprego - Administrador</title> </h:head> <h:body> <ui:composition template="../Layout/layout.xhtml"> <ui:define name="content"> <p:growl for="usermanagement" autoUpdate="true"></p:growl> <h:panelGroup layout="block" class="container" id="container"> <h:panelGroup id="userList" layout="block"> <h:panelGroup layout="block" class="title" id="title"> <h:panelGroup layout="block" class="page-header"> <h:panelGroup layout="block" class="row" id="titlerow"> <h:panelGroup layout="block" class="col-md-8"> <h1>Utilizadores Existentes</h1> </h:panelGroup> <h:panelGroup layout="block" class="col-md-offset-2 col-md-2"> <h:panelGroup layout="block" class="media"> <h:graphicImage styleClass="media-object" library="imgs" name="logocritical.png" style="min-height: 50px; height: 50px;" /> </h:panelGroup> </h:panelGroup> </h:panelGroup> </h:panelGroup> <h:panelGroup layout="block" class="row"> <h:panelGroup layout="block" class="col-md-12"> <h:form prependId="false" id="form"> <h:panelGroup layout="block" class="input-group"> <h:panelGroup styleClass="input-group-btn"> <h:commandButton action="#{userList.clearSearch()}" value="x" styleClass="btn btn-default"> <f:ajax render="userList" /> </h:commandButton> </h:panelGroup> <h:inputText id="campopesquisa" value="#{userList.searchText}" styleClass="form-control" a:placeholder="Pesquisa de utilizadores" onkeypress="searchUser();" /> <h:panelGroup styleClass="input-group-btn"> <h:commandButton id="searchUsersBtn" action="#{userList.doSearch()}" value="Pesquisar" styleClass="btn btn-default"> <f:ajax execute="campopesquisa" render="lista" /> </h:commandButton> </h:panelGroup> </h:panelGroup> </h:form> </h:panelGroup> <h:panelGroup layout="block" class="col-md-offset-6 col-md-3"> <h5 class="bg-danger text-center"> <h:message id="mensagens" styleClass="bg-info" /> </h5> </h:panelGroup> </h:panelGroup> <h:panelGroup layout="block" class="row spacer"></h:panelGroup> <h:form prependId="false" id="listform"> <h:panelGroup layout="block" styleClass="table-responsive"> <p:dataTable id="lista" tableStyleClass="table-condensed newlabeled" var="user" value="#{userList.allUsers}" emptyMessage="Sem resultados..." styleClass="text-center" paginator="true" paginatorPosition="bottom" paginatorTemplate="{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}" rowsPerPageTemplate="5,10,15" rows="5" rowStyleClass="#{user.id eq userID ? 'myRow' : null}"> <p:column headerText="Primeiro Nome" sortBy="#{user.firstName}"> <h:outputText value="#{user.firstName}" /> </p:column> <p:column headerText="Último Nome" sortBy="#{user.lastName}"> <h:outputText value="#{user.lastName}" /> </p:column> <p:column headerText="E-mail" sortBy="#{user.email}"> <h:outputText value="#{user.email}" /> </p:column> <p:column headerText="Nome de Utilizador" sortBy="#{user.username}"> <h:outputText value="#{user.username}" /> </p:column> <p:column headerText="Cargo" sortBy="#{user.roles.get(0).detail}"> <h:outputText value="#{user.roles.get(0).detail}" /> </p:column> <p:column headerText="Eliminar"> <p:commandLink rendered="#{user.id ne userID}" action="#{userList.deleteUser(user)}" update=":userList" process="@this" onclick="if (!confirm('Tem a certeza?')) return false;"> <i class="glyphicon glyphicon-remove-circle"></i> </p:commandLink> </p:column> </p:dataTable> </h:panelGroup> </h:form> <h:panelGroup layout="block" class="page-header"> <h:panelGroup layout="block" class="row"> <h:panelGroup layout="block" class="col-md-5"> <h:form prependId="false" id="addform"> <p:commandLink action="#{userList.doNothing()}" styleClass="btn btn-primary" oncomplete="PF('userWidget').show();" update=":newuserform"> <p:resetInput target=":newuserform"></p:resetInput> <span class="glyphicon glyphicon-plus-sign"></span> Adicionar novo utilizador </p:commandLink> </h:form> </h:panelGroup> </h:panelGroup> </h:panelGroup> </h:panelGroup> </h:panelGroup> </h:panelGroup> <ui:insert name="NewUser"> <ui:include src="newuserdlg.xhtml" /> </ui:insert> <script> function searchUser() { $('#searchUsersBtn').click(); } </script> </ui:define> </ui:composition> </h:body> </html>
import { Injectable, NotFoundException } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Vessel } from './entities/vessel.entity'; import { Repository } from 'typeorm'; import { CreateVesselDto } from './dto/create-vessel.dto'; @Injectable() export class VesselsService { constructor( @InjectRepository(Vessel) private readonly vesselsRepository: Repository<Vessel>, ) {} getAllVessels(queries: any) { return this.vesselsRepository.find({ where: queries }); } getOneVessel(vessel_code: string) { return this.vesselsRepository.findOne({ where: { vessel_code } }); } createVessel(vessel: CreateVesselDto) { const newVessel = this.vesselsRepository.create(vessel); return this.vesselsRepository.save(newVessel); } async updateVessel(vessel_code: string, vessel: CreateVesselDto) { const targetVessel = await this.vesselsRepository.findOne({ where: { vessel_code }, }); if (targetVessel) { Object.assign(targetVessel, vessel); return this.vesselsRepository.save(targetVessel); } else { throw new NotFoundException(); } } }
import { ReactNode, useState } from 'react' import PropTypes from 'prop-types' import { ProSidebar, Menu, MenuItem } from 'react-pro-sidebar' import 'react-pro-sidebar/dist/css/styles.css' import { Box, IconButton } from '@mui/material' import { Link } from 'react-router-dom' import MeetingRoomIcon from '@mui/icons-material/MeetingRoom' import MenuOutlinedIcon from '@mui/icons-material/MenuOutlined' import { useSelector } from 'react-redux' import { RootState } from '@/store' import AccountBoxIcon from '@mui/icons-material/AccountBox' import ButtonLogout from '../Authenticate/ButtonLogout' import ImageLogo from '@/assets/images/logo_web.jpg' import MedicalInformationOutlinedIcon from '@mui/icons-material/MedicalInformationOutlined' import ManageHistoryOutlinedIcon from '@mui/icons-material/ManageHistoryOutlined' // import BarChartIcon from '@mui/icons-material/BarChart' import ViewListOutlinedIcon from '@mui/icons-material/ViewListOutlined' // import FeedbackOutlinedIcon from '@mui/icons-material/FeedbackOutlined' import RecentActorsOutlinedIcon from '@mui/icons-material/RecentActorsOutlined' import SettingsOutlinedIcon from '@mui/icons-material/SettingsOutlined' interface PropsType { title: string to: string icon: ReactNode selected: string setSelected: React.Dispatch<React.SetStateAction<string>> } const Item = ({ title, to, icon, selected, setSelected }: PropsType) => { return ( <MenuItem active={selected === title} onClick={() => setSelected(title)} icon={icon} style={{ color: 'red' }}> <p>{title}</p> <Link to={to} /> </MenuItem> ) } const StaffSidebar = () => { const user = useSelector((state: RootState) => state.auth.user) // const role = useSelector((state: RootState) => state.auth.role) const [isCollapsed, setIsCollapsed] = useState(false) const [selected, setSelected] = useState('Dashboard') return ( <Box sx={{ position: 'fixed', height: '100vh', zIndex: 1000, display: 'flex', flexDirection: 'column', '& .pro-sidebar-inner': { background: `#4f65d2 !important` }, '& .pro-icon-wrapper': { backgroundColor: 'transparent !important' }, '& .pro-menu-item': { color: '#ecc7c7 !important' }, '& .pro-inner-item': { // padding: '5px 35px 5px 20px !important', }, '& .pro-inner-item:hover': { color: '#061207 !important' }, '& .pro-menu-item.active': { color: '#05fa2a !important' } }} > <ProSidebar collapsed={isCollapsed}> <Menu iconShape='square'> {/* Logo and menu icon */} <MenuItem onClick={() => setIsCollapsed(!isCollapsed)} icon={isCollapsed ? <MenuOutlinedIcon /> : undefined} style={{ margin: '10px 0 20px 0' }} > {!isCollapsed && ( <Box display='flex' justifyContent='space-between' alignItems='center' ml='15px'> <p className='font-bold text-gray-100'>CÁN BỘ Y TẾ</p> <IconButton onClick={() => setIsCollapsed(!isCollapsed)}> <MenuOutlinedIcon sx={{ color: '#fff' }} /> </IconButton> </Box> )} </MenuItem> {!isCollapsed && ( <Box mb='25px'> <Box> <p className='py-2 px-4 text-base font-bold text-gray-100 text-center'>QUẢN LÝ Y TẾ HỌC ĐƯỜNG</p> </Box> <Box display='flex' justifyContent='center' alignItems='center'> <Link to='/staff'> <img alt='profile-user' width={100} height={100} // src={user?.avatarUrl || ImageAdminDefault} src={ImageLogo} style={{ cursor: 'pointer', borderRadius: '50%' }} /> </Link> </Box> </Box> )} <Box paddingLeft={isCollapsed ? undefined : '3%'} sx={{ width: '280px' }}> {/* <Item title='Dashboard' to='/admin' icon={<HomeOutlinedIcon />} selected={selected} setSelected={setSelected} /> */} <Item title='Thông tin cá nhân' to='staff-info-personal' icon={<AccountBoxIcon />} selected={selected} setSelected={setSelected} /> <Item title='Danh sách học sinh' to='get-students' icon={<RecentActorsOutlinedIcon />} selected={selected} setSelected={setSelected} /> <Item title='Hồ sơ khám sức khỏe' to='health-records' icon={<MeetingRoomIcon />} selected={selected} setSelected={setSelected} /> <Item title='Danh sách BHYT' to='/health-insurances' icon={<ViewListOutlinedIcon />} selected={selected} setSelected={setSelected} /> <Item title='Kho thuốc của trường' to='view-medicines' icon={<MedicalInformationOutlinedIcon />} selected={selected} setSelected={setSelected} /> <Item title='Lịch sử dùng thuốc' to='history-use-medicines' icon={<ManageHistoryOutlinedIcon />} selected={selected} setSelected={setSelected} /> {/* <Item title='Thống kê' to='staff-statistic' icon={<BarChartIcon />} selected={selected} setSelected={setSelected} /> */} {/* <Item title='Đánh giá và hỏi đáp' to='manage-feedback' icon={<FeedbackOutlinedIcon />} selected={selected} setSelected={setSelected} /> */} <Item title='Đổi mật khẩu' to='/s-change-password' icon={<SettingsOutlinedIcon />} selected={selected} setSelected={setSelected} /> </Box> </Menu> </ProSidebar> {!isCollapsed && ( <Box mt='auto' sx={{ background: '#4f65d2' }}> <Box display='flex' justifyContent='center' alignItems='end'> <img alt='profile-user' width={40} height={40} src={user && user.avatarUrl ? `${user?.avatarUrl}` : ``} // src={ImageAdminDefault} style={{ cursor: 'pointer', borderRadius: '50%' }} /> <p className='pt-2 font-bold text-gray-100 ml-5'>{user?.fullName}</p> </Box> <Box display='flex' justifyContent='center' alignItems='center' mt='1px' mb='30px'> <ButtonLogout /> </Box> </Box> )} </Box> ) } Item.propTypes = { title: PropTypes.string.isRequired, to: PropTypes.string.isRequired, icon: PropTypes.node.isRequired, selected: PropTypes.string.isRequired, setSelected: PropTypes.func.isRequired } export default StaffSidebar
"use client"; import { useState, useEffect } from "react"; import { Task } from "../typescript/types"; // Import your Task type import { timeAgo } from "../hooks/useTimeAgo"; import { Trash } from "@/public/Icon"; import { saveTasksToLocalStorage } from "@/hooks/useLocalStorage"; export const TodoList = () => { // State to manage tasks const [tasks, setTasks] = useState<Task[]>([]); // State to manage filters const [filter, setFilter] = useState<"all" | "active" | "completed">("all"); // Use the middleware to persist tasks to Local Storage whenever tasks change useEffect(() => { saveTasksToLocalStorage(tasks); }, [tasks]); // Function to add a new task const addTask = (text: string) => { const newTask: Task = { id: Date.now().toString(), text, completed: false, createdAt: new Date(), }; setTasks([...tasks, newTask]); }; // Function submit form const handleOnSubmit = (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); const form = e.target as HTMLFormElement; const input = form.querySelector("input") as HTMLInputElement; if (input) { addTask(input.value); input.value = ""; } }; // Toggle task completion const toggleTaskCompletion = (id: string) => { setTasks((prevTasks) => prevTasks?.map((task) => task.id === id ? { ...task, completed: !task.completed } : task ) ); }; // Delete a task const deleteTask = (id: string) => { setTasks((prevTasks) => prevTasks.filter((task) => task.id !== id)); }; // Clear all completed tasks const clearCompletedTasks = () => { setTasks((prevTasks) => prevTasks.filter((task) => !task.completed)); }; // Apply the filter const filteredTasks = tasks?.filter((task) => { if (filter === "all") return true; if (filter === "active") return !task.completed; if (filter === "completed") return task.completed; return false; }); return ( <div> <h1 className=" pb-5 text-center text-2xl">Todo List</h1> {/* Form to add a new task */} <div className="rounded-lg bg-cyan-500 p-5"> <form onSubmit={handleOnSubmit}> <input className="p-2 rounded-lg mr-3 w-96" type="text" placeholder="New task" required /> <button className="bg-cyan-950 text-white p-2 rounded-lg" type="submit" > Add Task </button> </form> </div> {/* Filters */} <div className="grid grid-cols-3 gap-4 my-4 "> <button className="bg-cyan-950 text-white p-2 rounded-lg " onClick={() => setFilter("all")} > All </button> <button className="bg-cyan-950 text-white p-2 rounded-lg" onClick={() => setFilter("active")} > Active </button> <button className="bg-cyan-950 text-white p-2 rounded-lg" onClick={() => setFilter("completed")} > Completed </button> </div> {/* Task list */} <ul> {filteredTasks?.map((task) => ( <li key={task.id} className="border-cyan-500 my-2 p-3 rounded-lg border-2 flex justify-between" > <div> <input className="border-cyan-950 border-4" type="checkbox" checked={task.completed} onChange={() => toggleTaskCompletion(task.id)} /> <span className="pl-3" style={{ textDecoration: task.completed ? "line-through" : "none", }} > {task.text} </span> <span>({timeAgo(new Date(task.createdAt))})</span> </div> <button onClick={() => deleteTask(task.id)}> <Trash color="rgb(190 18 60)" /> </button> </li> ))} </ul> {/* Clear completed tasks */} {filter === "active" ? ( <></> ) : ( <div className="flex justify-end"> <button className="bg-pink-800 text-white p-2 rounded-lg" onClick={clearCompletedTasks} > Clear Completed </button> </div> )} </div> ); }; export default TodoList;
# Data Pipeline and ETL Process ## Project Overview This project aims to establish a robust data pipeline and ETL process on Google Cloud Platform to automate the extraction, transformation, and loading of cricket ranking data from various APIs into Google BigQuery for analysis and visualization in Looker Studio. ## Architecture Diagram ![maquete_projet](docs/maquete_projet.png) ## Components and Workflow ## Data Extraction 1. **Python Script**: A Python script extracts cricket rankings data from APIs and uploads it directly to Google Cloud Storage (GCS). 2. Airflow on Compute Engine: Airflow is set up on a Google Compute Engine instance to orchestrate and automate the Python script execution based on a predefined schedule. ## Data Processing and ETL 1. **Dataflow**: Utilizes a custom template to process and transform data extracted from GCS, parsing and inserting it into BigQuery. ![maquete_projet](docs/Dataflow.PNG) 2. Cloud Functions: An intermediate Cloud Function triggers the Dataflow job automatically whenever new data files are uploaded to GCS. ## Data Storage 1. **BigQuery**: Serves as the centralized data warehouse where transformed data is stored in date-partitioned tables for optimized query performance and cost-efficiency. ![maquete_projet](docs/Bigquery.PNG) ## Data Visualization 1. **Looker Studio**: Used for creating interactive dashboards and reports to visualize and analyze processed data. ![maquete_projet](docs/looker_dashboard.jpg) ## DevOps Integration 1. CI/CD Pipeline: Includes integration with Cloud Source Repositories and GitLab for version control, along with Cloud Build for automated builds and deployments. 2. Terraform: Infrastructure as Code (IaC) is used to define and provision all required cloud resources in a repeatable and consistent manner. ## Goals and Functionalities 1. **Automated Data Ingestion**: Scheduled extractions from APIs to GCS. 2. **Real-time Data Processing**: Immediate processing of new data files through Cloud Functions and Dataflow, ensuring data is timely and relevant. 3. **Scalable Storage Solutions**: Use of BigQuery for scalable and efficient data storage. 4. **Seamless DevOps Practices**: Implementation of a CI/CD pipeline to streamline updates and deployments of the pipeline components. 5. **Governance and Best Practices**: Adoption of best practices in cloud resource management and data governance.
<?php namespace App\Notifications; use Illuminate\Bus\Queueable; use Illuminate\Notifications\Notification; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Support\Facades\Auth; class LikedComment extends Notification { use Queueable; /** * Create a new notification instance. * * @return void * */ protected $post_id; protected $comment_id; public function __construct($post_id,$comment_id) { $this->post_id = $post_id; $this->comment_id = $comment_id; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { return ['database']; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { return (new MailMessage) ->line('The introduction to the notification.') ->action('Notification Action', url('/')) ->line('Thank you for using our application!'); } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ public function toArray($notifiable) { return [ 'message' => 'Your comment is liked by: ', 'post_id' => $this->post_id, 'comment_id' => $this->comment_id, 'user_id' => Auth::id(), 'user_name' => Auth::user()->name, ]; } }
#Compiling the model. model.compile(optimizer="adam", loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=["accuracy"]) #Run it with 25 Epochs history = model.fit(train_images, train_labels, epochs=25, validation_data=(test_images, test_labels)) #CHecking the model via graphs plt.plot(history.history["accuracy"], label="accuracy") plt.plot(history.history["val_accuracy"], label="val_accuracy") plt.xlabel("Epoch") plt.ylabel("Accuracy") plt.ylim([0.5, 1]) plt.legend(loc="lower right") test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2) plt.plot(history.history['loss'], label='training loss') plt.plot(history.history['val_loss'], label='validation loss') plt.title('Training and Validation Loss Curves') plt.xlabel('Epoch') plt.ylabel('Loss') plt.legend() plt.show()
import { ExtractJwt, Strategy } from 'passport-jwt'; import { Injectable, UnauthorizedException } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { PassportStrategy } from '@nestjs/passport'; import { User } from '@prisma/client'; import { PrismaService } from '../../../prisma/prisma.service'; import { JwtPayload } from '../interfaces/jwt-payload.interface'; @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor( private readonly primaService: PrismaService, configService: ConfigService, ) { super({ secretOrKey: configService.get('JWT_SECRET'), jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), }); } async validate(payload: JwtPayload): Promise<User> { const { id, email, roles } = payload; const user = await this.primaService.user.findUnique({ where: { id, email, roles: { equals: roles, }, }, }); if (!user) throw new UnauthorizedException('Token is not valid'); if (!user.isActive) throw new UnauthorizedException('User is not active'); return user; } }
import React from 'react' import { useSelector, useDispatch } from 'react-redux' import { decrement, increment, incrementByAmount } from './counterSlice' export function Counter() { const count = useSelector((state) => state.counter.value) const dispatch = useDispatch() return ( <div> <div> <button aria-label="Increment value" onClick={() => dispatch(increment())} > + </button> {count} <button aria-label="Decrement value" onClick={() => dispatch(decrement())} > - </button> <button aria-label="Increment value" onClick={() => dispatch(incrementByAmount(5))} > Increment By 5 </button> </div> </div> ) }
#include <stdio.h> #include <stdlib.h> // atoi, srandom, random #include <unistd.h> #include <termcap.h> #include <sys/shm.h> #include <sys/sem.h> #include <sys/types.h> #include <time.h> #include <sys/ipc.h> #define DEAD '.' #define ALIVE 'o' #define DYING '+' #define BLINKER 0 #define TOAD 1 #define BEACON 2 #define PULSAR 3 #define PENTADECATHLON 4 #define RANDOM 5 #define NLINES_RANDOM 50 #define NCOLUMNS_RANDOM 200 unsigned int GLOBAL_nlines, GLOBAL_ncolumns; char *GLOBAL_grid_A, *GLOBAL_grid_B; // definition of number of children #define NWORKERS 25 short create_children; int shmid_kill_children, *kill_children; int ret_children; // shared memories and parent semaphore variables int shmid_grid_A, shmid_grid_B, semid_parent; struct sembuf sop_parent[1]; struct sembuf sop_children[1]; union semun { int val; } arg; // children semaphore variables int semid_children; // cell range definitions typedef struct { int core; int offset; } cell_range; int extra, std, shmid_grid_cells; cell_range *grid_cells; // -1 for INFINITEhar **grid, // #define NITERS -1 #define NITERS 2000 // children's pids array pid_t children_pids[NWORKERS]; void clearScreen() { char buf[1024]; char *str; tgetent(buf, getenv("TERM")); str = tgetstr("cl", NULL); fputs(str, stdout); } void gridShow(char *grid) { // shows the grid in the screen, one grid line per screen line; // do not forget to call clearScreen before calling gridShow clearScreen(); char *ptr; int i = 0; for (ptr = grid; ptr <= grid + ((GLOBAL_nlines * GLOBAL_ncolumns) - 1); ptr++) { printf("%c", *ptr); if (i % GLOBAL_ncolumns == GLOBAL_ncolumns - 1) { putchar('\n'); } i++; } } void defineDimensions(int pattern) { // define number of lines (GLOBAL_nlines) and columns (GLOBAL_coluns) // of the grids, depending on the pattern (BLINKER, TOAD, ..., RANDOM); // for the specific number of lines and columns of each pattern see // https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life ; // if pattern is RANDOM you must use NLINES_RANDOM and NCOLUMNS_RANDOM switch (pattern) { case 0: GLOBAL_nlines = 5; GLOBAL_ncolumns = 5; break; case 1: GLOBAL_nlines = 6; GLOBAL_ncolumns = 6; break; case 2: GLOBAL_nlines = 6; GLOBAL_ncolumns = 6; break; case 3: GLOBAL_nlines = 17; GLOBAL_ncolumns = 17; break; case 4: GLOBAL_nlines = 18; GLOBAL_ncolumns = 11; break; case 5: GLOBAL_nlines = NLINES_RANDOM; GLOBAL_ncolumns = NCOLUMNS_RANDOM; break; default: printf("!!! ERROR : INVALID PATTERN !!!\n"); exit(404); break; } extra = (GLOBAL_nlines * GLOBAL_ncolumns) % NWORKERS; std = (GLOBAL_nlines * GLOBAL_ncolumns - extra) / NWORKERS; shmid_grid_cells = shmget(IPC_PRIVATE, NWORKERS * sizeof(cell_range), 00600); grid_cells = (cell_range *)shmat(shmid_grid_cells, NULL, 0); // first position of array definition grid_cells[0].core = 0; grid_cells[0].offset = std; if (extra > 0) { grid_cells[0].offset++; extra--; } // definition of NWORKERS - 1 positions of the array for (int i = 1; i < NWORKERS; i++) { grid_cells[i].core = grid_cells[i - 1].core + grid_cells[i - 1].offset; grid_cells[i].offset = std; if (extra > 0) { grid_cells[i].offset++; extra--; } } } void gridInit(char **grid, int pattern) { srand(time(NULL)); // initializes the starting grid depending on pattern (BLINKER,...); // for the initial state (dead/alive) of each cell see // https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life ; // if pattern is RANDOM you must define the state of the grid cells // in a random way, ensuring only a fraction of 10% are alive cells char *ptr; for (ptr = *grid; ptr <= *grid + ((GLOBAL_nlines * GLOBAL_ncolumns) - 1); ptr++) { *ptr = DEAD; } if (pattern == 5) { int num_alive = 0; while (num_alive < ((GLOBAL_nlines * GLOBAL_ncolumns) / 10)) { ptr = *grid + (rand() % (GLOBAL_nlines * GLOBAL_ncolumns)); if (*ptr == DEAD) { *ptr = ALIVE; num_alive++; } } } else { FILE *fp; int buffer; switch (pattern) { case 0: fp = fopen("./patterns/BLINKER.bin", "rb"); break; case 1: fp = fopen("./patterns/TOAD.bin", "rb"); break; case 2: fp = fopen("./patterns/BEACON.bin", "rb"); break; case 3: fp = fopen("./patterns/PULSAR.bin", "rb"); break; case 4: fp = fopen("./patterns/PENTADECATHLON.bin", "rb"); break; default: printf("!!! ERROR : INVALID PATTERN !!!\n"); exit(404); break; } if (fp == NULL) { printf("!!! ERROR : MISSING IMPORTANT FILE (%d)!!!\n", pattern); exit(410); } while (fread(&buffer, sizeof(int), 1, fp) == 1) { *(*grid + buffer) = ALIVE; } fclose(fp); } } void gridEvolve(char *current, char *next) { // generates the next grid depending on the content of the current grid, // by applying the game of life rules to each cell of the current grid int k, j, border_north = 0, border_east = 0, border_south = 0, border_west = 0, n_neighbours = 0; pid_t parent_pid = getpid(); // unblock every children for (k = 0; k < NWORKERS; k++) { sop_children->sem_num = k; sop_children->sem_op = 1; semop(semid_children, sop_children, 1); } for (j = 0; j < NWORKERS; j++) { if (parent_pid == getpid() && create_children-- > 0) { // create children only if is the parent and if there are children to be created ret_children = fork(); } if (ret_children == 0) { // child // calculate his own portion of the grid, defined by grid_cells char *aux; do { sop_children->sem_num = j; sop_children->sem_op = -1; semop(semid_children, sop_children, 1); // block i-child for (int i = grid_cells[j].core; i < (grid_cells[j].core + grid_cells[j].offset); i++) { border_north = i < GLOBAL_ncolumns ? 1 : 0; border_east = i % GLOBAL_ncolumns == GLOBAL_ncolumns - 1 ? 1 : 0; border_south = i >= GLOBAL_ncolumns * (GLOBAL_nlines - 1) ? 1 : 0; border_west = i % GLOBAL_ncolumns == 0 ? 1 : 0; if (!border_north && !border_west) { // avalia o vizinho NW if (*(current + (i - GLOBAL_ncolumns - 1)) != DEAD) { n_neighbours++; } } if (!border_north) { // avalia o vizinho N if (*(current + (i - GLOBAL_ncolumns)) != DEAD) { n_neighbours++; } } if (!border_north && !border_east) { // avalia o vizinho NE if (*(current + (i - GLOBAL_ncolumns + 1)) != DEAD) { n_neighbours++; } } if (!border_west) { // avalia o vizinho W if (*(current + (i - 1)) != DEAD) { n_neighbours++; } } if (!border_east) { // avalia o vizinho E if (*(current + (i + 1)) != DEAD) { n_neighbours++; } } if (!border_south && !border_west) { // avalia o vizinho SW if (*(current + (i + GLOBAL_ncolumns - 1)) != DEAD) { n_neighbours++; } } if (!border_south) { // avalia o vizinho S if (*(current + (i + GLOBAL_ncolumns)) != DEAD) { n_neighbours++; } } if (!border_south && !border_east) { // avalia o vizinho SE if (*(current + (i + GLOBAL_ncolumns + 1)) != DEAD) { n_neighbours++; } } switch (*(current + i)) { case ALIVE: *(next + i) = DYING; break; case DYING: if ((n_neighbours == 2) || (n_neighbours == 3)) { *(next + i) = DYING; } else { *(next + i) = DEAD; } break; case DEAD: if (n_neighbours == 3) { *(next + i) = ALIVE; } else { *(next + i) = DEAD; } break; default: printf("!!! ERROR : INVALID CELL STATE !!!\n"); exit(406); break; } n_neighbours = 0; } sop_parent->sem_op = -1; semop(semid_parent, sop_parent, 1); // decrement parent semaphore aux = current; current = next; next = aux; } while ((*kill_children) == 0); exit(0); } } sop_parent->sem_op = 0; semop(semid_parent, sop_parent, 1); // block parent until every child ends } int gridCompare(char *gridA, char *gridB) { // compares the two input grids, returning 0 if they are equal; // usefull to compare the current and the next grid to see if they // are equal, in which case the game converged to a final state int i, ret = 0; for (i = 0; i < (GLOBAL_nlines * GLOBAL_ncolumns); i++) { if (*(gridA + i) != *(gridB + i)) { ret++; } } return ret; } int main(int argc, char **argv) { // define initial pattern depending on the command line parameters if (NWORKERS <= 0) { printf("!!! ERROR : NO WORKERS !!!\n"); exit(405); } if (argc <= 1) { printf("!!! ERROR : NOT ENOUGH ARGUMENTS (%d)!!!\n", argc); exit(407); } if (argc > 2) { printf("!!! ERROR : TOO MANY ARGUMENTS !!!\n"); exit(408); } int pattern = atoi(argv[1]), niters = 0; // parent semaphore initialization (starts with NWORKERS) semid_parent = semget(IPC_PRIVATE, 1, 00600); arg.val = NWORKERS; sop_parent->sem_flg = 0; sop_parent->sem_num = 0; semctl(semid_parent, 0, SETVAL, arg); // children semaphores initialization semid_children = semget(IPC_PRIVATE, NWORKERS, 00600); arg.val = 0; sop_children->sem_flg = 0; for (int i = 0; i < NWORKERS; i++) semctl(semid_children, i, SETVAL, arg); // creation of children create_children = NWORKERS; shmid_kill_children = shmget(IPC_PRIVATE, sizeof(int), 00600); kill_children = (int *)shmat(shmid_kill_children, NULL, 0); *kill_children = 0; // define grids dimensions (GLOBAL_nlines and GLOBAL_ncolumns) depending on // pattern defineDimensions(pattern); if (GLOBAL_nlines * GLOBAL_ncolumns < NWORKERS) { printf("!!! ERROR : MORE WORKERS THAN CELLS (%d useless workers) !!!\n", NWORKERS - (GLOBAL_nlines * GLOBAL_ncolumns)); exit(409); } // alloc the working grids (GLOBAL_grid_A and GLOBAL_grid_B) in shared memory shmid_grid_A = shmget(IPC_PRIVATE, (GLOBAL_nlines * GLOBAL_ncolumns * sizeof(char)), 0666); GLOBAL_grid_A = (char *)shmat(shmid_grid_A, NULL, 0); shmid_grid_B = shmget(IPC_PRIVATE, (GLOBAL_nlines * GLOBAL_ncolumns * sizeof(char)), 0666); GLOBAL_grid_B = (char *)shmat(shmid_grid_B, NULL, 0); gridInit(&GLOBAL_grid_A, pattern); gridInit(&GLOBAL_grid_B, pattern); // alloc the start grid (start) in dynamic memory char *start = (char *)malloc(GLOBAL_nlines * GLOBAL_ncolumns * sizeof(char)); gridInit(&start, pattern); // initialize the seed grid (GLOBAL_grid_A) depending on the chosen pattern // main loop: WHILE (maximum number of iterations not reached AND convergence // not achieved) // show current generation // define next generation // if (convergence not achieved) // swap pointers between current and next generation char *aux, *current = GLOBAL_grid_A, *next = GLOBAL_grid_B; do { gridShow(current); gridEvolve(current, next); if (gridCompare(next, start) == 0) { gridShow(next); break; } aux = current; current = next; next = aux; niters++; sop_parent->sem_op = NWORKERS; semop(semid_parent, sop_parent, 1); // set again the semaphore to NWORKERS } while (niters != NITERS); printf("\nFINISHED all iterations\n"); *kill_children = 1; // unblock every children for (int i = 0; i < NWORKERS; i++) { sop_children->sem_num = i; sop_children->sem_op = 1; semop(semid_children, sop_children, 1); } // free shared and dynamic memory shmctl(shmid_grid_A, IPC_RMID, 0); shmctl(shmid_grid_B, IPC_RMID, 0); shmctl(shmid_grid_cells, IPC_RMID, 0); shmctl(shmid_kill_children, IPC_RMID, 0); semctl(semid_parent, 0, IPC_RMID, NULL); semctl(semid_children, 0, IPC_RMID, NULL); free(start); return (0); }
package tarea_Aprendizaje_03; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; // Crea un programa en Java que lea un fichero de caracteres y // pida por teclado qué vocal se quiere contar en el fichero. // El programa devolverá el número de veces que se repite esa vocal. import javax.swing.JOptionPane; public class ContarVocal { public static void main(String[] args) { // Solicitar al usuario que introduzca una vocal a buscar. String vocalUsuario = JOptionPane.showInputDialog("¿Qué vocal quieres buscar?"); // Validar que la entrada del usuario sea una única vocal. if (vocalUsuario == null || vocalUsuario.length() != 1 || "aeiouAEIOU".indexOf(vocalUsuario.charAt(0)) == -1) { JOptionPane.showConfirmDialog(null, "No has introducido una única vocal."); return; // Terminar programa si la entrada no es válida. } // Convertir la entrada del usuario (String) a un carácter (char) para la comparación. char vocalElegida = vocalUsuario.charAt(0); // Definir la ruta del archivo y crear un objeto File. File ficheroLeer = new File("src" + File.separator + "tarea_Aprendizaje_03" + File.separator + "caracteres.txt"); try (BufferedReader buffer = new BufferedReader(new FileReader(ficheroLeer))) { // Inicializar el contador de vocales y una variable para almacenar cada línea del archivo. int contador = 0; String linea; // Leer el archivo línea por línea. while((linea = buffer.readLine()) != null ) { // Aumentar el contador por la cantidad de vocales encontradas en la línea actual. contador += contarVocales(linea, vocalElegida); } // Mostrar el resultado al usuario. JOptionPane.showMessageDialog(null, "La vocal " + vocalElegida + " aparece " + contador + " veces en el fichero."); } catch (IOException e) { // Manejar posibles excepciones al leer el archivo y mostrar un mensaje de error al usuario. JOptionPane.showConfirmDialog(null,"Error: " + e.getMessage()); } } // Método para contar la cantidad de veces que aparece una vocal específica en una línea de texto. public static int contarVocales(String linea, char vocal) { int contador = 0; // Convertir la línea a un array de caracteres y recorrer cada carácter. for (char caracter : linea.toCharArray()) { // Si el carácter actual es la vocal que estamos buscando, aumentar el contador. if (caracter == vocal) { contador++; } } // Devolver el total de vocales encontradas en la línea. return contador; } }
import { Col, Input, Row, Select } from "antd"; import { observer } from "mobx-react-lite"; import { SearchOutlined } from "@ant-design/icons"; import { useStore } from "../Stores/StoreProvider"; import { Tag } from "../Types/Meal"; import "./SearchBar.scss"; import { useEffect } from "react"; import { RouteNames } from "../Types/Shared"; interface ISearchBarProps { route: RouteNames; } const SearchBar = (props: ISearchBarProps) => { const { mealStore, tagStore } = useStore(); useEffect(() => { mealStore.clearFilters(); tagStore.clearFilters(); }, [mealStore, tagStore]); const handleTextFilter = (event: React.ChangeEvent<HTMLInputElement>) => { const value = event.target.value; switch (props.route) { case "Meals": mealStore.setTextFilter(value); mealStore.filterMeals(); break; case "Tags": tagStore.setTextFilter(value); tagStore.filterTags(); break; default: break; } }; const handleTagFilter = (value: any) => { switch (props.route) { case "Meals": mealStore.setTagFilter(value); mealStore.filterMeals(); break; case "Tags": tagStore.setTagFilter(value); tagStore.filterTags(); break; default: break; } }; return ( <Row className="searchBarRow" gutter={[16, 16]}> <Col className="searchBarColumn"> <Input placeholder="Search" allowClear suffix={<SearchOutlined style={{ color: "grey" }} />} onChange={handleTextFilter} /> </Col> {props.route === "Meals" ? ( <Col className="searchBarColumn"> <Select mode="multiple" maxTagCount="responsive" placeholder="Tag" allowClear onChange={handleTagFilter} options={tagStore.tags.map((tag: Tag) => { return { value: tag.id, label: tag.name, }; })} ></Select> </Col> ) : null} </Row> ); }; export default observer(SearchBar);
import TOSBase, { TosResponse } from '../base'; import { DEFAULT_PART_SIZE, isCancelError, readAllDataToBuffer, } from '../../utils'; import * as fsp from '../../nodejs/fs-promises'; import { DataTransferStatus, DataTransferType } from '../../interface'; import headObject, { HeadObjectInput, HeadObjectOutput } from './headObject'; import { CancelToken } from 'axios'; import { Stats } from 'fs'; import path from 'path'; import TosClientError from '../../TosClientError'; import { getObjectV2, GetObjectV2Output } from './getObject'; import TosServerError from '../../TosServerError'; import { CancelError } from '../../CancelError'; import { IRateLimiter } from '../../rate-limiter'; import { CRC } from '../../universal/crc'; export interface DownloadFileCheckpointRecord { bucket: string; key: string; version_id?: string; part_size: number; object_info: { etag: string; hash_crc64ecma: string; object_size: number; last_modified: string; }; file_info: { file_path: string; temp_file_path: string; }; parts_info: DownloadFileCheckpointRecordPartInfo[]; } export interface DownloadFileCheckpointRecordPartInfo { part_number: number; range_start: number; range_end: number; hash_crc64ecma: string; is_completed: boolean; } export interface DownloadFileInput extends HeadObjectInput { filePath: string; /** * default is 20 MB * * unit: B */ partSize?: number; /** * the number of request to parallel upload part,default value is 1 */ taskNum?: number; /** * if checkpoint is a string and point to a exist file, * the checkpoint record will recover from this file. * * if checkpoint is a string and point to a directory, * the checkpoint will be auto generated, * and its name is `{bucketName}_{objectName}.{uploadId}`. */ checkpoint?: string | DownloadFileCheckpointRecord; dataTransferStatusChange?: (status: DataTransferStatus) => void; /** * the feature of pause and continue uploading */ downloadEventChange?: (event: DownloadEvent) => void; /** * the simple progress feature * percent is [0, 1] */ progress?: ( percent: number, checkpoint: DownloadFileCheckpointRecord ) => void; /** * cancel this upload progress */ cancelToken?: CancelToken; /** * unit: bit/s * server side traffic limit **/ trafficLimit?: number; /** * only works for nodejs environment */ rateLimiter?: IRateLimiter; } export interface DownloadFileOutput extends HeadObjectOutput {} export interface DownloadEvent { type: DownloadEventType; err?: Error; bucket: string; key: string; versionId?: string; filePath: string; checkpointFile?: string; downloadPartInfo?: DownloadPartInfo; } export interface DownloadPartInfo { partNumber: number; rangeStart: number; rangeEnd: number; } export enum DownloadEventType { CreateTempFileSucceed = 1, CreateTempFileFailed, DownloadPartSucceed, DownloadPartFailed, DownloadPartAborted, RenameTempFileSucceed, RenameTempFileFailed, } interface CheckpointRichInfo { filePath?: string | undefined; filePathIsPlaceholder?: boolean; record?: DownloadFileCheckpointRecord; } interface Task { partSize: number; offset: number; partNumber: number; } const CHECKPOINT_FILE_NAME_PLACEHOLDER = '@@checkpoint-file-placeholder@@'; const ABORT_ERROR_STATUS_CODE = [403, 404, 405]; export async function downloadFile( this: TOSBase, input: DownloadFileInput ): Promise<TosResponse<DownloadFileOutput>> { if (process.env.TARGET_ENVIRONMENT === 'browser') { throw new TosClientError( '`downloadFile` is not supported in browser environment' ); } const { cancelToken, versionId } = input; const isCancel = () => cancelToken && !!cancelToken.reason; const headObjectRes = await headObject.call(this, { bucket: input.bucket, key: input.key, versionId, }); const { data: objectStats } = headObjectRes; const etag = objectStats['etag']; const objectSize = +objectStats['content-length']; const checkpointRichInfo = await (async (): Promise<CheckpointRichInfo> => { if (process.env.TARGET_ENVIRONMENT === 'node') { if (typeof input.checkpoint === 'string') { const { checkpoint } = input; // file doesn't exist when stat is null let checkpointStat: Stats | null = null; try { checkpointStat = await fsp.stat(checkpoint); } catch (_err) { // TODO: remove any const err = _err as any; if (err.code === 'ENOENT') { // file doesn't exist } else { throw err; } } const isDirectory = (() => { if (checkpointStat) { return checkpointStat.isDirectory(); } return checkpoint.endsWith('/'); })(); // filePath will generated by uploadId, use placeholder temporarily const filePath = isDirectory ? path.resolve(checkpoint, CHECKPOINT_FILE_NAME_PLACEHOLDER) : checkpoint; const dirPath = path.dirname(filePath); // ensure directory exist await fsp.mkdir(dirPath, { recursive: true }); if (isDirectory) { return { filePath, filePathIsPlaceholder: true, }; } return { filePath, filePathIsPlaceholder: false, // filePath is json file // TODO: validate json schema record: checkpointStat ? require(filePath) : undefined, }; } } if (typeof input.checkpoint === 'object') { return { record: input.checkpoint, }; } return {}; })(); // check if file info is matched await (async () => { if (checkpointRichInfo.record?.object_info) { const { last_modified, object_size } = checkpointRichInfo.record?.object_info; if ( // TODO: `last-modified` aligns to number objectStats['last-modified'] !== last_modified || objectSize !== object_size ) { console.warn( `The file has been modified since ${new Date( last_modified )}, so the checkpoint file is invalid, and specified object will be downloaded again.` ); delete checkpointRichInfo.record; } } })(); const partSize = input.partSize || checkpointRichInfo.record?.part_size || DEFAULT_PART_SIZE; // check partSize is matched if ( checkpointRichInfo.record && checkpointRichInfo.record.part_size !== partSize ) { console.warn( 'The partSize param does not equal the partSize in checkpoint file, ' + 'so the checkpoint file is invalid, and specified object will be downloaded again.' ); delete checkpointRichInfo.record; } let bucket = input.bucket || this.opts.bucket || ''; const key = input.key; let tasks: Task[] = []; const allTasks: Task[] = getAllTasks(objectSize, partSize); const initConsumedBytes = (checkpointRichInfo.record?.parts_info || []) .filter((it) => it.is_completed) .reduce((prev, it) => prev + (it.range_end - it.range_start + 1), 0); // recorded tasks const recordedTasks = checkpointRichInfo.record?.parts_info || []; const recordedTaskMap: Map<number, DownloadFileCheckpointRecordPartInfo> = new Map(); recordedTasks.forEach((it) => recordedTaskMap.set(it.part_number, it)); const filePath = await (async () => { let filePathStats: Stats | null = null; try { filePathStats = await fsp.stat(input.filePath); } catch (_err) { const err = _err as any; if (err.code === 'ENOENT') { // file doesn't exist } else { throw err; } } const isDirectory = (() => { if (filePathStats) { return filePathStats.isDirectory(); } return input.filePath.endsWith('/'); })(); const filePath = isDirectory ? path.resolve(input.filePath, key) : input.filePath; const dirPath = path.dirname(filePath); await fsp.mkdir(dirPath, { recursive: true }); return filePath; })(); // TODO: there can check temp fileSize const [tempFilePath, isExist] = await (async () => { const tempFilePath = filePath + '.temp'; let isExist = true; try { await fsp.stat(input.filePath); } catch (_err) { const err = _err as any; if (err.code === 'ENOENT') { isExist = false; // file doesn't exist } else { throw err; } } return [tempFilePath, isExist]; })(); if (checkpointRichInfo.record) { if (!isExist) { console.warn( "The temp file doesn't not exist " + 'so the checkpoint file is invalid, and specified object will be downloaded again.' ); delete checkpointRichInfo.record; } } let tempFileFd = -1; const nextEnsureCloseFd = async () => { const getCheckpointContent = () => { const checkpointContent: DownloadFileCheckpointRecord = { bucket, key, version_id: versionId, part_size: partSize, parts_info: recordedTasks, file_info: { file_path: filePath, temp_file_path: tempFilePath, }, object_info: { last_modified: objectStats['last-modified'], etag: etag, hash_crc64ecma: objectStats['x-tos-hash-crc64ecma'] || '', object_size: objectSize, }, }; return checkpointContent; }; const triggerDownloadEvent = ( e: Omit< DownloadEvent, 'bucket' | 'versionId' | 'key' | 'checkpointFile' | 'filePath' > ) => { if (!input.downloadEventChange) { return; } const event: DownloadEvent = { bucket, versionId, key, filePath, ...e, }; if (checkpointRichInfo.filePath) { event.checkpointFile = checkpointRichInfo.filePath; } input.downloadEventChange(event); }; let consumedBytesForProgress = initConsumedBytes; enum TriggerProgressEventType { downloadPartSucceed = 1, renameTempFileSucceed = 2, } const triggerProgressEvent = (type: TriggerProgressEventType) => { if (!input.progress) { return; } let ret = 0; if (type === TriggerProgressEventType.renameTempFileSucceed) { ret = 1; } else { ret = !objectSize ? 1 : consumedBytesForProgress / objectSize; } if ( consumedBytesForProgress === objectSize && type === TriggerProgressEventType.downloadPartSucceed ) { // 100% 仅在 complete 后处理,以便 100% 可以拉取到新对象 } else { input.progress(ret, getCheckpointContent()); } }; let consumedBytes = initConsumedBytes; const { dataTransferStatusChange } = input; const triggerDataTransfer = ( type: DataTransferType, rwOnceBytes: number = 0 ) => { if (!dataTransferStatusChange) { return; } consumedBytes += rwOnceBytes; dataTransferStatusChange?.({ type, rwOnceBytes, consumedBytes, totalBytes: objectSize, }); }; const writeCheckpointFile = async () => { if ( process.env.TARGET_ENVIRONMENT === 'node' && checkpointRichInfo.filePath ) { const content = JSON.stringify(getCheckpointContent(), null, 2); const dirPath = path.dirname(checkpointRichInfo.filePath); // ensure directory exist await fsp.mkdir(dirPath, { recursive: true, }); await fsp.writeFile(checkpointRichInfo.filePath, content, 'utf-8'); } }; const rmCheckpointFile = async () => { if ( process.env.TARGET_ENVIRONMENT === 'node' && checkpointRichInfo.filePath ) { await fsp.rm(checkpointRichInfo.filePath).catch((err: any) => { // eat err console.warn( 'remove checkpoint file failure, you can remove it by hand.\n', `checkpoint file path: ${checkpointRichInfo.filePath}\n`, err.message ); }); } }; /** * * @param task one part task * @param downloadPartRes upload part failed if `downloadPartRes` is Error */ const updateAfterDownloadPart = async ( task: Task, downloadPartRes: GetObjectV2Output | Error ) => { let existRecordTask = recordedTaskMap.get(task.partNumber); const rangeStart = task.offset; const rangeEnd = Math.min(task.offset + partSize, objectSize - 1); if (!existRecordTask) { existRecordTask = { part_number: task.partNumber, range_start: rangeStart, range_end: rangeEnd, hash_crc64ecma: '', is_completed: false, }; recordedTasks.push(existRecordTask); recordedTaskMap.set(existRecordTask.part_number, existRecordTask); } if (!(downloadPartRes instanceof Error)) { existRecordTask.is_completed = true; } await writeCheckpointFile(); const downloadPartInfo: DownloadPartInfo = { partNumber: existRecordTask.part_number, rangeStart, rangeEnd, }; if (downloadPartRes instanceof Error) { const err = downloadPartRes; let type: DownloadEventType = DownloadEventType.DownloadPartFailed; if (err instanceof TosServerError) { if (ABORT_ERROR_STATUS_CODE.includes(err.statusCode)) { type = DownloadEventType.DownloadPartAborted; } } triggerDownloadEvent({ type, err, downloadPartInfo: downloadPartInfo, }); return; } consumedBytesForProgress += downloadPartInfo.rangeEnd - downloadPartInfo.rangeStart + 1; triggerDownloadEvent({ type: DownloadEventType.DownloadPartSucceed, downloadPartInfo: downloadPartInfo, }); triggerProgressEvent(TriggerProgressEventType.downloadPartSucceed); }; if (checkpointRichInfo.record) { tempFileFd = await fsp.open(input.filePath, 'r+'); bucket = checkpointRichInfo.record.bucket; // checkpoint info exists, so need to calculate remain tasks const uploadedPartSet: Set<number> = new Set( (checkpointRichInfo.record.parts_info || []) .filter((it) => it.is_completed) .map((it) => it.part_number) ); tasks = allTasks.filter((it) => !uploadedPartSet.has(it.partNumber)); } else { try { tempFileFd = await fsp.open(tempFilePath, 'w+'); } catch (_err) { const err = _err as any; triggerDownloadEvent({ type: DownloadEventType.CreateTempFileFailed, err, }); throw err; } if (checkpointRichInfo.filePathIsPlaceholder) { checkpointRichInfo.filePath = checkpointRichInfo.filePath?.replace( `${CHECKPOINT_FILE_NAME_PLACEHOLDER}`, getDefaultCheckpointFilePath(bucket, key, versionId) ); } triggerDownloadEvent({ type: DownloadEventType.CreateTempFileSucceed, }); triggerDataTransfer(DataTransferType.Started); tasks = allTasks; } const handleTasks = async () => { let firstErr: Error | null = null; let index = 0; const crcInstance = new CRC(); // TODO: how to test parallel does work, measure time is not right await Promise.all( Array.from({ length: input.taskNum || 1 }).map(async () => { while (true) { const currentIndex = index++; if (currentIndex >= tasks.length) { return; } const curTask = tasks[currentIndex]; try { const res = await getObjectV2.call(this, { bucket, key, versionId, // support rateLimiter so changed to stream // dataType: 'buffer', headers: { 'if-match': etag, range: `bytes=${curTask.offset}-${Math.min( curTask.offset + curTask.partSize - 1, objectSize - 1 )}`, }, trafficLimit: input.trafficLimit, rateLimiter: input.rateLimiter, }); // 上面的 call 调用,ts 丢失了类型推断 const buffer = await readAllDataToBuffer(res.data.content); // 开启 crc 的时候再计算 if (this.opts.enableCRC) { crcInstance.update(buffer); } await fsp.write( tempFileFd, buffer, 0, buffer.byteLength, curTask.offset ); triggerDataTransfer(DataTransferType.Rw, buffer.byteLength); if (isCancel()) { throw new CancelError('cancel uploadFile'); } await updateAfterDownloadPart(curTask, res.data); } catch (_err) { const err = _err as any; if (isCancelError(err)) { throw err; } if (!firstErr) { firstErr = err; } await updateAfterDownloadPart(curTask, err); } } }) ); // 计算最终的 crc 并比对 const serverCRC64 = headObjectRes.data['x-tos-hash-crc64ecma']; if (this.opts.enableCRC && serverCRC64) { crcInstance.final(); if (!crcInstance.equalsTo(serverCRC64)) { throw new TosClientError( `expect crc64 ${serverCRC64}, actual crc64 ${crcInstance.toString()}` ); } } if (firstErr) { throw firstErr; } }; const handleEmptyObj = async () => {}; objectSize === 0 ? await handleEmptyObj() : await handleTasks(); try { await fsp.rename(tempFilePath, filePath); } catch (_err) { const err = _err as any; triggerDownloadEvent({ type: DownloadEventType.RenameTempFileFailed, err, }); triggerDataTransfer(DataTransferType.Failed); throw err; } triggerDownloadEvent({ type: DownloadEventType.RenameTempFileSucceed, }); triggerProgressEvent(TriggerProgressEventType.renameTempFileSucceed); triggerDataTransfer(DataTransferType.Succeed); await rmCheckpointFile(); return headObjectRes; }; try { return await nextEnsureCloseFd(); } finally { if (tempFileFd >= 0) { await fsp.close(tempFileFd); } } } export default downloadFile; /** * 即使 totalSize 是 0,也需要一个 Part,否则 Server 端会报错 read request body failed */ function getAllTasks(totalSize: number, partSize: number) { const tasks: Task[] = []; for (let i = 0; ; ++i) { const offset = i * partSize; const currPartSize = Math.min(partSize, totalSize - offset); tasks.push({ offset, partSize: currPartSize, partNumber: i + 1, }); if ((i + 1) * partSize >= totalSize) { break; } } return tasks; } function getDefaultCheckpointFilePath( bucket: string, key: string, versionId?: string ) { const originPath = `${bucket}_${key}.${versionId}.json`; const normalizePath = originPath.replace(/[\\/]/g, ''); return normalizePath; }
import 'package:appflowy/mobile/presentation/database/mobile_board_screen.dart'; import 'package:appflowy/mobile/presentation/database/mobile_calendar_screen.dart'; import 'package:appflowy/mobile/presentation/database/mobile_grid_screen.dart'; import 'package:appflowy/mobile/presentation/favorite/mobile_favorite_page.dart'; import 'package:appflowy/mobile/presentation/presentation.dart'; import 'package:appflowy/startup/startup.dart'; import 'package:appflowy/startup/tasks/app_widget.dart'; import 'package:appflowy/user/application/auth/auth_service.dart'; import 'package:appflowy/user/presentation/presentation.dart'; import 'package:appflowy/util/platform_extension.dart'; import 'package:appflowy/workspace/presentation/home/desktop_home_screen.dart'; import 'package:flowy_infra/time/duration.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; GoRouter generateRouter(Widget child) { return GoRouter( navigatorKey: AppGlobals.rootNavKey, initialLocation: '/', routes: [ // Root route is SplashScreen. // It needs LaunchConfiguration as a parameter, so we get it from ApplicationWidget's child. _rootRoute(child), // Routes in both desktop and mobile _signInScreenRoute(), _skipLogInScreenRoute(), _encryptSecretScreenRoute(), _workspaceErrorScreenRoute(), // Desktop only if (!PlatformExtension.isMobile) _desktopHomeScreenRoute(), // Mobile only if (PlatformExtension.isMobile) ...[ // settings _mobileHomeSettingPageRoute(), _mobileSettingPrivacyPolicyPageRoute(), _mobileSettingUserAgreementPageRoute(), // view page _mobileEditorScreenRoute(), _mobileGridScreenRoute(), _mobileBoardScreenRoute(), _mobileCalendarScreenRoute(), // home // MobileHomeSettingPage is outside the bottom navigation bar, thus it is not in the StatefulShellRoute. _mobileHomeScreenWithNavigationBarRoute(), // trash _mobileHomeTrashPageRoute(), ], // Desktop and Mobile GoRoute( path: WorkspaceStartScreen.routeName, pageBuilder: (context, state) { final args = state.extra as Map<String, dynamic>; return CustomTransitionPage( child: WorkspaceStartScreen( userProfile: args[WorkspaceStartScreen.argUserProfile], ), transitionsBuilder: _buildFadeTransition, transitionDuration: _slowDuration, ); }, ), GoRoute( path: SignUpScreen.routeName, pageBuilder: (context, state) { return CustomTransitionPage( child: SignUpScreen( router: getIt<AuthRouter>(), ), transitionsBuilder: _buildFadeTransition, transitionDuration: _slowDuration, ); }, ), ], ); } /// We use StatefulShellRoute to create a StatefulNavigationShell(ScaffoldWithNavBar) to access to multiple pages, and each page retains its own state. StatefulShellRoute _mobileHomeScreenWithNavigationBarRoute() { return StatefulShellRoute.indexedStack( builder: ( BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell, ) { // Return the widget that implements the custom shell (in this case // using a BottomNavigationBar). The StatefulNavigationShell is passed // to be able access the state of the shell and to navigate to other // branches in a stateful way. return MobileBottomNavigationBar(navigationShell: navigationShell); }, branches: <StatefulShellBranch>[ StatefulShellBranch( routes: <RouteBase>[ GoRoute( path: MobileHomeScreen.routeName, builder: (BuildContext context, GoRouterState state) { return const MobileHomeScreen(); }, ), ], ), StatefulShellBranch( routes: <RouteBase>[ GoRoute( path: MobileFavoriteScreen.routeName, builder: (BuildContext context, GoRouterState state) { return const MobileFavoriteScreen(); }, ), ], ), StatefulShellBranch( routes: <RouteBase>[ GoRoute( path: '/d', builder: (BuildContext context, GoRouterState state) => const RootPlaceholderScreen( label: 'Search', detailsPath: '/d/details', ), routes: <RouteBase>[ GoRoute( path: 'details', builder: (BuildContext context, GoRouterState state) => const DetailsPlaceholderScreen( label: 'Search Page details', ), ), ], ), ], ), StatefulShellBranch( routes: <RouteBase>[ GoRoute( path: '/e', builder: (BuildContext context, GoRouterState state) => const RootPlaceholderScreen( label: 'Notification', detailsPath: '/e/details', ), routes: <RouteBase>[ GoRoute( path: 'details', builder: (BuildContext context, GoRouterState state) => const DetailsPlaceholderScreen( label: 'Notification Page details', ), ), ], ), ], ), ], ); } GoRoute _mobileHomeSettingPageRoute() { return GoRoute( parentNavigatorKey: AppGlobals.rootNavKey, path: MobileHomeSettingPage.routeName, pageBuilder: (context, state) { return const MaterialPage(child: MobileHomeSettingPage()); }, ); } GoRoute _mobileSettingPrivacyPolicyPageRoute() { return GoRoute( parentNavigatorKey: AppGlobals.rootNavKey, path: PrivacyPolicyPage.routeName, pageBuilder: (context, state) { return const MaterialPage(child: PrivacyPolicyPage()); }, ); } GoRoute _mobileSettingUserAgreementPageRoute() { return GoRoute( parentNavigatorKey: AppGlobals.rootNavKey, path: UserAgreementPage.routeName, pageBuilder: (context, state) { return const MaterialPage(child: UserAgreementPage()); }, ); } GoRoute _mobileHomeTrashPageRoute() { return GoRoute( parentNavigatorKey: AppGlobals.rootNavKey, path: MobileHomeTrashPage.routeName, pageBuilder: (context, state) { return const MaterialPage(child: MobileHomeTrashPage()); }, ); } GoRoute _desktopHomeScreenRoute() { return GoRoute( path: DesktopHomeScreen.routeName, pageBuilder: (context, state) { return CustomTransitionPage( child: const DesktopHomeScreen(), transitionsBuilder: _buildFadeTransition, transitionDuration: _slowDuration, ); }, ); } GoRoute _workspaceErrorScreenRoute() { return GoRoute( path: WorkspaceErrorScreen.routeName, pageBuilder: (context, state) { final args = state.extra as Map<String, dynamic>; return CustomTransitionPage( child: WorkspaceErrorScreen( error: args[WorkspaceErrorScreen.argError], userFolder: args[WorkspaceErrorScreen.argUserFolder], ), transitionsBuilder: _buildFadeTransition, transitionDuration: _slowDuration, ); }, ); } GoRoute _encryptSecretScreenRoute() { return GoRoute( path: EncryptSecretScreen.routeName, pageBuilder: (context, state) { final args = state.extra as Map<String, dynamic>; return CustomTransitionPage( child: EncryptSecretScreen( user: args[EncryptSecretScreen.argUser], key: args[EncryptSecretScreen.argKey], ), transitionsBuilder: _buildFadeTransition, transitionDuration: _slowDuration, ); }, ); } GoRoute _skipLogInScreenRoute() { return GoRoute( path: SkipLogInScreen.routeName, pageBuilder: (context, state) { return CustomTransitionPage( child: const SkipLogInScreen(), transitionsBuilder: _buildFadeTransition, transitionDuration: _slowDuration, ); }, ); } GoRoute _signInScreenRoute() { return GoRoute( path: SignInScreen.routeName, pageBuilder: (context, state) { return CustomTransitionPage( child: const SignInScreen(), transitionsBuilder: _buildFadeTransition, transitionDuration: _slowDuration, ); }, ); } GoRoute _mobileEditorScreenRoute() { return GoRoute( path: MobileEditorScreen.routeName, pageBuilder: (context, state) { final id = state.uri.queryParameters[MobileEditorScreen.viewId]!; final title = state.uri.queryParameters[MobileEditorScreen.viewTitle]; return MaterialPage( child: MobileEditorScreen( id: id, title: title, ), ); }, ); } GoRoute _mobileGridScreenRoute() { return GoRoute( path: MobileGridScreen.routeName, pageBuilder: (context, state) { final id = state.uri.queryParameters[MobileGridScreen.viewId]!; final title = state.uri.queryParameters[MobileGridScreen.viewTitle]; return MaterialPage( child: MobileGridScreen( id: id, title: title, ), ); }, ); } GoRoute _mobileBoardScreenRoute() { return GoRoute( path: MobileBoardScreen.routeName, pageBuilder: (context, state) { final id = state.uri.queryParameters[MobileBoardScreen.viewId]!; final title = state.uri.queryParameters[MobileBoardScreen.viewTitle]; return MaterialPage( child: MobileBoardScreen( id: id, title: title, ), ); }, ); } GoRoute _mobileCalendarScreenRoute() { return GoRoute( path: MobileCalendarScreen.routeName, pageBuilder: (context, state) { final id = state.uri.queryParameters[MobileCalendarScreen.viewId]!; final title = state.uri.queryParameters[MobileCalendarScreen.viewTitle]!; return MaterialPage( child: MobileCalendarScreen( id: id, title: title, ), ); }, ); } GoRoute _rootRoute(Widget child) { return GoRoute( path: '/', redirect: (context, state) async { // Every time before navigating to splash screen, we check if user is already logged in in desktop. It is used to skip showing splash screen when user just changes apperance settings like theme mode. final userResponse = await getIt<AuthService>().getUser(); final routeName = userResponse.fold( (error) => null, (user) => DesktopHomeScreen.routeName, ); if (routeName != null && !PlatformExtension.isMobile) return routeName; return null; }, // Root route is SplashScreen. // It needs LaunchConfiguration as a parameter, so we get it from ApplicationWidget's child. pageBuilder: (context, state) => MaterialPage( child: child, ), ); } Widget _buildFadeTransition( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child, ) => FadeTransition(opacity: animation, child: child); Duration _slowDuration = Duration( milliseconds: (RouteDurations.slow.inMilliseconds).round(), );
#!/usr/bin/perl use strict; use warnings; use Test::More; use Path::Class; use W3C::SOAP::WADL::Parser; use WWW::Mechanize; use TryCatch; use File::ShareDir qw/dist_dir/; use Template; use Data::Dumper qw/Dumper/; my $dir = file($0)->parent; my $app = file($0)->parent->file('app.pl'); my $port = 4001; my $pid = fork; if ( !defined $pid ) { plan skip_all => "Couldn't start test server! $!\n"; exit 0; } elsif ( !$pid ) { # Keep test output clean by hiding server details close STDERR; open STDERR, '>', '/dev/null'; close STDOUT; open STDOUT, '>', '/dev/null'; $ENV{PORT} = $port; exec $app, 'daemon', '--listen', "http://*:$port"; } sleep 1; my $mech = WWW::Mechanize->new; $mech->get("http://localhost:$port/wadl"); my $wadl = $mech->content; if ( $mech->status != 200 || $wadl !~ m{^<application \s xmlns="http://wadl.dev}xms ) { plan skip_all => "Couldn't connect to the test server! $!\n"; exit 0; } else { diag substr $wadl, 0, 92; } try { my $parser = get_parser(); check_dynamic($parser); } catch ($e) { ok !$e, 'no errors'; diag $e; } kill 9, $pid or diag "Error killing child! $!\n"; done_testing(); sub get_parser { $mech->get("http://localhost:$port/wadl"); my $wadl = $mech->content; ok $wadl, 'Get the WADL text from the server' or diag $mech->status; my $template = Template->new( INCLUDE_PATH => dist_dir('W3C-SOAP-WADL') . ':' . dist_dir('W3C-SOAP'), INTERPOLATE => 0, EVAL_PERL => 1, ); $wadl = W3C::SOAP::WADL::Parser->new( location => "http://localhost:$port/wadl", template => $template, module => 'Test::Ping', lib => $dir->subdir('lib').'', ); ok $wadl, "Got a parser object"; my $test = $dir->subdir('lib', 'Test'); if ( -d $test ) { my @files = $test->children; for my $file (@files) { if (-d $file) { push @files, $file->children; } elsif ( -f $file ) { unlink $file; } } } $wadl->write_modules; ok -f $dir->file(qw/lib Test Ping.pm/), "Wrote main lib file"; # add path to @INC; push @INC, $dir->subdir('lib').''; # use generated module use_ok 'Test::Ping'; return Test::Ping->new; } sub check_dynamic { my $wadl = shift; ok $wadl, 'Create new object'; my ($res, $ping) = $wadl->ping_GET( 'X_Request_ID' => 1, 'X_Request_DateTime' => 'now', 'X_Request_TimeZone' => 'Z', 'X_Partner_ID' => 'test', ); ok $ping, 'Get ping response'; is $ping->X_Response_ID, 0, 'Get response id'; is $ping->I_Response_ID, 1, 'Get response id'; ($res, $ping) = $wadl->ping_POST( 'X_Request_ID' => 1, 'X_Request_DateTime' => 'now', 'X_Request_TimeZone' => 'Z', 'X_Partner_ID' => 'test', ); ok $ping, 'Get ping response'; is $ping->X_Response_ID, 1, 'Get response id'; is $ping->Response_ID, 2, 'Get response id'; ($res, $ping) = $wadl->ping_POST( 'X_Request_ID' => 1, 'X_Request_DateTime' => 'now', 'X_Request_TimeZone' => 'Z', 'X_Partner_ID' => 'test', 'I_Status' => 400, ); ok $ping, 'Get ping 400 response'; ($res, $ping) = $wadl->ping_POST( 'X_Request_ID' => 1, 'X_Request_DateTime' => 'now', 'X_Request_TimeZone' => 'Z', 'X_Partner_ID' => 'test', 'I_Status' => 401, ); ok $ping, 'Get ping 401 response'; is $res->{multi}, 'true', 'Get multi param'; ($res, $ping) = $wadl->ping_POST( 'X_Request_ID' => 1, 'X_Request_DateTime' => 'now', 'X_Request_TimeZone' => 'Z', 'X_Partner_ID' => 'test', 'I_Status' => 402, ); ok $ping, 'Get ping 402 response'; is $res->{form}, '1', 'Get form param'; ($res, $ping) = $wadl->ping_POST( 'X_Request_ID' => 1, 'X_Request_DateTime' => 'now', 'X_Request_TimeZone' => 'Z', 'X_Partner_ID' => 'test', 'I_Status' => 403, ); ok $ping, 'Get ping 403 response'; is $res->{url}, 'u', 'Get url param'; ($res, $ping) = $wadl->ping_POST( 'X_Request_ID' => 1, 'X_Request_DateTime' => 'now', 'X_Request_TimeZone' => 'Z', 'X_Partner_ID' => 'test', 'I_Status' => 404, ); ok $ping, 'Get ping 404 response'; ok ref $res, 'get xml back' or diag Dumper $res, $ping; }
import React, { Component, useState } from "react"; import { connect } from "react-redux"; import { createTutorial } from "../actions/tutorials"; const AddTutorial = ({ createTutorial }) => { const [title, setTitle] = useState(""); const [description, setDescription] = useState(""); const [submitted, setSubmitted] = useState(false); const onChangeTitle = (e) => { setTitle(e.target.value); }; const onChangeDescription = (e) => { setDescription(e.target.value); }; const saveTutorial = () => { createTutorial(title, description) .then((data) => { setTitle(data.title); setDescription(data.description); setSubmitted(true); console.log(data); }) .catch((error) => { console.log(error); }); }; const newTutorial = () => { setTitle(""); setDescription(""); setSubmitted(false); }; return ( <> {submitted ? ( <div> <h4>You submitted succesfully!</h4> <button onClick={newTutorial}>Add another tutorial</button> </div> ): ( <div> <div className="form-group"> <label htmlFor="title">Title</label> <input type="text" className="form-control" id="title" required value={title} onChange={onChangeTitle} name="title" /> </div> <div className="form-group"> <label htmlFor="description">Title</label> <textarea className="form-control" id="description" required value={description} onChange={onChangeDescription} name="description" /> </div> <button onClick={saveTutorial} className="btn btn-success" > Submit </button> </div> )} </> ); }; export default connect(null, { createTutorial })(AddTutorial);
<?php namespace App\Entity; use App\Repository\InscripcionRepository; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Serializer\Annotation\Groups; use Nelmio\ApiDocBundle\Annotation\Model; use OpenApi\Attributes as OA; #[ORM\Entity(repositoryClass: InscripcionRepository::class)] #[ORM\HasLifecycleCallbacks] class Inscripcion { #[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column] private ?int $id = null; #[ORM\ManyToOne(inversedBy: 'inscripcions')] #[Groups(["create", "update"])] #[OA\Property(ref: new Model(type: Torneo::class))] private ?Torneo $torneo = null; #[ORM\OneToOne(inversedBy: 'inscripcion', cascade: ['persist'/*, 'remove'*/])] #[Groups(["create", "update"])] #[OA\Property(ref: new Model(type: Equipo::class))] private ?Equipo $equipo = null; #[ORM\Column] private ?\DateTimeImmutable $createdAt = null; #[ORM\Column] private ?\DateTimeImmutable $updatedAt = null; #[ORM\Column] #[Groups(["create", "update"])] private ?bool $habilitado = null; public function getId(): ?int { return $this->id; } public function getTorneo(): ?Torneo { return $this->torneo; } public function setTorneo(?Torneo $torneo): static { $this->torneo = $torneo; return $this; } public function getEquipo(): ?Equipo { return $this->equipo; } public function setEquipo(?Equipo $equipo): static { $this->equipo = $equipo; return $this; } public function getCreatedAt(): ?\DateTimeImmutable { return $this->createdAt; } #[ORM\PrePersist] public function setCreatedAt(): static { $this->createdAt = new \DateTimeImmutable('now'); ; return $this; } public function getUpdatedAt(): ?\DateTimeImmutable { return $this->updatedAt; } #[ORM\PrePersist] #[ORM\PreUpdate] public function setUpdatedAt(): static { $this->updatedAt = new \DateTimeImmutable('now'); ; return $this; } public function isHabilitado(): ?bool { return $this->habilitado; } public function setHabilitado(bool $habilitado): static { $this->habilitado = $habilitado; return $this; } }
import { createContext, ReactElement, useMemo, useReducer } from "react"; export type CartItemType = { sku: string; name: string; price: number; qty: number; }; type CartStateType = { cart: CartItemType[] }; const initCartState: CartStateType = { cart: [] }; const REDUCER_ACTION_TYPE = { ADD: "ADD", REMOVE: "REMOVE", QUANTITY: "QUANTITY", SUBMIT: "SUBMIT", }; export type ReducerActionType = typeof REDUCER_ACTION_TYPE; export type ReducerAction = { type: string; payload?: CartItemType; }; const reducer = ( state: CartStateType, action: ReducerAction ): CartStateType => { switch (action.type) { case REDUCER_ACTION_TYPE.ADD: { if (!action.payload) { throw new Error("action.payload missing in ADD action"); } const { sku, name, price } = action.payload; const filteredCart: CartItemType[] = state.cart.filter( (item) => item.sku !== sku ); const itemExists: CartItemType | undefined = state.cart.find( (item) => item.sku === sku ); const qty: number = itemExists ? itemExists.qty + 1 : 1; return { ...state, cart: [...filteredCart, { sku, name, price, qty }] }; } case REDUCER_ACTION_TYPE.REMOVE: { if (!action.payload) { throw new Error("action.payload missing in REMOVE action"); } const { sku } = action.payload; const filteredCart: CartItemType[] = state.cart.filter( (item) => item.sku !== sku ); return { ...state, cart: [...filteredCart] }; } case REDUCER_ACTION_TYPE.QUANTITY: { if (!action.payload) { throw new Error("action.payload missing in QUANTITY action"); } const { sku, qty } = action.payload; const itemExists: CartItemType | undefined = state.cart.find( (item) => item.sku === sku ); if (!itemExists) { throw new Error("Item must exist in order to update quantity"); } const updateItem: CartItemType = { ...itemExists, qty }; const filteredCart: CartItemType[] = state.cart.filter( (item) => item.sku !== sku ); return { ...state, cart: [...filteredCart, updateItem] }; //...filteredCart means we are spreading the array and then adding the updateItem to the end of the array, this is the same as filteredCart.concat(updateItem) //spread operator is the same as concat } case REDUCER_ACTION_TYPE.SUBMIT: { return { ...state, cart: [] }; } default: throw new Error("Unidentified reducer action type"); } }; const useCartContext = (initCartState: CartStateType) => { const [state, dispatch] = useReducer(reducer, initCartState); //what we done is memoize that reducer action type so its always so it always has the same referential equality when we pass it into a component and that will help us memoize the component in the future without worrying about the reducer actions causing a re-render const REDUCER_ACTIONS = useMemo(() => { // Reducer_action is a constant so it will never change, so we can use useMemo to memoize it so it will always have the same referential equality return REDUCER_ACTION_TYPE; }, []); const totalItems: number = state.cart.reduce((previousValue, cartItem) => { return previousValue + cartItem.qty; }, 0); // reducer needs the initial value, in this case it's 0 const totalPrice = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", }).format( state.cart.reduce((previousValue, cartItem) => { return previousValue + cartItem.qty * cartItem.price; }, 0) ); // set cart to sort by sku const cart = state.cart.sort((a, b) => { const itemA = Number(a.sku.slice(-4)); const itemB = Number(b.sku.slice(-4)); return itemA - itemB; }); // I created custom hook that doesn't mean they won't cause a re-render, it is just another way to approach it and memorization only helps when we would use react.memo, that would only help if we were passing things down as props return { dispatch, REDUCER_ACTIONS, cart, totalItems, totalPrice }; }; export type UseCartContextType = ReturnType<typeof useCartContext>; //initializing UseCartContextType const initCartContextState: UseCartContextType = { dispatch: () => {}, REDUCER_ACTIONS: REDUCER_ACTION_TYPE, totalItems: 0, totalPrice: " ", cart: [], }; export const CartContext = createContext<UseCartContextType>(initCartContextState); //the childrentype is essentially equal to that same children type that I defined in the products context. Other way, I could keep this in another file and import it to use in both files if I want to export it from that. type ChildrenType = { children?: ReactElement | ReactElement[] }; export const CartProvider = ({ children }: ChildrenType): ReactElement => { return ( <CartContext.Provider value={useCartContext(initCartState)}> {children} </CartContext.Provider> ); }; export default CartContext;
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class MethodChannelDemo extends StatefulWidget { const MethodChannelDemo({super.key}); @override State<MethodChannelDemo> createState() => _MethodChannelInvocationPageState(); } class _MethodChannelInvocationPageState extends State<MethodChannelDemo> { static const platform = MethodChannel('com.test.library/nativeMethods'); int _number = 0; Future<void> invokeNativeMethod() async { try { await platform.invokeMethod('randomNumber', [10]).then((value) { setState(() { _number = value; }); }); } on PlatformException catch (e) { print("error: $e"); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).colorScheme.inversePrimary, title: const Text("Method Invocation"), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( child: const Text("invoke"), onPressed: () { invokeNativeMethod(); }), Text( '$_number', style: Theme.of(context).textTheme.headlineMedium, ), ], ), ), ); } }
import React, { useState } from "react"; import { Link, useNavigate } from "react-router-dom"; import axios from "../axios"; import { BsEyeFill, BsEyeSlashFill } from "react-icons/bs"; import { FcGoogle } from "react-icons/fc"; import { validateEmail, validateName, validatePassword, } from "../helpers/validation"; import { IoIosCheckmarkCircleOutline, IoMdCloseCircleOutline, } from "react-icons/io"; import InputContainer from "../components/InputContainer"; import toast from "react-hot-toast"; import Button from "../components/ButtonLoader"; function Register() { const [formData, setFormData] = useState({ username: "", email: "", password: "", }); const [showPassword, setShowPassword] = useState(false); const navigate = useNavigate(); const handleSubmit = async (e) => { if ( !validateName(formData.username) || !validateEmail(formData.email) || !validatePassword(formData.password) ) { } else { const user = { username: formData.username, email: formData.email, password: formData.password, }; try { const res = await axios.post("/auth/register", user, { withCredentials: true, }); toast.success(res.data.message); navigate("/login"); } catch (err) { toast.error(err.message); } } }; const signInGoogle = async () => { window.open( "https://mernsocialmedia.onrender.com/api/auth/google", "_self" ); }; return ( <div className="min-h-screen lg:h-screen flex flex-col bg-background"> <div className="h-full flex flex-1 flex-col lg:flex-row sm:p-2 gap-4 md:gap-8 lg:gap-0"> <div className="bg-background lg:bg-[#f2f4f8] h-20 lg:h-full lg:w-[400px] xl:w-[580px] rounded-md"> <img src="/assets/home-illustration-3.svg" className="h-full w-full hidden lg:block" /> </div> <div className="flex flex-1 lg:items-center justify-center"> <div onClick={() => navigate("/")} className="flex items-center cursor-pointer absolute left-1/2 -translate-x-1/2 lg:translate-x-0 top-2 lg:left-2" > <picture className="lg:-mr-4"> <source media="(min-width: 992px)" srcSet="/assets/socialLogo.png" width={100} height={100} ></source> <source media="(min-width: 768px)" srcSet="/assets/socialLogo.png" width={120} height={120} ></source> <source media="(min-width: 600px)" srcSet="/assets/socialLogo.png" width={110} height={110} ></source> <img src="/assets/socialLogo.png" width={100} height={100} /> </picture> <h1 className="font-bold text-[22px] hidden lg:block mt-3"> connect </h1> </div> <div className="flex flex-col gap-6 items-center"> <div className="flex flex-col gap-2 w-96"> <h1 className="text-lg sm:text-2xl md:text-3xl font-semibold text-center"> Sign up to Connect </h1> </div> <div className="w-full px-5 sm:px-0 sm:max-w-[450px] sm:w-[450px] md:space-y-4 sm:space-y-3 space-y-2 self-center"> <form className="w-full md:h-fit flex flex-col rounded-md space-y-3 lg:space-y-5"> <div className="space-y-3 flex-1"> <InputContainer name="username" type="text" {...{ formData, setFormData }} > {!validateName(formData.username) && formData.username && ( <IoMdCloseCircleOutline size={20} color="red" /> )} {validateName(formData.username) && ( <IoIosCheckmarkCircleOutline size={20} color="green" /> )} </InputContainer> <InputContainer name="email" type="email" {...{ formData, setFormData }} > {!validateEmail(formData.email) && formData.email && ( <IoMdCloseCircleOutline size={20} color="red" /> )} {validateEmail(formData.email) && ( <IoIosCheckmarkCircleOutline size={20} color="green" /> )} </InputContainer> <InputContainer name="password" type={showPassword ? "text" : "password"} {...{ formData, setFormData }} > {!validatePassword(formData.password) && formData.password && ( <IoMdCloseCircleOutline size={20} color="red" /> )} {validatePassword(formData.password) && ( <IoIosCheckmarkCircleOutline size={20} color="green" /> )} {showPassword ? ( <BsEyeFill className="cursor-pointer" color="darkgray" onClick={() => setShowPassword(false)} /> ) : ( <BsEyeSlashFill className="cursor-pointer" color="darkgray" onClick={() => setShowPassword(true)} /> )} </InputContainer> </div> </form> <Button text="Sign Up" callbackFn={handleSubmit} /> <p className="text-gray_dark text-sm relative text-center after:absolute after:w-1/3 after:h-0.5 after:top-1/2 after:left-10 w-full after:bg-gray-200 before:absolute before:w-1/3 before:h-0.5 before:bg-gray-200 before:top-1/2 before:right-10"> or </p> <button onClick={signInGoogle} className="border-2 border-[#e8ebf3] w-full py-2.5 md:py-3 rounded-md text-[14px] flex items-center gap-2 justify-center" > <FcGoogle size={18} /> <p className="text-[14px] sm:text-[15px]"> Sign up with google </p> </button> <p className="text-[14px] sm:text-[15px] text-gray_dark"> Already have an account?{" "} <Link to="/login"> <span className="w-full py-2 rounded-md hover:underline text-accent font-medium"> Login </span> </Link> </p> </div> </div> </div> </div> </div> ); } export default Register;
<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://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous" /> <title>Employee Form</title> </head> <body> <div class="container"> <h5 class="py-1 text-center">Employee Form</h5> <input type="hidden" name="csrfmiddlewaretoken" value="hc49sfcYlrLH5gzUaDqkMa7rbg0A4eST8vHz50Auv0tOZ5U7iRi1LlOFVtaTwurp" /> <div class="form-row"> <div class="form-group col-md-6 mb-0"> <div id="div_id_full_name" class="form-group"> <label for="id_full_name" class="requiredField"> Full name<span class="asteriskField">*</span> </label> <div class=""> <input type="text" name="full_name" maxlength="200" class="textinput textInput form-control" required="" id="id_full_name" /> </div> </div> </div> <div class="form-group col-md-6 mb-0"> <div id="div_id_address" class="form-group"> <label for="id_address" class="requiredField"> Address<span class="asteriskField">*</span> </label> <div class=""> <input type="text" name="address" maxlength="120" class="textinput textInput form-control" required="" id="id_address" /> </div> </div> </div> </div> <div class="form-row"> <div class="form-group col-md-6 mb-0"> <div id="div_id_email" class="form-group"> <label for="id_email" class="requiredField"> Email<span class="asteriskField">*</span> </label> <div class=""> <input type="email" name="email" maxlength="120" class="emailinput form-control" required="" id="id_email" /> </div> </div> </div> <div class="form-group col-md-6 mb-0"> <div id="div_id_phone_number" class="form-group"> <label for="id_phone_number" class="requiredField"> Phone number<span class="asteriskField">*</span> </label> <div class=""> <input type="text" name="phone_number" maxlength="20" class="textinput textInput form-control" required="" id="id_phone_number" /> </div> </div> </div> </div> <div id="div_id_image" class="form-group col-md-3 mb-0"> <label for="id_image" class="requiredField"> Image<span class="asteriskField">*</span> </label> <div class=""> <input type="file" name="image" accept="image/*" class="clearablefileinput form-control-file" required="" id="id_image" /> </div> </div> <button class="btn btn-primary" onclick="post_data()">Create Employee</button> <h5 class="pt-3 pb-1 text-center">Employee Table</h5> <table class="table table-sm"> <thead> <tr> <th scope="col">id</th> <th scope="col">Name</th> <th scope="col">Address</th> <th scope="col">Email</th> <th scope="col">Phone Number</th> <th scope="col">Created on</th> <th scope="col">Updated on</th> <th scope="col">Action</th> </tr> </thead> <tbody id='table_body'> </tbody> </table> </div> <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/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.23.0/axios.min.js"></script> <script> const Url = "http://localhost:8000/api/employee/" let loadData = () => { document.getElementById('table_body').innerHTML = ''; axios.get(Url).then(response => { if (response.data.data.length > 0) { let person_list = response.data.data; person_list.forEach((person) => { const element = `<tr> <th scope="row">${person.id}</th> <td>${person.full_name}</td> <td>${person.address}</td> <td>${person.email}</td> <td>${person.phone_number}</td> <td>${person.created}</td> <td>${person.updated}</td> <td> <p class="btn btn-danger" onclick='deleteEmployee(${person.id})'>Delete</p> <p class="btn btn-warning" onClick='editEmployee(${person.id})'>Edit</p> <a href="/${person.id}/details" class="btn btn-info">Details</a> </td> </tr>`; document.getElementById('table_body').innerHTML += element; }); // console.log(response.data.data[0].id) } } ) .catch(error => console.error(error)); } loadData(); let clearData = () => { document.getElementById('id_full_name').value = '' document.getElementById("id_email").value = '' document.getElementById("id_address").value = '' document.getElementById("id_phone_number").value = '' document.getElementById("id_image").value = '' } // let fetch_data = { // full_name: document.getElementsByName('full_name').value, // email: document.getElementsByName("email").value, // address: document.getElementsByName("address").value, // phone_number: document.getElementsByName("phone_number").value, // image: document.getElementsByName("image").value // } // axios.post(Url, {fetch_data}).then().catch() let validate_data = () => { let name = document.getElementById('id_full_name').value; let email = document.getElementById("id_email").value; let address = document.getElementById("id_address").value; let phone_number = document.getElementById("id_phone_number").value; let image = document.getElementById("id_image").value; if (name == '') { alert('Please provide name') } else if (email == "") { alert("please provide email") } else if (address == "") { alert('please provide address') } else if (phone_number == '') { alert("please Provide phone number") } else if (image == '') { alert("please provide image") } } let post_data = (data) => { validate_data(); let format_data = new FormData(); format_data.append('full_name', document.getElementById("id_full_name").value) format_data.append('email', document.getElementById("id_email").value) format_data.append('address', document.getElementById("id_address").value) format_data.append('phone_number', document.getElementById("id_phone_number").value) const imagefile = document.querySelector('#id_image'); format_data.append('image', imagefile.files[0]) format_data.append("csrfmiddlewaretoken", '{{csrf_token}}') console.log(format_data) axios.post(Url, format_data, { headers: { 'Content-Type': 'multipart/form-data' } }) .then(response => { console.log(response) clearData(); loadData(); }) .catch(error => { console.log(error) }) } // let deleteEmployee = (id) => { // axios.delete(Url + id + '/', { // headers: { // 'Content-Type': 'multipart/form-data' // }) // .then(response => { // console.log(response) // }) // .catch(error => { // console.log(error); // }) // } // } let deleteEmployee = (id) => { axios.delete(Url + id + '/', { headers: { 'Content-Type': 'multipart/form-data', "csrfmiddlewaretoken": '{{csrf_token}}', } }) .then(response => { console.log(response); loadData(); }) .catch(error => { console.log(error) }) } let editEmployee = (id) => { axios.get(Url + id + '/') .then(response => { const employee = response.data.data; document.getElementById('id_full_name').value = employee.full_name document.getElementById("id_email").value = employee.email document.getElementById("id_address").value = employee.address document.getElementById("id_phone_number").value = employee.phone_number document.getElementById("id_image").value = employee.image }) .catch(error => { console.log(error) }) } </script> </body> </html>
import inspect import json import os import numpy as np import torch from ..tfops import tf def save_params(model, path, model_name): hparams = dict() arg_names = list(inspect.signature(model.__init__).parameters.keys()) if "data_info" in arg_names: arg_names.remove("data_info") if "device" in arg_names: arg_names.remove("device") if "items" in arg_names: ###MODIFICA arg_names.remove("items") if "patience" in arg_names: ###MODIFICA arg_names.remove("patience") for p in arg_names: hparams[p] = model.all_args[p] param_path = os.path.join(path, f"{model_name}_hyper_parameters.json") with open(param_path, "w") as f: json.dump(hparams, f, separators=(",", ":"), indent=4) def load_params(model_class, path, data_info, model_name): if not os.path.exists(path): raise OSError(f"file folder {path} doesn't exists...") param_path = os.path.join(path, f"{model_name}_hyper_parameters.json") with open(param_path, "r") as f: hparams = json.load(f) hparams.update({"data_info": data_info}) if "with_training" in inspect.signature(model_class.__init__).parameters.keys(): hparams.update({"with_training": False}) return hparams def save_tf_model(sess, path, model_name): model_path = os.path.join(path, f"{model_name}_tf") saver = tf.train.Saver() saver.save(sess, model_path, write_meta_graph=True) def load_tf_model(model_class, path, model_name, data_info): model_path = os.path.join(path, f"{model_name}_tf") hparams = load_params(model_class, path, data_info, model_name) model = model_class(**hparams) # model_class.__class__(**hparams) # saver = tf.train.import_meta_graph(os.path.join(path, model_name + ".meta")) saver = tf.train.Saver() saver.restore(model.sess, model_path) return model def save_tf_variables(sess, path, model_name, inference_only): variable_path = os.path.join(path, f"{model_name}_tf_variables") variables = dict() for v in tf.global_variables(): if inference_only: # also save moving_mean and moving_var for batch_normalization if v in tf.trainable_variables() or "moving" in v.name: variables[v.name] = sess.run(v) else: variables[v.name] = sess.run(v) np.savez_compressed(variable_path, **variables) def load_tf_variables(model_class, path, model_name, data_info): variable_path = os.path.join(path, f"{model_name}_tf_variables.npz") variables = np.load(variable_path) hparams = load_params(model_class, path, data_info, model_name) model = model_class(**hparams) update_ops = [] for v in tf.global_variables(): # also load moving_mean and moving_var for batch_normalization if v in tf.trainable_variables() or "moving" in v.name: update_ops.append(v.assign(variables[v.name])) # v.load(variables[v.name], session=model.sess) model.sess.run(update_ops) return model def save_torch_state_dict(model, path, model_name): save_path = os.path.join(path, f"{model_name}_torch.pt") torch.save( { "model_state_dict": model.torch_model.state_dict(), "optimizer_state_dict": model.trainer.optimizer.state_dict(), }, save_path, ) def load_torch_state_dict(path, model_name, device): load_path = os.path.join(path, f"{model_name}_torch.pt") state = torch.load(load_path, map_location=device) return state["model_state_dict"], state["optimizer_state_dict"]
%{ /**************************************************************************** * Copyright (c) 2022, CEA * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *****************************************************************************/ %} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Author : Erell Jamelot CEA % % MatPoissonLG.m: % Assemblages des matrices de masse et de raideur % % avec les elements finis de Galerkin continus (polynomes de Lagrange P1 ou P2) % % SYNOPSIS [Ku,Mu] = MatPoissonLG(CoorNeu,NumTri,TriEdg,EdgTri,Lga2,EdgNorm,Aires,ordre,nuT) % % INPUT - CoorNeu(Nbpt,2) : coordonnees (x, y) des sommets % - NumTri(Nbtri,3) : liste de triangles % (3 numeros de sommets) % - TriEdg(Nbtri,3) : Pour chaque triangle, TriEdg(l,i) est le numero de l'arete opposee au sommet NumTri(l,i) % (3 numeros des aretes - matrice entiere Nbtri x 3) % - EdgTri(NbEdg,2) : Pour chaque arete, EdgTri(a,:) donne les numeros des 2 triangles de chaque arete % EdgTri(a,2) = 0 si a est sur la frontiere % - Lga2(NbEdg,1) : longueurs des aretes au carre % - EdgNorm(NbEdg,2) : vecteurs face-normale, orientes tri1->tri2 % - Aires(Nbtri,1) : aires des triangles % - ordre : 1 ou 2 % - nuT : coefficient de raideur % % OUTPUT - Ku : matrice de raideur % - Mu : matrice de masse % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [Ku,Mu] = MatPoissonLG(CoorNeu,NumTri,TriEdg,EdgTri,Lga2,EdgNorm,Aires,ordre,nuT) % Nbpt=size(CoorNeu,1); Nbtri=size(NumTri,1); % % Matrices de masse locales pour aire=1 !! [MT1,invMT1,MT01,MT2,invMT2,MT02,MT12]=MassLGTriangle; if (ordre==1) Ndof_u=Nbpt; Numloc=NumTri; MLG=MT1; end % if (ordre==2) NbEdg=size(EdgTri,1); Ndof_u=Nbpt+NbEdg; Numloc=[NumTri,TriEdg+Nbpt]; MLG=MT2; end Ku=sparse(Ndof_u,Ndof_u); Mu=Ku; for t=1:Nbtri aire=Aires(t); AGLO=TriEdg(t,:); EdgNormT=EdgNorm(AGLO,:); Lga2T=Lga2(AGLO); for iloc=1:2 if (EdgTri(AGLO(iloc),1)~=t) EdgNormT(iloc,:)=-EdgNormT(iloc,:); end end EdgNormT(3,:)=-EdgNormT(1,:)-EdgNormT(2,:); %Lga2T(3)=dot(EdgNormT(3,:),EdgNormT(3,:)); % On suppose nu constant par element [KLG,K1,K2]=KriLGTriangle(aire,EdgNormT,Lga2T,ordre); KuT=nuT(t)*KLG; MuT=aire*MLG; %% Ku et Mu IGLO=Numloc(t,:); Ku(IGLO,IGLO)+=KuT; Mu(IGLO,IGLO)+=MuT; end % end_for t=1:Nbtri %
// potentiometer array size, must be constant const int num_of_analog_pins = 3; // push-button array size, must be constant const int num_of_digital_pins = 3; // create an array to store the values of the potentiometers int analog_values[num_of_analog_pins]; // create an array to store the values of the push-buttons int digital_values[num_of_digital_pins]; void setup() { for(int i = 0; i < num_of_digital_pins; i++){ pinMode((i + 2), INPUT_PULLUP); } Serial.begin(9600); } void loop() { for(int i = 0; i < num_of_analog_pins; i++){ analog_values[i] = analogRead(i); } for(int i = 0; i < num_of_digital_pins; i++){ digital_values[i] = !digitalRead(i + 2); } Serial.print("Analog values: "); for(int i = 0; i < num_of_analog_pins; i++){ Serial.print(analog_values[i]); Serial.print(" "); } Serial.print("Digital values: "); for(int i = 0; i < (num_of_digital_pins - 1); i++){ Serial.print(digital_values[i]); Serial.print(" "); } Serial.println(digital_values[num_of_digital_pins - 1]); delay(500); }
package me.buck.sunflower_kotlin.viewmodels import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import me.buck.sunflower_kotlin.data.GardenPlantingRepository /** * Factory for creating a [GardenPlantingListViewModel] with a constructor that takes a * [GardenPlantingRepository]. */ class GardenPlantingListViewModelFactory( private val repository: GardenPlantingRepository ) : ViewModelProvider.NewInstanceFactory() { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { return GardenPlantingListViewModel(repository) as T } }
package MetodosClasses; public class Metodos { /* Método é uma função que programamos para a classe main, ele é o método principal Como criar um método? Indicador de Acesso - public static Tipo de Retorno - void / Nada Nome - main Conjunto de parametros desse método - (String[] args) */ public static void main(String[] args) { //Faz a chamada do método e executa a instrução que tem dentro mensagem(); //Faz a passagem dos itens para o método instrucoes("Estudando e treinando"); instrucoes("Aprendendo JAVA"); // Faz a passagem de 4 notas e calcula a média // Passando valores do tipo double media(10,9.5,8,6.5); // Sobrecarga de métodos /* Podemos criar mais de um método com o mesmo nome, mas eles devem ter tipos diferentes para serem aceitos*/ // Passando valores do tipo int media(10,9,8,6); int resultado; resultado = soma(5, 9); System.out.println("Resultado da soma: "+resultado); //----------------------------------- System.out.println("Resultado: "+somaNumeros(5,10,20,10,13)); } //Indicador de Acesso - public static //Tipo de Retorno - void / Nada //Nome - mensagem public static void mensagem() { System.out.println("Aprendendo sobre Métodos"); } // Criando o método com um parâmetro de entrada // String texto - recebe o texto que vem do método main e exibe na tela com o auxílio do System.out.println public static void instrucoes(String texto) { System.out.println(texto); } /*public - Tenho acesso a esse método fora da classe Se o método main é static ou outros também terão que ser static*/ public static void media(double nota1, double nota2, double nota3, double nota4) { double media; media = (nota1 + nota2 + nota3 + nota4) / 4; System.out.println("Média final com Double: "+media); } /* mesmo nome do método acima, mas com tipos diferentes (um é do tipo double e o outro int) o java entende que são coisas diferentes*/ public static void media(int nota1, int nota2, int nota3, int nota4) { int media; media = (nota1 + nota2 + nota3 + nota4) / 4; System.out.println("Média final com Int: "+media); } public static int soma(int valor1, int valor2) { int resultado = valor1 + valor2; // return - Retorna o resultado da operação return resultado; } // Criando uma lista de parâmetros do tipo int public static int somaNumeros(int ... numeros) { int resultado = 0; for (int posicao = 0; posicao < numeros.length; posicao++) { resultado = resultado + numeros[posicao]; } return resultado; } }
import { useState } from "react"; import axios from "axios"; import { useGetUserID } from "../components/hooks/useGetUserID"; import { useGetToken } from "../components/hooks/useGetToken"; import useDecodedToken from "../components/hooks/useDecodedToken"; import { useNavigate } from 'react-router-dom'; /** * AddData Component. * Allows users to submit new data entries, checking their clearance level and * providing inputs for various data attributes like description, tags, and additional info. */ export const AddData = () => { // Retrieve the current user's ID const userID = useGetUserID(); // Retrieve the current session's JWT token const token = useGetToken(); // Decode the JWT token to access user-related attributes like clearance level const decodedToken = useDecodedToken(token); // State to manage the form data for new data entry const [data, setData] = useState({ clearanceLevel: (decodedToken && decodedToken.clearanceLevel) || 0, description: "", tags: [], info: "", userOwner: userID, }); // Hook to programmatically navigate between routes const navigate = useNavigate(); // Clearance levels available for selection const clearanceLevels = [0, 1, 2, 3]; /** * Handles the change of input fields in the form. */ const handleChange = (event) => { const { name, value } = event.target; setData({ ...data, [name]: value }); }; /** * Handles the change of tags input fields in the form. */ const handleTagChange = (event, idx) => { const { value } = event.target; const updatedTags = [...data.tags]; updatedTags[idx] = value; setData({ ...data, tags: updatedTags }); }; /** * Adds an empty input field for a new tag. */ const addTag = () => { setData({ ...data, tags: [...data.tags, ""] }); }; /** * Handles the submission of the form data to the server. */ const handleSubmitData = async (event) => { event.preventDefault(); const selectedClearanceLevel = data.clearanceLevel; // Validation: Description is mandatory if (!data.description) { alert("Description is required."); return; } // Validation: Ensure user's clearance level matches or exceeds the clearance level of the data being submitted if (decodedToken.clearanceLevel < selectedClearanceLevel) { alert("Insufficient clearance level to submit this data."); return; } const dataToSend = { clearanceLevel: selectedClearanceLevel, description: data.description, tags: data.tags, info: data.info, userOwner: data.userOwner, }; // Send the data to the server try { const response = await axios.post("http://localhost:3001/data", dataToSend, { headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", }, }); if (response.data.error) { alert("Error while submitting data. Server returned an error."); } else { alert("Data Added"); navigate("/") // Navigate back to the home page } } catch (err) { alert("Error while submitting data. An error occurred on the client."); console.error("Client Error:", err); } }; // Render the component return ( <div className="add-data"> <h2>Add Data</h2> <form onSubmit={handleSubmitData}> <label htmlFor="clearanceLevel">Clearance Level</label> <select id="clearanceLevel" name="clearanceLevel" onChange={handleChange} value={data.clearanceLevel} > {clearanceLevels.map((level) => ( <option key={level} value={level}> {level} </option> ))} </select> <label htmlFor="description">Description</label> <textarea id="description" name="description" onChange={handleChange} value={data.description} ></textarea> <label htmlFor="tags">Tags</label> {data.tags.map((tag, idx) => ( <div key={idx}> <input type="text" name="tags" value={tag} onChange={(event) => handleTagChange(event, idx)} /> </div> ))} <button type="button" onClick={addTag}>Add Tag</button> <label htmlFor="info">Information</label> <textarea id="info" name="info" onChange={handleChange} value={data.info} ></textarea> <button type="submit">Add Data</button> </form> </div> ); };
import notifee, {EventType,AndroidImportance} from '@notifee/react-native'; import messaging from '@react-native-firebase/messaging'; import {PERMISSIONS, request} from 'react-native-permissions'; import { navigate } from './navigation'; export const getFcmToken = async () => { let token = null; await checkApplicationNotificationPermission(); await registerAppWithFCM(); try { token = await messaging().getToken(); console.log('getFcmToken-->', token); } catch (error) { console.log('getFcmToken Device Token error ', error); } return token; }; export async function registerAppWithFCM() { console.log( 'registerAppWithFCM status', messaging().isDeviceRegisteredForRemoteMessages, ); if (!messaging().isDeviceRegisteredForRemoteMessages) { await messaging() .registerDeviceForRemoteMessages() .then(status => { console.log('registerDeviceForRemoteMessages status', status); }) .catch(error => { console.log('registerDeviceForRemoteMessages error ', error); }); } } //method was called on un register the user from firebase for stoping receiving notifications export async function unRegisterAppWithFCM() { console.log( 'unRegisterAppWithFCM status', messaging().isDeviceRegisteredForRemoteMessages, ); if (messaging().isDeviceRegisteredForRemoteMessages) { await messaging() .unregisterDeviceForRemoteMessages() .then(status => { console.log('unregisterDeviceForRemoteMessages status', status); }) .catch(error => { console.log('unregisterDeviceForRemoteMessages error ', error); }); } await messaging().deleteToken(); console.log( 'unRegisterAppWithFCM status', messaging().isDeviceRegisteredForRemoteMessages, ); } export const checkApplicationNotificationPermission = async () => { const authStatus = await messaging().requestPermission(); const enabled = authStatus === messaging.AuthorizationStatus.AUTHORIZED || authStatus === messaging.AuthorizationStatus.PROVISIONAL; if (enabled) { console.log('Authorization status:', authStatus); } request(PERMISSIONS.ANDROID.POST_NOTIFICATIONS) .then(result => { console.log('POST_NOTIFICATIONS status:', result); }) .catch(error => { console.log('POST_NOTIFICATIONS error ', error); }); }; //method was called to listener events from firebase for notification triger export function registerListenerWithFCM() { const unsubscribe = messaging().onMessage(async remoteMessage => { console.log('onMessage Received : ', JSON.stringify(remoteMessage)); if ( remoteMessage?.notification?.title && remoteMessage?.notification?.body ) { onDisplayNotification( remoteMessage.notification?.title, remoteMessage.notification?.body, remoteMessage?.data, ); } }); notifee.onForegroundEvent(({type, detail}) => { switch (type) { case EventType.DISMISSED: console.log('User dismissed notification', detail.notification); break; case EventType.PRESS: navigate('Login') break; } }); messaging().onNotificationOpenedApp(async remoteMessage => { navigate('Login') }); messaging() .getInitialNotification() .then(remoteMessage => { if (remoteMessage) { console.log( 'Notification caused app to open from quit state:', remoteMessage.notification, ); } }); return unsubscribe; } //method was called to display notification async function onDisplayNotification(title, body, data) { console.log('onDisplayNotification Adnan: ', JSON.stringify(data)); // Request permissions (required for iOS) await notifee.requestPermission(); // Create a channel (required for Android) const channelId = await notifee.createChannel({ id: 'default', name: 'Default Channel', importance: AndroidImportance.HIGH }); // Display a notification await notifee.displayNotification({ title: title, body: body, data: data, android: { channelId, // pressAction is needed if you want the notification to open the app when pressed pressAction: { id: 'default', }, }, }); } // Alias: AndroidDebugKey // MD5: 2D:6A:D3:44:E0:0A:BF:21:94:59:4C:6C:31:D5:A8:B1 // SHA1: 4A:D1:13:CA:C5:C8:86:E6:CF:22:40:32:82:CC:CE:C8:35:C9:BE:8D // SHA-256: 36:8D:99:52:72:C3:57:60:5D:FE:94:BA:2E:A1:F1:2F:B4:DA:8B:C5:C0:06:FB:DA:4B:2C:FE:D5:EA:FE:FA:8B // const getFcmToken = async () => { // let token = null; // await checkApplicationNotificationPermission(); // await registerAppWithFCM(); // try { // token = await messaging().getToken(); // console.log('getFcmToken-->', token); // } catch (error) { // console.log('getFcmToken Device Token error ', error); // } // return token; // }; // async function registerAppWithFCM() { // console.log( // 'registerAppWithFCM status', // messaging().isDeviceRegisteredForRemoteMessages, // ); // if (!messaging().isDeviceRegisteredForRemoteMessages) { // await messaging() // .registerDeviceForRemoteMessages() // .then(status => { // console.log('registerDeviceForRemoteMessages status', status); // }) // .catch(error => { // console.log('registerDeviceForRemoteMessages error ', error); // }); // } // } // //method was called on un register the user from firebase for stoping receiving notifications // async function unRegisterAppWithFCM() { // console.log( // 'unRegisterAppWithFCM status', // messaging().isDeviceRegisteredForRemoteMessages, // ); // if (messaging().isDeviceRegisteredForRemoteMessages) { // await messaging() // .unregisterDeviceForRemoteMessages() // .then(status => { // console.log('unregisterDeviceForRemoteMessages status', status); // }) // .catch(error => { // console.log('unregisterDeviceForRemoteMessages error ', error); // }); // } // await messaging().deleteToken(); // console.log( // 'unRegisterAppWithFCM status', // messaging().isDeviceRegisteredForRemoteMessages, // ); // } // const checkApplicationNotificationPermission = async () => { // const authStatus = await messaging().requestPermission(); // const enabled = // authStatus === messaging.AuthorizationStatus.AUTHORIZED || // authStatus === messaging.AuthorizationStatus.PROVISIONAL; // if (enabled) { // console.log('Authorization status:', authStatus); // } // request(PERMISSIONS.ANDROID.POST_NOTIFICATIONS) // .then(result => { // console.log('POST_NOTIFICATIONS status:', result); // }) // .catch(error => { // console.log('POST_NOTIFICATIONS error ', error); // }); // }; // //method was called to listener events from firebase for notification triger // function registerListenerWithFCM() { // const unsubscribe = messaging().onMessage(async remoteMessage => { // console.log('onMessage Received : ', JSON.stringify(remoteMessage)); // if ( // remoteMessage?.notification?.title && // remoteMessage?.notification?.body // ) { // onDisplayNotification( // remoteMessage.notification?.title, // remoteMessage.notification?.body, // remoteMessage?.data, // ); // } // }); // notifee.onForegroundEvent(({type, detail}) => { // switch (type) { // case EventType.DISMISSED: // console.log('User dismissed notification', detail.notification); // break; // case EventType.PRESS: // if (navigationRef.isReady()) { // navigationRef.navigate('Login'); // } // break; // } // }); // messaging().onNotificationOpenedApp(async remoteMessage => { // if (navigationRef.isReady()) { // navigationRef.navigate('Login'); // } // }); // // Check whether an initial notification is available // messaging() // .getInitialNotification() // .then(remoteMessage => { // if (remoteMessage) { // console.log( // 'Notification caused app to open from quit state:', // remoteMessage.notification, // ); // } // }); // return unsubscribe; // } // //method was called to display notification // async function onDisplayNotification(title, body, data) { // console.log('onDisplayNotification Adnan: ', JSON.stringify(data)); // // Request permissions (required for iOS) // await notifee.requestPermission(); // // Create a channel (required for Android) // const channelId = await notifee.createChannel({ // id: 'default', // name: 'Default Channel', // importance: AndroidImportance.HIGH, // }); // // Display a notification // await notifee.displayNotification({ // title: title, // body: body, // data: data, // android: { // channelId, // // pressAction is needed if you want the notification to open the app when pressed // pressAction: { // id: 'default', // }, // }, // }); // } // useEffect(() => { // const fetchData = async () => { // const getNotification = await AsyncStorage.getItem('get_notification'); // const getNotificationNewProduct = await AsyncStorage.getItem( // 'get_notification_new_product', // ); // const getNotificationNewCustomer = await AsyncStorage.getItem( // 'get_notification_new_customer', // ); // const getNotificationCustomerEvent = await AsyncStorage.getItem( // 'get_notification_customer_event', // ); // const getNotificationCheckingEvent = await AsyncStorage.getItem( // 'get_notification_checking_event', // ); // const getNotificationWarehouse = await AsyncStorage.getItem( // 'get_notification_warehouse', // ); // if (getNotification === 'yes') { // const unsubscribe = registerListenerWithFCM(); // return unsubscribe; // } else if (getNotification === 'no') { // return; // } else if (getNotification === null) { // await AsyncStorage.setItem('get_notification', 'yes'); // const unsubscribe = registerListenerWithFCM(); // return unsubscribe; // } // if (getNotificationNewProduct === null) { // await AsyncStorage.setItem('get_notification_new_product', 'yes'); // } else { // } // if (getNotificationNewCustomer === null) { // await AsyncStorage.setItem('get_notification_new_customer', 'yes'); // } else { // } // if (getNotificationCustomerEvent === null) { // await AsyncStorage.setItem('get_notification_customer_event', 'yes'); // } else { // } // if (getNotificationCheckingEvent === null) { // await AsyncStorage.setItem('get_notification_checking_event', 'yes'); // } else { // } // if (getNotificationWarehouse === null) { // await AsyncStorage.setItem('get_notification_warehouse', 'yes'); // } else { // } // }; // fetchData(); // }, []);
from collections import Counter def simulate_fish(fish: Counter[int], days: int) -> int: for _ in range(days): fish_to_add = fish[0] for k in fish.keys(): num_fish = fish[k] if num_fish > 0: fish[k] = 0 if k != 0: fish[k - 1] += num_fish fish[8] += fish_to_add fish[6] += fish_to_add return fish.total() def read_data(input: str) -> Counter[int]: counter = Counter({0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0}) fish = [int(num) for num in input.strip().split(",")] counter.update(fish) return counter def part_one(input_file: str) -> int: with open(input_file) as input: fish_counter = read_data(input.readline()) return simulate_fish(fish_counter, 80) def part_two(input_file: str) -> int: with open(input_file) as input: fish_counter = read_data(input.readline()) return simulate_fish(fish_counter, 256)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png"> <link rel="stylesheet" href="styles.css"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet"> <style> body { font-family: "Poppins", sans-serif; } </style> <title>Frontend Mentor | Four card feature section</title> </head> <body> <div class="main"> <div class="title"> <div class="titlecontainer"> <h1> Reliable, efficient delivery </h1> <h2> Powered by Technology </h2> <p> Our Artificial Intelligence powered tools use millions of project data points to ensure that your project is successful </p> </div> </div> <div class="cardsection"> <div class="cardcontainer" id="left"> <div class="card" id="supervisor"> <h3>Supervisor</h3> <p>Monitors activity to identify project roadblocks</p> </div> </div> <div class="cardcontainer" id="center"> <div class="card" id="teambuilder"> <h3>Team Builder</h1> <p>Scans our talent network to create the optimal team for your project</p> </div> <div class="card" id="karma"> <h3>Karma</h3> <p>Regularly evaluates our talent to ensure quality</p> </div> </div> <div class="cardcontainer" id="right"> <div class="card" id="calculator"> <h3>Calculator</h3> <p>Uses data from past projects to provide better delivery estimates</p> </div> </div> </div> </div> <footer> <p class="attribution"> Challenge by <a href="https://www.frontendmentor.io?ref=challenge" target="_blank">Frontend Mentor</a>. Coded by <a href="#">L0ds4m0n3y</a>. </p> </footer> </body> </html>
package com.toy.springcacheex.config import com.fasterxml.jackson.databind.ObjectMapper import com.toy.springcacheex.common.CustomRedisSerializer import com.toy.springcacheex.common.CacheConstants import org.slf4j.LoggerFactory import org.springframework.boot.autoconfigure.cache.RedisCacheManagerBuilderCustomizer import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty import org.springframework.cache.annotation.EnableCaching import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.data.redis.cache.RedisCacheConfiguration import org.springframework.data.redis.connection.RedisConnectionFactory import org.springframework.data.redis.connection.RedisStandaloneConfiguration import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory import org.springframework.data.redis.core.RedisTemplate import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer import org.springframework.data.redis.serializer.RedisSerializationContext import org.springframework.data.redis.serializer.RedisSerializer import java.time.Duration @Configuration @ConditionalOnProperty(name = ["spring.cache.type"], havingValue = "REDIS") @EnableCaching class RedisConfig( private val redisProperties: RedisProperties, private val customRedisSerializer: CustomRedisSerializer, ) { @Bean fun cacheManagerBuilderCustomizer(objectMapper: ObjectMapper): RedisCacheManagerBuilderCustomizer { return RedisCacheManagerBuilderCustomizer { it .withInitialCacheConfigurations(redisExpiresConfigurationMap(objectMapper)) } } @Bean fun redisTemplate(redisConnectionFactory: RedisConnectionFactory, objectMapper: ObjectMapper): RedisTemplate<String, Any> { return RedisTemplate<String, Any>().apply { connectionFactory = redisConnectionFactory keySerializer = RedisSerializer.string() valueSerializer = GenericJackson2JsonRedisSerializer(objectMapper) } } @Bean fun redisConnectionFactory(): RedisConnectionFactory { val redisStandaloneConfig = RedisStandaloneConfiguration(redisProperties.host, redisProperties.port) return LettuceConnectionFactory(redisStandaloneConfig) } private fun redisExpiresConfigurationMap(objectMapper: ObjectMapper) = CacheConstants.expiresMap.keys .associateWith { redisExpiresConfiguration(CacheConstants.expiresMap[it]!!, objectMapper) } private fun redisExpiresConfiguration(duration: Duration, objectMapper: ObjectMapper): RedisCacheConfiguration { return RedisCacheConfiguration.defaultCacheConfig(Thread.currentThread().contextClassLoader) .entryTtl(duration) .serializeValuesWith( // RedisSerializationContext.SerializationPair.fromSerializer(GenericJackson2JsonRedisSerializer(objectMapper)) RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.json()) ) } }
--- title: Common Issues description: Learn about common issues that you may encounter when using GitKraken Client. taxonomy: category: gitkraken-client --- *** ### General Troubleshooting for GitKraken Client 9.4.0+ In 9.4.0, GitKraken introduced the experimental feature for the [Git Executable](/gitkraken-client/experimental-features/#git-executable). As this is currently an experimental feature that our team is continuing to improve on, you can try adjusting your use of the Git Executable. Under `Preferences > Experimental`, first try adjusting the `Git Executable` version used. If you are using the “Bundled with GitKraken” version (comes pre-installed with GitKraken) try changing this to your own version of Git. If you do not have this installed, it can be downloaded [here](https://git-scm.com/download). The reason this may help is because the Bundled version is a minimal install of Git, which does not include all features (specifically bash programs that may be used in Git Hooks). <img src="/wp-content/uploads/gkc-git-executable-version.png" class="img-responsive center img-bordered"> If using your own version does not resolve the issue, try unchecking `Use Git Executable`. <img src="/wp-content/uploads/gkc-use-git-executable.png" class="img-responsive center img-bordered"> If this does resolve your issue, it is very important to note that GitKraken Client is transitioning all actions to the Git Executable (from LibGit2/nodegit) and the Git Executable will become the exclusive way GitKraken Client performs Git operations in a future release. As such, it is crucial for our team to be made aware of any issues related to using the Git Executable so we can look into and address them. Please reach out to our [support team](https://help.gitkraken.com/gitkraken-client/contact-support/) if you experience any issues with using this Experimental feature. For more information on what this feature is and why it is being implimented, you can check out this [blog post](https://www.gitkraken.com/blog/gitkraken-client-migrating-from-libgit2-to-git-executable). *** ## Integration - 1000 Error (1002, 1003, 1005, 1007) When attempting to connect to one of our integrations, you may see `Error 1002`, `Error 1003`, `Error 1005` or `Error 1007`. <img src="/wp-content/uploads/error-1002.png" srcset="/wp-content/uploads/error-1002@2x.png 2x" class="img-responsive center img-bordered"> ### Solution: These are general authentication errors. First, verify you used the correct credentials then try one of the following potential solutions: - If your credentials are correct, you can try signing out of the service in your default browser first, and then attempting the authentication from GitKraken Client again. - Clear your browser cache, sign out of the git hosting service, then restart GitKraken Client and try again. - If that is not working you can also try changing your operating system default browser to be a different browser. Once this is changed you can restart GitKraken Client and attempt to authenticate again. If that still does not work, please contact our [support team](https://www.gitkraken.com/contact) and we can troubleshoot further. *** ## Error when pushing a branch When attempting to push a branch, you may see the following `Push Failed: Cannot read property 'fullName' of undefined` error: <img src="/wp-content/uploads/push-error.png" class="img-responsive center img-bordered"> ### Solution: This usually indicates that there is a casing difference between the local branch and the upstream remote branch. You can rename the local branch to match the casing of the upstream remote branch, which will allow you to push the changes. <div class='callout callout--warning'> <p>Note: You may need an intermediate name change to get the branch named correctly. For example: Test-branch > temp-name > test-branch</p> </div> *** ## Some branches or files not appearing - Capitalization issue This most often occurs when having multiple remote banches nested together, but the capitalization differs. For example: `Feature/foo` and `feature/foo` may either be detected as the same branch OR a different branch depending on how your operating sytem treats capitalization. Most often this appears on Windows machines. Symptoms: - Branches not appearing in GitKraken - only one of the branches will be detected when they share a name. - This can also apply to files. If two files share the same name with only different capitalization one may appear deleted, moved, or not at all. - This can also manifest as the file being staged but not showing as staged when running a `git status`. To avoid these capitalization issues, we recommend giving each branch, file, and remote a unique name. *** ## Cannot log in - Cannot read property 'email' of null When trying to log in, you may see the following error: `Cannot read property 'email' of null`. This is commonly related to a network issue such as a proxy, firewall, or security application. The most common occurrence is something like Zscaler. ### Solution: If you have any of the above in place try the following: - Sign in with GitHub authentication - Approve the GitKraken application - Continue as free with 0 days - Click on free icon in bottom right, this brings up a web page inside GitKraken Client which authenticates against Zscaler - Restart GitKraken Client and authenticate normally This should allow you to log in without issue. *** ## Windows taskbar icon is not showing the GitKraken logo Some Windows users are seeing the taskbar icon show incorrectly for GitKraken. This is due to the start menu shortcut moving from ``C:\\Users\\USER\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Axosoft, LLC`` to ``C:\\Users\\USER\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\GitKraken``. ### Solution: You can delete the old folder ``C:\\Users\\USER\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Axosoft, LLC``, start GitKraken from the start menu, and then pin it to the taskbar again to resolve this. ## Why can't I see my GitHub remotes or repositories in the drop down menu? Why am I getting an error about GitHub organization permissions? In order to work with with a repository owned by a GitHub organization with the GitHub integrtion connected, you need an organization to first allow access. <img src="/wp-content/uploads/error.png" class="img-bordered img-responsive center"> * First check to see if access is allowed to GitKraken from your profile's [GitHub Applications](https://github.com/settings/connections/applications/a7557949433b7d282a76) * If access has been allowed, then the organization will need to allow [Organization Approval](https://help.github.com/articles/requesting-organization-approval-for-your-authorized-applications/) * If you are attempting to use GitKraken with a repository owned by a different individual, consider forking their repository to use GitKraken for your changes. Otherwise this other individual will need to first [install GitKraken](/gitkraken-client/how-to-install/) and connect it to GitHub to authorize GitKraken. * For details about third-party application restrictions view [Third-party apps list](https://help.github.com/articles/about-third-party-application-restrictions/)
/* * Edited version of gmod bouncing balls */ AddCSLuaFile() DEFINE_BASECLASS( "base_anim" ) ENT.PrintName = "Hungry Ball" ENT.Author = "Brokko" ENT.Spawnable = false ENT.AdminOnly = false ENT.RenderGroup = RENDERGROUP_TRANSLUCENT ENT.SpawnSize = 50 ENT.BouncingBoost = 20 function ENT:SetupDataTables() self:NetworkVar( "Float", 0, "BallSize", { KeyName = "ballsize", Edit = { type = "Float", order = 1 } } ) self:NetworkVar( "Vector", 0, "BallColor", { KeyName = "ballcolor", Edit = { type = "VectorColor", order = 2 } } ) if ( SERVER ) then self:NetworkVarNotify( "BallSize", self.OnBallSizeChanged ) end end function ENT:Initialize() -- We do NOT want to execute anything below in this FUNCTION on CLIENT if ( CLIENT ) then return end -- Use the helibomb model just for the shadow (because it's about the same size) self:SetModel( "models/Combine_Helicopter/helicopter_bomb01.mdl" ) -- We will put this here just in case, even though it should be called from OnBallSizeChanged in any case self:SetBallSize( self.SpawnSize ) self:RebuildPhysics( self:GetBallSize() ) self:GetPhysicsObject():SetBuoyancyRatio( 1.75 ) -- Select a random color for the ball self:SetBallColor( table.Random( { Vector( 1, 0.3, 0.3 ), Vector( 0.3, 1, 0.3 ), Vector( 1, 1, 0.3 ), Vector( 0.2, 0.3, 1 ), } ) ) end function ENT:RebuildPhysics( value ) -- This is necessary so that the vphysics.dll will not crash when attaching constraints to the new PhysObj after old one was destroyed -- TODO: Somehow figure out why it happens and/or move this code/fix to the constraint library self.ConstraintSystem = nil local size = math.floor( value / 2.1 ) self:PhysicsInitSphere( size, "metal_bouncy" ) self:SetCollisionBounds( Vector( -size, -size, -size ), Vector( size, size, size ) ) self:PhysWake() end if ( SERVER ) then function ENT:OnBallSizeChanged( varname, oldvalue, newvalue ) -- Do not rebuild if the size wasn't changed if ( oldvalue == newvalue ) then return end self:RebuildPhysics( newvalue ) end end local BounceSound = Sound( "garrysmod/balloon_pop_cute.wav" ) function ENT:PhysicsCollide( data, physobj ) -- Play sound on bounce local pitch = 32 + 128 - self:GetBallSize() sound.Play( BounceSound, self:GetPos(), 75, 180, math.Clamp( data.Speed / 150, 0, 1 ) ) -- Bounce like a crazy bitch local LastSpeed = math.max( data.OurOldVelocity:Length(), data.Speed ) local NewVelocity = physobj:GetVelocity() NewVelocity:Normalize() local TargetVelocity = NewVelocity * ( math.max( NewVelocity:Length(), LastSpeed ) + self.BouncingBoost ) physobj:SetVelocity( TargetVelocity ) local entity = data.HitEntity if(entity.GetBallProtected) then if(entity:GetBallProtected()) then return end end if (entity:IsNPC() or entity:IsPlayer()) then local d = DamageInfo() d:SetDamage( math.min( entity:Health(), LastSpeed / 10 )) d:SetAttacker( physobj:GetEntity() ) d:SetDamageType( DMG_CRUSH ) entity:TakeDamageInfo(d) --self:SetBallSize( self:GetBallSize() * 1.25 ) end end function ENT:OnTakeDamage( dmginfo ) -- React physically when shot/getting blown dmginfo:AddDamage(5000) self:TakePhysicsDamage( dmginfo ) end if ( SERVER ) then return end -- We do NOT want to execute anything below in this FILE on SERVER local matBall = Material( "sprites/sent_ball" ) function ENT:Draw() render.SetMaterial( matBall ) local pos = self:GetPos() local lcolor = render.ComputeLighting( pos, Vector( 0, 0, 1 ) ) local c = self:GetBallColor() lcolor.x = c.r * ( math.Clamp( lcolor.x, 0, 1 ) + 0.5 ) * 255 lcolor.y = c.g * ( math.Clamp( lcolor.y, 0, 1 ) + 0.5 ) * 255 lcolor.z = c.b * ( math.Clamp( lcolor.z, 0, 1 ) + 0.5 ) * 255 local size = self:GetBallSize() render.DrawSprite( pos, size, size, Color( lcolor.x, lcolor.y, lcolor.z, 255 ) ) end
<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%> <!-- //한글처리 --> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!-- // 반복문 c:forEach c:if--> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %> <!-- // model and view --> <%@ page session="false" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>1:1문의</title> <link rel="stylesheet" href="resources/css/bootstrap.css" /> <link rel="stylesheet" href="resources/css/v1_adminside.css" /> <link rel="stylesheet" href="resources/css/w3.css" /> <style> .modal-backdrop.in { z-index:auto; } .table-head{ font-color:white; } .title{ margin-top:50px; margin-bottom:20px; font-size:50px } .count{ width:100px; align:center } .btn_add{ margin-bottom:10px } .select{ width:50px; vertical-align:middle } </style> </head> <body> <div class="row"> <jsp:include page="v1_admin_header.jsp"></jsp:include> <div class="container-fluid"> <div class="side-body"> <div class="title">1:1문의</div> <div class="row"> <div class=" col-md-offset-8 col-md-4 form-inline" style="margin-bottom:10px;"> <select class="form-control" id="search_type"> <option value="all">전체</option> <option value="qst_title">질문</option> <option value="qst_content">내용</option> <option value="mb_id">아이디</option> </select> <input type="text" class="form-control" id="search_text" /> <button type="button" class="form-control btn-success" id="search_btn">검색</button> </div> </div> <table class="table"> <tr class="w3-dark-gray table-head"> <th style="vertical-align:middle">번호</th> <th style="vertical-align:middle">질문</th> <th style="vertical-align:middle">내용</th> <th style="vertical-align:middle">이미지</th> <th style="vertical-align:middle; width:120px"> <select class="form-control w3-dark-gray w3-border-dark-gray" id="sel_code"> <option ${param.sel_code == '유형' ? 'selected="selected"':''}>유형</option> <option ${param.sel_code == '예약' ? 'selected="selected"':''}>예약</option> <option ${param.sel_code == '결재' ? 'selected="selected"':''}>결재</option> <option ${param.sel_code == '환불' ? 'selected="selected"':''}>환불</option> <option ${param.sel_code == '리뷰' ? 'selected="selected"':''}>리뷰</option> <option ${param.sel_code == '서비스' ? 'selected="selected"':''}>서비스</option> <option ${param.sel_code == '기타' ? 'selected="selected"':''}>기타</option> </select> </th> <th style="width:120px"> <select class="form-control w3-dark-gray w3-border-dark-gray" id="sel_type"> <option value="all" ${param.sel_type == 'all' ? 'selected="selected"':''}>답변여부</option> <option value="0" ${param.sel_type == '0' ? 'selected="selected"':''}>미답변</option> <option value="1" ${param.sel_type == '1' ? 'selected="selected"':''}>답변완료</option> </select> </th> <th style="vertical-align:middle">아이디</th> <th style="vertical-align:middle">날짜</th> </tr> <c:forEach var="vo" items="${list}"> <tr> <td class="count qst_no">${vo.qst_no}</td> <td class="qst_title">${vo.qst_title}</td> <td style="width:300px" class="qst_content"><div class="con">${vo.qst_content}</div></td> <td style="width:300px"><img src="qnaImg.do?qst_no=${vo.qst_no}" width="300px" height="60px" class="checkimg" /></td> <td>${vo.qst_code}</td> <td> <c:if test="${vo.qst_open==0}"> <a href="#" class="btn btn-xs btn-danger btn_common btn_insert">답변등록</a> </c:if> <c:if test="${vo.qst_open==1}"> <a href="#" class="btn btn-xs btn-primary btn_common btn_update">답변완료</a> </c:if> </td> <td>${vo.mb_id}</td> <td>${vo.qst_date}</td> </tr> </c:forEach> </table> <div align="center"> <ul class="pagination"></ul> </div> </div> </div> </div> <form:form action="admin_qna.do?type=${param.type}&text=${param.text}&sel_code=${param.sel_code}&sel_type=${param.sel_type}&page=${param.page}" modelAttribute="vo" method="post"> <div class="modal fade" id="insertmodal"> <div class="modal-dialog"> <div class="modal-content" style="width:700px; height:850px;"> <div class="modal-header"> <h4>답변등록</h4> </div> <div class="modal-body"> <div class="form-inline" style="margin-top:3px; margin-bottom:3px"> <form:input type="hidden" id="qst_no" path="qst_no" /> <label style="width:120px">제목</label> <input type="text" class="form-control" style="width:400px;" id="qst_title" readonly /> </div> <div class="form-inline" style="margin-top:3px; margin-bottom:3px"> <label style="width:120px">질문</label> <textarea class="form-control" style="width: 400px; resize:none;" rows="15" id="qst_content" readonly></textarea> </div> <div class="form-inline" style="margin-top:3px; margin-bottom:3px"> <label style="width:120px">답변</label> <form:textarea class="form-control" path="qst_as_content" style="width: 400px; resize:none;" rows="15"></form:textarea> </div> </div> <div class="modal-footer"> <input type="submit" class="btn btn-success" value="등록" /> <button type="button" class="btn btn-default" data-dismiss="modal">취소</button> </div> </div> </div> </div> </form:form> <form:form action="admin_qna_update.do?type=${param.type}&text=${param.text}&sel_code=${param.sel_code}&sel_type=${param.sel_type}&page=${param.page}" method="post" modelAttribute="vo"> <div class="modal fade" id="updatemodal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h2>답변수정</h2> </div> <div class="modal-body"> <div class="form-inline" style="margin-top:3px; margin-bottom:3px"> <form:input type="hidden" id="qst_no1" path="qst_no" /> <label style="width:120px">제목</label> <input type="text" class="form-control" style="width:400px;" id="qst_title1" readonly /> </div> <div class="form-inline" style="margin-top:3px; margin-bottom:3px"> <label style="width:120px">질문</label> <textarea class="form-control" style="width: 400px; resize:none;" rows="15" id="qst_content1" readonly></textarea> </div> <div class="form-inline" style="margin-top:3px; margin-bottom:3px"> <label style="width:120px">답변</label> <form:textarea class="form-control" path="qst_as_content" style="width: 400px; resize:none;" rows="15" id="qst_as_content1"></form:textarea> </div> <div class="form-inline" style="margin-top:3px; margin-bottom:3px"> <label style="width:120px">답변날짜</label> <input type="text" id="qst_as_date" class="form-control" style="width:400px;" readonly /> </div> </div> <div class="modal-footer"> <input type="submit" class="btn btn-success" value="수정" /> <button type="button" class="btn btn-default" data-dismiss="modal">취소</button> </div> </div> </div> </div> </form:form> <div class="modal fade" id="checkmodal"> <div class="modal-dialog"> <div class="modal-content" style="width:700px"> <div class="modal-header"> <h2>사진확인</h2> </div> <div class="modal-body"> <div class="form-inline" style="margin-top:3px; margin-bottom:3px"> <img src="" width="650px" height="650px" id="check_img"/> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-success" data-dismiss="modal">확인</button> </div> </div> </div> </div> <script type="text/javascript" src="resources/js/jquery-1.9.1.min.js"></script> <script type="text/javascript" src="resources/js/bootstrap.min.js"></script> <script type="text/javascript" src="resources/js/readmore.min.js"></script> <script type="text/javascript" src="resources/js/jquery.twbsPagination-1.3.1.js"></script> <script> $(function() { $('.con').readmore({ blockCSS: 'display: block;', speed: 75, collapsedHeight: 65, moreLink: '<a href="#" style="color:blue;"><span class="glyphicon glyphicon-triangle-bottom" aria-hidden="true"></span>자세히</a>', lessLink: '<a href="#" style="color:blue;"><span class="glyphicon glyphicon-triangle-top" aria-hidden="true"></span>숨김</a>' }); $('.checkimg').click(function(){ var idx = $(this).index('.checkimg'); var arr = new Array(); <c:forEach var="vo" items="${list}"> var arr1 = new Array() arr1.push("${vo.qst_no}"); arr.push(arr1); </c:forEach> $('#check_img').attr('src', 'qnaImg.do?qst_no='+arr[idx][0]); $('#checkmodal').modal('show'); }); $('.pagination').twbsPagination({ totalPages:'${totPage}', visiblePages:10, href:'?type=${param.type}&text='+encodeURIComponent('${param.text}')+'&sel_code='+encodeURIComponent('${param.sel_code}')+'&sel_type=${param.sel_type}&page={{number}}' }); $('#sel_type').change(function(){ var sty = $(this).val(); window.location.href="admin_qna.do?type=${param.type}&text=${param.text}&sel_code=${param.sel_code}&sel_type="+sty+"&page=1"; }); var func = function(){ var ty = $('#search_type').val(); var tx = encodeURIComponent($('#search_text').val()); window.location.href="admin_qna.do?type="+ty+"&text="+tx+"&sel_code=${param.sel_code}&sel_type=${param.sel_type}&page=1"; }; $('#search_btn').click(function(){ func(); }); $('#search_text').keyup(function(event){ if(event.which == 13){ func(); } }); $('#sel_code').change(function(){ var sty = $(this).val(); window.location.href="admin_qna.do?type=${param.type}&text=${param.text}&sel_code="+sty+"&sel_type=${param.sel_type}&page=1"; }); $('.btn_update').click(function(){ var idx = $(this).index('.btn_common'); var qst_no = $('.qst_no').eq(idx).text(); $('#qst_no1').val(qst_no); $('#qst_title1').val($('.qst_title').eq(idx).text()); $('#qst_content1').val($('.qst_content').eq(idx).text()); $.get('ajax_qst_answer.do?qst_no='+qst_no,function(data){ $('#qst_as_content1').val(data.qst_as_content); $('#qst_as_date').val(data.qst_as_date); },'json'); $('#updatemodal').modal('show'); }); $('.btn_insert').click(function(){ var idx = $(this).index('.btn_common'); $('#qst_no').val($('.qst_no').eq(idx).text()); $('#qst_title').val($('.qst_title').eq(idx).text()); $('#qst_content').val($('.qst_content').eq(idx).text()); $('#insertmodal').modal('show'); }); $('.navbar-toggle').click(function () { $('.navbar-nav').toggleClass('slide-in'); $('.side-body').toggleClass('body-slide-in'); $('#search').removeClass('in').addClass('collapse').slideUp(200); /// uncomment code for absolute positioning tweek see top comment in css //$('.absolute-wrapper').toggleClass('slide-in'); }); // Remove menu for searching $('#search-trigger').click(function () { $('.navbar-nav').removeClass('slide-in'); $('.side-body').removeClass('body-slide-in'); /// uncomment code for absolute positioning tweek see top comment in css //$('.absolute-wrapper').removeClass('slide-in'); }); }); </script> </body> </html>
import { Register, UUID } from '@boostercloud/framework-types' import { Command } from '@boostercloud/framework-core' import { DrinkOrdered } from '../events/drink-ordered' import { Mom, Dad } from '../roles' @Command({ authorize: [Mom, Dad], }) export class OrderCocktail { public constructor( readonly drink: string, readonly tid?: string // input used by test utilities ) {} public static async handle(command: OrderCocktail, register: Register): Promise<void> { // check inputs if (!command.drink || command.drink === '') throw new Error('What drink does today call for?') const orderId = command.tid || UUID.generate().toString() const orderTakenBy = ['Erik', 'Abi'][Math.floor(Math.random() * 2)] // do work const capitalize = (s: string): string => s.charAt(0).toUpperCase() + s.slice(1) // register events if (command.drink) { register.events( new DrinkOrdered( orderId, // capitalize(command.drink), orderTakenBy ) ) } } }
<div class="login-Page"> <div class="mainlogin-container"> <div class="form-container"> <div class="form-header"> <img src="../../../assets/images/logo_new.svg"> </div> <div class="form-body"> <form [formGroup]="signinForm" (ngSubmit)="loginUser()"> <div class="form-wrapper"> <div class="form-group mt-2" *ngIf="submitted && loginError"> <div class="alert alert-danger" role="alert" > {{ errorMessage }} </div> </div> <div class="form-group"> <label for="username">Email</label> <input type="text" class="form-control" formControlName="username" name="username" [ngClass]="{ 'is-invalid': submitted && f['username'].errors }" /> <div *ngIf="submitted && f['username'].errors" class="invalid-feedback"> <div *ngIf="f['username'].errors['required']">Please enter Username</div> <!--<div *ngIf="f['username'].errors['email']">Email is invalid</div>--> </div> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" class="form-control" name="password" formControlName="password" [ngClass]="{ 'is-invalid': submitted && f['password'].errors }" /> <div *ngIf="submitted && f['password'].errors" class="invalid-feedback"> <div *ngIf="f['password'].errors['required']"> Please enter Password</div> <!--<div *ngIf="f['password'].errors['minlength']"> Password must be at least 6 characters </div> <div *ngIf="f['password'].errors['maxlength']"> Password must not exceed 20 characters </div>--> </div> </div> </div> <div class="form-group mt-2 text-center instructorbtn"> <button class="btn logInbtn"> Login </button> </div> </form> </div><!-- End of "form-body" --> </div><!-- End of "form-container" --> </div><!-- End of "mainlogin-container" --> </div>
require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({41:[function(require,module,exports){ (function (global){ 'use strict'; var _jquery = (typeof window !== "undefined" ? window['jQuery'] : typeof global !== "undefined" ? global['jQuery'] : null); var _jquery2 = _interopRequireDefault(_jquery); var _debounce = require('lodash/debounce'); var _debounce2 = _interopRequireDefault(_debounce); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * toggle.js */ var toggle = function toggle() { /** * Get Panel from toggle. */ function getTogglePanel($toggle) { var $panel = (0, _jquery2.default)('#' + $toggle.attr('aria-controls')); return $panel.length > 0 ? $panel : false; } /** * Click Handler. */ function collapseGroup(group) { var $group = (0, _jquery2.default)('[data-toggleGroup="' + group + '"]').trigger('collapse'); } /** * Click Handler. */ function onToggleClick(event) { if (event.type === 'keydown') { var code = event.charCode || event.keyCode; // 27 === 'Escape' if (code == 27) { (0, _jquery2.default)(event.currentTarget).trigger('collapse'); return; } } if (event.type === 'keydown') { var _code = event.charCode || event.keyCode; if (_code !== 32 && _code !== 13) { return; } } var $target = (0, _jquery2.default)(event.currentTarget); var wasExpanded = $target.attr('aria-expanded') === 'true'; // Collapse other toggles in the group. var group = $target.attr('data-toggleGroup'); if (group) { collapseGroup(group); } $target.trigger(wasExpanded ? 'collapse' : 'expand'); event.preventDefault(); return false; } function onHandleEscape(event) { var $panel = (0, _jquery2.default)(event.currentTarget); var $trigger = (0, _jquery2.default)('[aria-controls="' + $panel.attr('id') + '"]'); if (event.type === 'keydown') { var code = event.charCode || event.keyCode; // 27 === 'Escape' if (code !== 27) { return; } } $trigger.trigger('collapse').focus(); } /** * Collapse Handler. */ function onToggleCollapse(event) { var $target = (0, _jquery2.default)(event.target); var $panel = getTogglePanel($target); // Update this toggle's state. $target.attr('aria-expanded', 'false'); // Collapse this panel. if ($panel) { $panel.trigger('collapse'); $panel.off('keydown', onHandleEscape); } } /** * Expand Handler. */ function onToggleExpand(event) { var $target = (0, _jquery2.default)(event.target); var $panel = getTogglePanel($target); // Update this toggle's state. $target.attr('aria-expanded', 'true'); // Expand this panel. if ($panel) { $panel.trigger('expand'); $panel.on('keydown', onHandleEscape); } } /** * Expand Handler. */ function onBodyClick(event) { var $target = (0, _jquery2.default)(event.target); // Ignore toggles. if ($target.is('.toggle')) { return false; } // Ignore children of expanded panels. if ($target.parents('[aria-expanded="true"]').length >= 1) { return; } // Close all focused toggles. (0, _jquery2.default)('[data-toggleFocused]').trigger('collapse'); } // Click handler that closes tabs when clicked outside of a tab. function onGeneralFocus(event) { var $target = (0, _jquery2.default)(event.target); if (!$target.is('[aria-haspopup][aria-expanded="true"], [role="dialog"][aria-expanded="true"] *')) { (0, _jquery2.default)('[data-toggleFocused]').trigger('collapse'); } } /** * Bind Toggles. */ function bindUi() { var toggle = this, $body = (0, _jquery2.default)('body'); $body.on('touchstart.toggle mousedown.toggle keydown', '.toggle[aria-controls], .js-toggle[aria-controls]', // Keep this from calling multiple time. (0, _debounce2.default)(onToggleClick, 300, { leading: true, trailing: false })); $body.on('expand.toggle', onToggleExpand); $body.on('collapse.toggle', onToggleCollapse); $body.on('touchstart.toggle mousedown.toggle', (0, _debounce2.default)(onBodyClick, 300, { leading: true, trailing: false })); $body.on('focusin.toggle', onGeneralFocus); } return { init: function init() { bindUi(); } }; }; (function ($) { $(document).ready(function () { toggle().init(); }); })(jQuery); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"lodash/debounce":49}],49:[function(require,module,exports){ var isObject = require('./isObject'), now = require('./now'), toNumber = require('./toNumber'); /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max, nativeMin = Math.min; /** * Creates a debounced function that delays invoking `func` until after `wait` * milliseconds have elapsed since the last time the debounced function was * invoked. The debounced function comes with a `cancel` method to cancel * delayed `func` invocations and a `flush` method to immediately invoke them. * Provide `options` to indicate whether `func` should be invoked on the * leading and/or trailing edge of the `wait` timeout. The `func` is invoked * with the last arguments provided to the debounced function. Subsequent * calls to the debounced function return the result of the last `func` * invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the debounced function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.debounce` and `_.throttle`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to debounce. * @param {number} [wait=0] The number of milliseconds to delay. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=false] * Specify invoking on the leading edge of the timeout. * @param {number} [options.maxWait] * The maximum time `func` is allowed to be delayed before it's invoked. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * // Avoid costly calculations while the window size is in flux. * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); * * // Invoke `sendMail` when clicked, debouncing subsequent calls. * jQuery(element).on('click', _.debounce(sendMail, 300, { * 'leading': true, * 'trailing': false * })); * * // Ensure `batchLog` is invoked once after 1 second of debounced calls. * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); * var source = new EventSource('/stream'); * jQuery(source).on('message', debounced); * * // Cancel the trailing debounced invocation. * jQuery(window).on('popstate', debounced.cancel); */ function debounce(func, wait, options) { var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } wait = toNumber(wait) || 0; if (isObject(options)) { leading = !!options.leading; maxing = 'maxWait' in options; maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; trailing = 'trailing' in options ? !!options.trailing : trailing; } function invokeFunc(time) { var args = lastArgs, thisArg = lastThis; lastArgs = lastThis = undefined; lastInvokeTime = time; result = func.apply(thisArg, args); return result; } function leadingEdge(time) { // Reset any `maxWait` timer. lastInvokeTime = time; // Start the timer for the trailing edge. timerId = setTimeout(timerExpired, wait); // Invoke the leading edge. return leading ? invokeFunc(time) : result; } function remainingWait(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall; return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting; } function shouldInvoke(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; // Either this is the first call, activity has stopped and we're at the // trailing edge, the system time has gone backwards and we're treating // it as the trailing edge, or we've hit the `maxWait` limit. return (lastCallTime === undefined || (timeSinceLastCall >= wait) || (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); } function timerExpired() { var time = now(); if (shouldInvoke(time)) { return trailingEdge(time); } // Restart the timer. timerId = setTimeout(timerExpired, remainingWait(time)); } function trailingEdge(time) { timerId = undefined; // Only invoke if we have `lastArgs` which means `func` has been // debounced at least once. if (trailing && lastArgs) { return invokeFunc(time); } lastArgs = lastThis = undefined; return result; } function cancel() { if (timerId !== undefined) { clearTimeout(timerId); } lastInvokeTime = 0; lastArgs = lastCallTime = lastThis = timerId = undefined; } function flush() { return timerId === undefined ? result : trailingEdge(now()); } function debounced() { var time = now(), isInvoking = shouldInvoke(time); lastArgs = arguments; lastThis = this; lastCallTime = time; if (isInvoking) { if (timerId === undefined) { return leadingEdge(lastCallTime); } if (maxing) { // Handle invocations in a tight loop. timerId = setTimeout(timerExpired, wait); return invokeFunc(lastCallTime); } } if (timerId === undefined) { timerId = setTimeout(timerExpired, wait); } return result; } debounced.cancel = cancel; debounced.flush = flush; return debounced; } module.exports = debounce; },{"./isObject":50,"./now":53,"./toNumber":54}],54:[function(require,module,exports){ var isObject = require('./isObject'), isSymbol = require('./isSymbol'); /** Used as references for various `Number` constants. */ var NAN = 0 / 0; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Built-in method references without a dependency on `root`. */ var freeParseInt = parseInt; /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } module.exports = toNumber; },{"./isObject":50,"./isSymbol":52}],52:[function(require,module,exports){ var baseGetTag = require('./_baseGetTag'), isObjectLike = require('./isObjectLike'); /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && baseGetTag(value) == symbolTag); } module.exports = isSymbol; },{"./_baseGetTag":44,"./isObjectLike":51}],51:[function(require,module,exports){ /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } module.exports = isObjectLike; },{}],44:[function(require,module,exports){ var Symbol = require('./_Symbol'), getRawTag = require('./_getRawTag'), objectToString = require('./_objectToString'); /** `Object#toString` result references. */ var nullTag = '[object Null]', undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } module.exports = baseGetTag; },{"./_Symbol":43,"./_getRawTag":46,"./_objectToString":47}],47:[function(require,module,exports){ /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } module.exports = objectToString; },{}],46:[function(require,module,exports){ var Symbol = require('./_Symbol'); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } module.exports = getRawTag; },{"./_Symbol":43}],43:[function(require,module,exports){ var root = require('./_root'); /** Built-in value references. */ var Symbol = root.Symbol; module.exports = Symbol; },{"./_root":48}],53:[function(require,module,exports){ var root = require('./_root'); /** * Gets the timestamp of the number of milliseconds that have elapsed since * the Unix epoch (1 January 1970 00:00:00 UTC). * * @static * @memberOf _ * @since 2.4.0 * @category Date * @returns {number} Returns the timestamp. * @example * * _.defer(function(stamp) { * console.log(_.now() - stamp); * }, _.now()); * // => Logs the number of milliseconds it took for the deferred invocation. */ var now = function() { return root.Date.now(); }; module.exports = now; },{"./_root":48}],48:[function(require,module,exports){ var freeGlobal = require('./_freeGlobal'); /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); module.exports = root; },{"./_freeGlobal":45}],45:[function(require,module,exports){ (function (global){ /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; module.exports = freeGlobal; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],50:[function(require,module,exports){ /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } module.exports = isObject; },{}]},{},[41]);
import { Component, EventEmitter, Input, Output } from '@angular/core'; import { Producto, CreateProductDTO, UpdateProductDTO, } from '../../../website/components/models/producto.model'; import { StoreService } from 'src/app/services/store.service'; import { ProductsService } from 'src/app/services/products.service'; import { switchMap } from 'rxjs'; @Component({ selector: 'app-productos', templateUrl: './productos.component.html', styleUrls: ['./productos.component.scss'], }) export class ProductosComponent { total = 0; myShopCar: Producto[] = []; @Input() products: Producto[] = []; today = new Date(); date = new Date(2021, 1, 21); @Output() loadedMore: EventEmitter<string> = new EventEmitter<string>(); // @Input() productId: string | null = null; @Input() set productId(id: string | null) { if (id) { this.onShowDetail(id); } } loadMore() { this.loadedMore.emit(); } statusDetail: 'loading' | 'success' | 'error' | 'init' = 'init'; showProductDetail = false; productChosen: Producto = { id: '', title: '', price: 0, images: [], description: '', category: { id: -1, name: '', }, }; constructor( private storeService: StoreService, private productService: ProductsService ) { this.myShopCar = this.storeService.getMyShopCar(); } onAddToShopCar(product: Producto) { this.storeService.addProduct(product); this.total = this.storeService.getTotal(); } toggleProduct() { this.showProductDetail = !this.showProductDetail; } onShowDetail(id: string) { this.statusDetail = 'loading'; if (!this.showProductDetail) { this.showProductDetail = true; } this.productService.getProduct(id).subscribe( (data) => { this.productChosen = data; this.statusDetail = 'success'; }, (errorMsg) => { window.alert(errorMsg); this.statusDetail = 'error'; } ); } readAndUpdate(id: string) { this.productService .getProduct(id) .pipe( switchMap((product) => this.productService.update(product.id, { title: 'change' }) ) ) .subscribe((data) => { console.log(data); }); this.productService .fetchReadAndUpdate(id, { title: 'string nuevo' }) .subscribe((response) => { const red = response[0]; const update = response[1]; console.log(red, update); }); } createNewProduct() { const product: CreateProductDTO = { categoryId: 1, title: 'Nuevo producto', price: 200, images: [`https://placeimg.com/640/480/any?random=${Math.random()}`], description: 'Lorem Ipsum Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit... There is no one who loves pain itself, who seeks after it and wants to have it, simply because it is pain... ', }; this.productService.create(product).subscribe((data) => { this.products.unshift(data); }); } updateProduct() { const changes: UpdateProductDTO = { title: 'nuevo titulo', }; const id = this.productChosen.id; this.productService.update(id, changes).subscribe((data) => { const productIndex = this.products.findIndex((item) => item.id == id); this.products[productIndex] = data; this.productChosen = data; }); } deleteProduct() { const id = this.productChosen.id; this.productService.delete(id).subscribe(() => { const productIndex = this.products.findIndex((item) => item.id == id); this.products.splice(productIndex, 1); this.showProductDetail = false; }); } }
# Sensitivity analysis for the participants with and without # psychological support following the accident. # # Participants with a psychological support or with psychological # therapy/psychiatric therapy are coded as individuals with the support insert_head() # container ------- se_support <- list() # analysis data for the psychological support strata ------- insert_msg('Psychometry for the psychological support strata') se_support$data <- ptsd$dataset %>% mutate(psych_support_post_accident = ifelse(psych_support_post_accident == 'yes' | psych_therapy_post_accident == 'yes', 'yes', 'no'), psych_support_post_accident = factor(psych_support_post_accident, c('no', 'yes'))) %>% minus_level_data(split_factor = 'psych_support_post_accident', extremes = FALSE) %>% set_names(c('support', 'without_support')) # Cluster analysis objects ------- insert_msg('Cluster analysis objects') ## the global solution for all participants included in the analysis se_support$clust_obj$global <- se_globals$clust_obj ## structures with the strata se_support$clust_obj[names(se_support$data)] <- se_support$data %>% map(kcluster, distance_method = 'cosine', clust_fun = 'pam', k = 3, seed = 1234) ## re-naming after the key cluster characteristics ## and for consistency with the global cluster solution se_support$clust_obj$support <- se_support$clust_obj$support %>% rename(c('2' = 'neutral', '3' = 'PTG', '1' = 'PTS')) se_support$clust_obj$without_support <- se_support$clust_obj$without_support %>% rename(c('2' = 'neutral', '3' = 'PTG', '1' = 'PTS')) # Characteristic of the clustering structures -------- insert_msg('Characteristic of the clustering structures') se_support$stats <- se_support$clust_obj %>% map(summary) %>% compress(names_to = 'dataset') %>% relocate(dataset) ## cluster distribution se_support$clust_size <- se_support$clust_obj %>% map(ngroups) %>% map(mutate, n_total = sum(n), percent = n/n_total * 100) # Assignment of the support strata to the clusters ------ insert_msg('Assignment of the support strata to the clusters') se_support$assignment <- se_support$clust_obj %>% map(extract, 'assignment') %>% map(set_names, c('ID', 'clust_id')) %>% map(left_join, ptsd$dataset[c('ID', 'psych_support_post_accident')], by = 'ID') %>% map(~filter(.x, complete.cases(.x))) # END ------- insert_tail()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>javascrip</title> </head> <!-- _Valor por Referencia: ______________________ _en las variables, su valor es dinámico y puede cambiar en el tiempo es decir, que su valor lo podremos alterar en el tiempo posteriormente haciendo referencia a la respectiva veriale y re asignándole un nuevo valor _más en los objeto esto no es así, cuando una variable hace referencia a un objeto, ej; var proof1 = { nombre: "Juán"; } var proof2 = proof1; console.log(proof1, proof2); _en éste ejemplo creamos el objeto proof, con una propiedad de "nombre", y asu vez creamos el objeto "proof2", con el valor del objeto "proof1" _más que pasará si accedemos a la propiedad "nombre", del objeto "proof", y cambiamos su valor, ej; _proof1.nombre = "Pedro"; _en éste caso cuando llamemos a la variable "proof2", ahora ésta también, tendrá el mismo valor de propiedad de "Pedro", que el del objeto "proof1" _de ésta manera, podremos ver que cuando un objecto hace referencia ha otro objeto, éstos compartirán todas sus propiedades internas y características --> <!--ejemplo para la creación del entorno de javascript--> <script type="text/javascript"> var proof1 = { nombre: "Juán" } var proof2 = proof1; console.log(proof1, proof2); proof1.nombre = "Pedro"; console.log(proof2); </script> <body> </body> </html>
Problem Description Construct a class Rectangle that represents a rectangle. The class should support the following functionalities:- perimeter() -> returns the perimeter of the rectangle area() -> returns the area of the rectangle Input format: First argument A is an integer representing the number of testcases. For each case, x (length) and y (breadth) are taken as input in new line. Output format: The perimeter and area of the constructed rectangle are printed. class Rectangle { // Define properties here int length; int breadth; // Define constructor here Rectangle(int x,int y){ length=x; breadth=y; } int perimeter(){ // Complete the function int a = (2*(length+breadth)); return a; } int area(){ // Complete the function int b = length*breadth; return b; } } /* Rectangle a = new Rectangle(2, 3) // Length = 2, Breadth = 3 a.perimeter() // Should give 10 a.area() // Should give 6 */
import { File } from './file'; export class Directory { private name: string; private files: File[]; private directories: Directory[]; private parent: Directory | null; private size: number; constructor( name: string, parent: Directory | null = null, files: File[] = [], directories: Directory[] = [], size = 0 ) { this.name = name; this.files = files; this.directories = directories; this.parent = parent; this.size = size; } setSize = (size: number) => { this.size = size; }; getSize = (): number => { return this.size; }; addFile = (file: File) => { this.files.push(file); }; addDirectory = (directory: Directory) => { this.directories.push(directory); }; getName = (): string => { return this.name; }; getFiles = (): File[] => { return this.files; }; getDirectories = (): Directory[] => { return this.directories; }; getDirectory = (directoryName: string): Directory | null => { for (const directory of this.directories) { if (directory.name === directoryName) { return directory; } } return null; }; getParent = (): Directory | null => { return this.parent; }; hasDirectory = (directoryName: string): boolean => { for (const directory of this.directories) { if (directory.name === directoryName) { return true; } } return false; }; }
import { useNavigate, Form, redirect } from 'react-router-dom'; import { destroyClient } from '../data/clients'; export async function action({ params }) { await destroyClient(params.clientId); return redirect('/'); } function Client({ client }) { const navigate = useNavigate(); const { id, nombre, telefono, email, empresa } = client; return ( <tr className=" border-b hover:bg-gray-100"> <td className="p-6">{id}</td> <td className="p-6 space-y-2"> <p className=" text-2xl text-gray-800">{nombre}</p> <p>{empresa}</p> </td> <td className="p-6"> <p className=" text-gray-600"> <span className=" text-gray-800 uppercase font-bold">Email: </span> {email} </p> <p className=" text-gray-600"> <span className=" text-gray-800 uppercase font-bold">Tel: </span> {telefono} </p> </td> <td className="p-6 flex gap-3"> <button onClick={() => navigate(`/clientes/${id}/editar`)} type="button" className=" text-blue-600 hover:text-blue-700 font-bold uppercase text-xs" > Editar </button> <Form method="post" action={`/clientes/${id}/eliminar`} onSubmit={(e) => { if (!confirm(`¿Deseas eliminar el registro de ${nombre}?`)) { e.preventDefault(); } }} > <button type="submit" className=" text-red-600 hover:text-red-700 font-bold uppercase text-xs" > Eliminar </button> </Form> </td> </tr> ); } export default Client;
# Ilyatoo graph vis ![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg) [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier) Enjoy a graph visualization of the [Ilyatoo](https://ilyatoo.com/) data. ## Development guide First, clone the repo: ```bash git clone https://github.com/Tomansion/IlyatooGraphApp.git cd IlyatooGraphApp ``` ### Backend The backend is made with Python and requests / flask, it is based on a OpenAPI specification, check the [OpenAPI specification](./back/api.yaml) for more information. #### Requirements - Python v3.8 - pip v23.1.2 #### How to setup ```bash cd backend pip install -r requirements.txt ``` #### Configuration Fill the [config file](./backend/config/config.ini) with your ArangoDB credentials. #### Run the backend ```bash python websrv.py ``` Check the SwaggerUI at [http://localhost:3000/api/ui](http://localhost:3000/api/ui) [Testing guide](./backend/tests/README.md) #### Good practices Check that your code is compliant with our linter Black: ```bash black . ``` ### Frontend The frontend is made with VueJS. #### Requirements - NodeJS v19.0.0c - npm v8.19.2 #### How to setup ```bash cd frontend npm install ``` #### Run the frontend ```bash npm run serve ``` The frontend is now available by connecting to the backend URL at [http://localhost:3000](http://localhost:3000) #### Good practices Check that your code is compliant with our linter Prettier: ```bash npm run prettier ``` Check that your code has no spelling mistakes: ```bash npm run spellcheck ``` ### Recommended development environment - VSCode with extensions: - [Vetur](https://marketplace.visualstudio.com/items?itemName=octref.vetur) - [Black](https://marketplace.visualstudio.com/items?itemName=lextudio.restructuredtext) - [Cspell](https://marketplace.visualstudio.com/items?itemName=streetsidesoftware.code-spell-checker) - [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode)
#ifndef LISTS_H #define LISTS_H #include <stdio.h> #include <stdlib.h> /** * struct listint_s - A singly linked list * @n: Pointer to an integer * @next: Pointer to the next node. * Descrption: Singly linked list node struct */ typedef struct listint_s { int c; struct listint_s *next; } listint_t; size_t print_listint(const listint_t *h); listint_t *add_nodeint_end(listint_t **head, const int n); void free_listint(listint_t *head); int is_palindrome(listint_t **head); #endif /* LISTS_H */
import BasicCard from "../../components/BasicCard"; import StakingSteps from "./StakingSteps"; import { useState } from "react"; import StakingForm from "./StakingForm"; import DurationForm from "./DurationForm"; import ReviewForm from "./ReviewForm"; import { useNavigate } from "react-router-dom"; import { Duration, StakingContext } from "./StakingContext"; function StakingSectionHeader() { return ( <div className="flex flex-col justify-start text-lext w-full"> <h1 className="text-white text-lg font-quicksand font-semibold"> Stake your tokens </h1> </div> ); } export default function StakingSection() { const [currentStep, setCurrentStep] = useState(1); const [stakingAmount, setStakingAmount] = useState(0); const [stakingDuration, setStakingDuration] = useState<Duration>(); const navigate = useNavigate(); const handleSetStakingAmount = () => { setCurrentStep(2); }; const handleSelectDuration = () => { setCurrentStep(3); }; const handleBack = () => { setCurrentStep(currentStep - 1); }; const handleStake = () => { navigate("/my-rewards"); }; return ( <section className="relative flex flex-col justify-between md:top-0 md:pt-[160px] pt-[120px]"> <div className="flex flex-col lg:flex-row justify-between w-full gap-6 max-w-[760px] mx-auto px-6 md:px-7 lg:px-4"> <StakingContext.Provider value={{ stakingAmount, stakingDuration, setStakingAmount, setStakingDuration, }} > <BasicCard className="max-w-[900px] md:mt-10 bg-[#0F1015]/90 border-white/5 px-6 md:px-10"> <div className="flex flex-col gap-8 justify-center items-start w-full"> <div className="flex flex-col gap-2 justify-start items-start w-full h-full"> <StakingSectionHeader /> <hr className="my-3 border-gray-200 sm:mx-auto dark:border-white/5 lg:my-3 w-full" /> <StakingSteps activeStep={currentStep} /> <hr className="my-3 border-gray-200 sm:mx-auto dark:border-white/5 lg:my-3 w-full" /> {currentStep === 1 && ( <StakingForm onSubmit={handleSetStakingAmount} /> )} {currentStep === 2 && ( <DurationForm onSubmit={handleSelectDuration} onBack={handleBack} /> )} {currentStep === 3 && ( <ReviewForm onSubmit={handleStake} onBack={handleBack} /> )} </div> </div> </BasicCard> </StakingContext.Provider> </div> </section> ); }
<!DOCTYPE html> <html lang="en"> <head> <title>Hyperbolic Navigation</title> <meta charset="utf-8"> <!-- css --> <style> @media print { body { margin-left: 0; margin-right: 0; } } @media (min-width:320px) { body { margin-left: 6%; margin-right: 6%; } h1 { font-family: sans-serif; font-weight: bold; font-size: 1.7em; text-align: justify; } h2 { font-family: sans-serif; font-weight: bold; font-size: 1.5em; text-align: justify; } p { font-family: serif; text-align: justify; font-size: 1.3em; } } @media (min-width:481px) { body { margin-left:6%; margin-right: 6%; } h1 { font-family: sans-serif; font-weight: bold; font-size: 1.7em; text-align: justify; } h2 { font-family: sans-serif; font-weight: bold; font-size: 1.5em; text-align: justify; } p { font-family: serif; text-align: justify; font-size: 1.3em; } } @media (min-width:641px) { body { margin-left: 8%; margin-right: 8%; } h1 { font-family: sans-serif; font-weight: bold; font-size: 1.7em; text-align: justify; } h2 { font-family: sans-serif; font-weight: bold; font-size: 1.5em; text-align: justify; } p { font-family: serif; text-align: justify; font-size: 1.3em; } } @media (min-width:961px) { body { margin-left: 10%; margin-right: 10%; } h1 { font-family: sans-serif; font-weight: bold; font-size: 1.9em; text-align: justify; } h2 { font-family: sans-serif; font-weight: bold; font-size: 1.7em; text-align: justify; } p { font-family: serif; text-align: justify; font-size: 1.5em; } } @media (min-width:1025px) { body { margin-left: 25%; margin-right: 25%; } h1 { font-family: sans-serif; font-weight: bold; font-size: 1.9em; text-align: justify; } h2 { font-family: sans-serif; font-weight: bold; font-size: 1.7em; text-align: justify; } p { font-family: serif; text-align: justify; font-size: 1.5em; } } @media (min-width:1281px) { body { margin-left: 25%; margin-right: 25%; } h1 { font-family: sans-serif; font-weight: bold; font-size: 1.9em; text-align: justify; } h2 { font-family: sans-serif; font-weight: bold; font-size: 1.7em; text-align: justify; } p { font-family: serif; text-align: justify; font-size: 1.5em; } } </style> </head> <body> <h1>Introduction</h1> <p>I often take satellite navigation systems such as GPS for granted, and it got me thinking about how dependent we are on that technology, and how on earth people managed in the past. This article documents my findings.</p> <p>It covers the concept of latitude and longitude, and how navigation was performed on ships using star or sun location, and measuring time. </p> <p>By the 20th century, during World War 2, techniques were developed that relied on clusters or 'chains' of ground station radio transmitters broadcasting signals that could be received on planes and ships. Each transmission within a chain had a certain time relationship with each other. The article discusses how that information could trace out invisible curved (hyperbolic-shaped) lanes over land or sea, and how those curves could form a sort of grid.</p> <p>There is also a brief look at how GPS works.</p> <h1>Longitude and Time-keeping</h1> <p>In the introduction of a book called <a href="https://www.amazon.co.uk/Longitude-Genius-Greatest-Scientific-Problem/dp/080271529X">Longitude</a>, Neil Armstrong mentions how <a href="https://en.wikipedia.org/wiki/Pope_Alexander_IV">Pope Alexander IV</a> drew a vertical line from North to South, and assigned all lands to the two top maritime powers of Europe: all lands to the west to Spain, and all to the right to Portugal. The problem was, no-one knew for sure where the line fell, so it was hard to argue who owned what!</p> <p>The problem of identifying precise longitude was of high importance, because sailors would routinely perish, because of the difficulty of determining where land was.</p> <p><img title="Latitude and Longitude diagram" width="100%" align="left" src="assets\diag-lat-lon-explained.jpg"></p> <p><strong>Latitude</strong> (angle indicating how far up or down the globe) was not too difficult to figure out, because it could be determined in several ways; for instance you could search for particular stars (for instance the North Star, and measuring the angle of it from the horizon). A quick daytime method would be to measure the angle of the sun from your visible horizon, which is known as the sun's angle of elevation, and subtract it from 90. Then, a correction is needed because the earth tilts up to plus or minus 23.4 degrees over the course of the year; it's seasonal (about +23.4 degrees in mid-June, and -23.4 degrees in mid-December, and is close to zero mid-March and mid-September), is easy to calculate, and is called the sun's angle of declination. You'd need to subtract the magnitude of that angle of declination, to get an accurate result.</p> <p><img title="Measuring Latitude" width="100%" align="left" src="assets\diag-latitude.jpg"></p> <p>However, <strong>longitude</strong> starts at an arbitrary man-made position (it happens to be in Greenwich, London). There are many stories of ships traveling the wrong distance east or west around the globe, and poor longitude estimates resulted in either crashing into rocks, or overshooting or undershooting land, and, with depleting food, and risk of scurvy, the captain would decide to turn around, and upon traveling for days or weeks, only to then realize that the first direction must have been correct. Just on one voyage, two thousand sailors on four warships died for want of better navigation, and eventually, the UK government issued a reward (worth millions in today's money) for a solution. It went unclaimed for more than half a century.</p> <p>Some people believed the solution lay with correct timing, however, clocks were inaccurate in the 1700's!</p> <p>The reason time is important, is that, (there are several ways, but this is the easiest to understand) by simply looking at the position of the sun (which moves across the sky at 15 degrees per hour), and knowing the time at the Greenwich Meridian, you can determine your longitude. For example, if the sun is directly above you, and the time at Greenwich is 1 pm, then you know that your longitude must be 15 degrees west of Greenwich.</p> <p>There were some crackpot suggestions for the time problem, one of them being 'the wounded dog' method. There was a theory that a particular medicine had mystical powers of 'healing at a distance' if the original bandage was soaked in it. The logic went that if a dog were deliberately wounded and then placed on a ship, then someone on land could daily soak the bandage at noon, and the distant wounded dog would let out a yelp at that precise time since the medicine would sting in the wound. You'd just need to deliberately prevent the wound from fully healing, for months while out to voyage.</p> <p>The person who actually solved the problem without mystic medicine, <a href="https://en.wikipedia.org/wiki/John_Harrison">John Harrison</a>, was treated badly by his government, and, for a lifetime's work, received just a small reward with only three years of life left to enjoy it. John Harrison's solution was an ultra-accurate timepiece (so accurate, it easily competes with modern quartz watches some 250 years later!) that could withstand operation on ships.</p> <h1>Hyperbolic Radio Navigation</h1> <p>Fast-forward to the period approaching World War 2, and now there were requirements for accurate airborne navigation. Various radio-based ideas were considered, and it was soon very obvious that relying simply on signal strength was not very feasible because it was hard to accurately measure signal strength at a distance because it dropped off so quickly, and therefore the inaccuracies would be significant.</p> <p>It was felt by some that pulse-based (RADAR was a secret at that time) or phase-based systems might hold more promise.</p> <p><img title="Hyperbola Lines" width="100%" align="left" src="assets\burst-phase-systems.jpg"></p> <p>This opened up a whole range of possibilities, collectively known as hyperbolic navigation systems. If you have two transmitters transmitting in phase, or transmitting pulses simultaneously, then if a receiver is exactly halfway between the two transmitters, then the signals arrive in phase (or pulses arrive simultaneously). If, however, the receiver is at a different location, then there will be a phase or delay difference. The difference remains the same if the receiver is at any location which traces a hyperbola. The diagram below shows why.</p> <p>The concentric circles emanating from one transmitter site indicate the positions where signals arrive at fixed times. If you try to intersect those circles with those from the other transmitter location, such that the difference between the pairs of ranges always remains a fixed distance, then hyperbolae are traced out. All the hyperbolae in the diagram below, have the same fixed difference of phase or pulse, the colors are just to identify separate lines or 'lanes', but if the receiver is on any of these lines, the phase difference is the same. For any given delay or phase difference, it is possible to plot a set of hyperbolae.</p> <p><img title="Hyperbola Lines" width="100%" align="left" src="assets\hyperbolae-lines.jpg"></p> <p>What the above means is that if you have a way of measuring the phase difference or pulse arrival delay between the two transmitters, you can place yourself on a set of hyperbolae. You won't know which of the hyperbola lines you are on, however.</p> <p>Various things can be done to try to identify the particular hyperbola out of the set. One method is for the two transmitters to sweep through phase relative to each other. That results in the hyperbola lines bending as the phase changes so that the receiver sees a time-varying signal strength, an increase in received signal when they are on a hyperbola, and a decrease when they are in between two lines. Then, timing can help identify which hyperbola you're on. Another method is to switch to a lower frequency, so that there are fewer hyperbola lines temporarily, so that the receiver can coarsely resolve, before switching to a higher frequency.</p> <h1>Pulses: Gee System (QH)</h1> <p>One system developed in the UK, later called the Gee system (known as 'QH' during WW2), relied on pulses. A master transmitter would synchronize three slave transmitters, all transmitting a pulse at the same frequency after a fixed pause from the master transmission. Together, these four transmitters are known as a <strong>chain</strong>.</p> <p><img title = "Gee diagram" width="100%" align="left" src="assets\gee-diagram2.jpg"></p> <p>At the receiver end, the pulses were observed on a little display (known as an oscilloscope) that charted the pulse blips over time. The circuitry would direct the pulses onto two visual graphical traces. The master transmitter pulse was observed on both traces. The next received pulse would be sent to the top trace. The pulse after that was sent to the second trace. The final pulse was sent to both traces, but it happened to be a double pulse, so it could be distinguished. The operator would measure the distance between the pulses, and the intersecting hyperbolae would provide a position fix.</p> <p>The photo here shows a Gee receiver and display unit.</p> <p><img title = "Gee receiver and display" width="100%" align="left" src="assets\gee-photo.jpg"></p> <p>Image source: <a href="https://commons.wikimedia.org/wiki/File:J_M_Briscoe24_07_200713_05_14IMG2104_GEE_AIRBORNE.JPG">Wikipedia</a></p> <p>There is some excellent detail (including beautiful photographs) at <a href="https://www.radiomuseum.co.uk/rf25.html">radiomuseum.co.uk</a>.</p> <p>Since there was no trigger circuitry, the operator manually fine-tuned until the pulses sat in the correct position on the display. Best-case accuracy was about 150 meters, but at distances of several hundred miles, the error could easily be several miles.</p> <p>Gee was used during WW2 for navigation around the UK.</p> <h1>Phase: Decca Navigation (QM)</h1> <p>For Operation Overlord (Battle of Normandy), a different navigation system was used, called QM (later called the Decca Navigational System). The idea was invented by William O'Brien and Harvey Schwarz in the USA but gained significant interest in the UK and was trialed in 1941 on the Welsh coast. The system relied on phase difference, rather than measuring the time between pulses. The way it worked was that a master site and a number of slaves (two or three), together known as a chain, all transmitted signals at different frequencies, but all locked to a base frequency. The receiver would multiply pairs of received signals to a common frequency and then work out the phase difference.</p> <p>In 1943, the base frequency <strong>f</strong> was 14 kHz, and the master and two slaves transmitted at <strong>6f</strong>, <strong>8f</strong> and <strong>9f</strong> respectively (i.e. 84, 112 and 126 kHz).</p> <p>At the receiving end, the master and first slave received signals would be separately multiplied by 4 and 3 respectively, i.e. 84 x 4 and 112 x 3, which would result in two signals both of frequency 24f (336 kHz), but with different phase, depending on location with respect to the master and the first slave.</p> <p>Similarly, the master and second slave signals would be separately multiplied by 3 and 2, resulting in two signals of frequency 18f (252 kHz), again with a phase relationship. (Later, a third slave was added, at a frequency of <strong>5f</strong>).</p> <p>Just as shown in the earlier diagram, hyperbola lines could be drawn at any phase relationship, for instance when the signals are in phase, at zero degrees.</p> <p>The lines were used as '<strong>lanes</strong>' during Operation Overlord, creating invisible paths through the English Channel towards Normandy. Minesweepers followed those paths, allowing ships and landing craft to follow.</p> <p><img title="Decca test (1941) and deployment (1944)" width="100%" align="left" src="assets\nav-map-oo.jpg"></p> <p>The receiver didn't use an oscilloscope but instead used a center-zero meter that would display the phase shift. The lanes were separated by several hundred meters. A tiny movement (a few feet) off one of the lanes would cause a phase shift from zero, which would move the meter needle significantly. By seeing the number of deflections, the lines could be easily counted. After WW2, further improvements to the system were made, so that lane counting became unnecessary. By the time the system was fully mature, the transmitter sites were transmitting signals at different frequencies, over a 20-second period, repeatedly, and the sequence was quite complex. A very good collection of information about the Decca system can be found at <a href="http://www.jproc.ca/hyperbolic/decca.html">Jerry Proc's website</a>.</p> <p>By the 1980's or so, there were about 50 chains deployed. The diagram below shows the European chains; 25 were deployed there. The circled values are unique chain numbers. The slave transmitters within each chain had color-code identifiers (red, green, purple).</p> <p><img title="Decca European chains" width="100%" align="left" src="assets\european-chains.jpg"></p> <p>Image source: Philips</p> <p>The Decca system was deployed in many regions, and was used commercially until about the year 2000. The receivers were made by Racal Decca, but eventually other manufacturers, particularly Philips, built them too. This model is made by Philips, despite the Racal logo.</p> <p><img title="Decca Yacht Navigator Mk III" width="100%" align="left" src="assets\yn-photo.jpg"></p> <p>If you're curious what's inside, the photo below shows all the interesting bits in the lower half of the case (the other half just houses the LCD digit displays and keypad).</p> <p><img title="Decca Yacht Navigator internals, annotated" width="100%" align="left" src="assets\yn-parts-annotated.jpg"></p> <p>There appears to be a frequency synthesizer, two simultaneous RF receivers (so that the phase between pairs of signals can be measured), and everything is co-ordinated with an 8085-based microprocessor. </p> <h1>Summary</h1> <p>It's easy to take satellite-based navigation systems for granted these days, but there was a time when thousands of lives would frequently be lost due to the difficulty of determining longitude. Although that was solved in the 18th century, there were new demands during WW2.</p> <p>Prior to GPS deployment, hyperbolic navigation systems were the state-of-the-art, a couple of them being QH and QM, or Gee and Decca, respectively. The Decca system relied on phase measurement to place the receiver on hyperbolic lines or lanes and, with multiple transmitters, onto a grid of lanes. After WW2, the system was adapted for commercial use and ran successfully until the year 2000. An example of a Decca navigation system receiver was examined briefly.</p> <p>There were many other hyperbolic or hyperbolic-like navigation systems that are not covered here. Some systems were incrementally improved upon, and others were independently developed. </p> <p>Thanks for reading.</p> <h2>Further Reading: Quick Look at Satellite-Based Navigation: How Does it Work?</h2> <p>Now that pre-GPS techniques have been discussed, you may be interested in how GPS and other Global Navigation Satellite Systems (GNSS) function.</p> <p>There are well over a hundred satellites in orbit, which transmit signals containing timing information and satellite position. The timing information comes from an ultra-precise clock inside each satellite. The satellite position can be pictured by imagining a sphere surrounding the planet. The satellite position can be defined using two angles: the angle from one of the poles, and the angle around the sphere (a bit like longitude), which meet up at the satellite location on that sphere.</p> <p>The timing information, and the satellite position information, are transmitted at a frequency of about 1.5 GHz, and, due to the distance of the satellite orbit, it takes about 10 msec to arrive on Earth.</p> <p> In the case of GPS, there are six orbital paths, about 20,000 km overhead, each with multiple satellites spaced out.</p> <p><img title = "GPS orbits" width="100%" align="left" src="assets\gps-orbits.jpg"></p> <p>The received signal is very weak and would be impossible to pull out of the noise, so it is sent relatively slowly (50 bits per second), with each bit of data being encoded with a special (much faster) binary pattern before it's transmitted. The GPS receiver tries to match up the pattern. When it does that, then, mathematically, the signal can be recovered from the noise; the pattern is known as a pseudo-random sequence (although it contains the word 'random', it's not random in the normal sense; it looks random to a casual viewer, but in reality it has a pattern that can be exactly replicated by the receiver), and the matching effect is known as autocorrelation. Together, it is known as Spread Spectrum communication. The signal directed toward Earth is invisible by the time it arrives (since it's below the noise floor!) until autocorrelation is achieved by the receiving system.</p> <p>Another neat trick is that many satellites can transmit simultaneously, each with a different pseudo-random sequence, and the receiver can, in parallel, perform multiple matching operations, to achieve autocorrelation for each signal.</p> <p>The receiver is designed to have the ability to time things too, but not to the same accuracy as the satellites! The receiver will locally timestamp the arrival time of each message, and then compare that local timestamp with the time encoded in the satellite signals. Once there are signals from at least four satellites (the more the better!), then there is enough information to use simultaneous equations, to solve for the location of the receiver.</p> <p>Today, there are more global navigation systems than just GPS out there; there is also Galileo (European), BeiDou (Chinese) and GLONASS (Russian), all operating in a similar way. There are also more geographically-specific navigation systems too. A GNSS receiver (colloquially known as a GPS receiver) can receive information from several of the navigation systems, and therefore provide more accurate location information, by selecting based on received signal quality.</p> <p>In order to make use of GNSS, nowadays a single chip can be used. The chip will typically receive the RF signals, shift them to a much lower frequency, then perform the correlation operation, and then pre-programmed software inside the chip will compute the receiver location. The pre-programmed software has a model of the Earth, to try to reduce errors in altitude (height) measurement, say, above sea level. </p> <p>The altitude is interesting to briefly consider; the earth isn't spherical, it bulges a little, i.e. it is slightly ellipsoidal, plus, on top of that, sea level depends on gravity, and gravity isn't constant across the earth. Where the earth is denser, it attracts more water, and the mean sea level rises there. There is an internal table of heights inside the chip, and the reported altitude takes that into account, to try to provide an altitude value that is referenced off that internal table of mean sea levels at the reported location. It's known as an orthometric height. </p> <h2>Further Reading (References)</h2> <p><a href="https://www.amazon.co.uk/Longitude-Genius-Greatest-Scientific-Problem/dp/080271529X">Longitude</a> book by Dava Sobel</p> <p><a href="https://digital-library.theiet.org/content/journals/10.1049/jiere.1985.0069">Early History of the Decca Navigation System</a> - Powell</p> <p><a href="https://elektrotanya.com/showresult?what=decca+yacht&kategoria=All&kat2=All">Decca Yacht Navigator User Manual</a></p> <p><a href="http://www.jproc.ca/hyperbolic/decca.html">Decca website</a> by Jerry Proc</p> </body> </html>
create table test_retention ( uid String COMMENT '用户', eventId String COMMENT '事件名称', city String COMMENT '事件发生所在城市', region String COMMENT '大区名称', eventTime DateTime COMMENT '事件时间' ) engine = Memory; insert into test_retention values ('小明', '签到', '厦门', '服务器1', '2020-01-01'), ('小明', '签到', '厦门', '服务器1', '2020-01-02'), ('小明', '签到', '厦门', '服务器1', '2020-01-03'), ('小东', '签到', '厦门', '服务器1', '2020-01-01'), ('小东', '签到', '厦门', '服务器1', '2020-01-02'), ('小张', '签到', '厦门', '服务器1', '2020-01-01'), ('小张', '签到', '厦门', '服务器1', '2020-01-03'), ('小林', '签到', '厦门', '服务器1', '2020-01-01'), ('小红', '签到', '北京', '服务器2', '2020-01-01'), ('小明', '签到', '北京', '服务器2', '2020-01-02'), ('小明', '北京', '厦门', '服务器2', '2020-01-03'), ('小绿', '签到', '北京', '服务器2', '2020-01-01'), ('小东', '签到', '北京', '服务器2', '2020-01-02'), ('小白', '签到', '北京', '服务器2', '2020-01-01'), ('小张', '签到', '北京', '服务器2', '2020-01-03'), ('小黑', '签到', '北京', '服务器2', '2020-01-01'); -- retention 函数可以方便的计算留存情况,该函数接受多个条件,以第一个条件的结算结果为基准 -- 观察后面的各个条件是否也满足,满足则为1,不满足则为0,最终返回0和1的数组。 -- 通过统计1的数量,即可计算出留存率 -- 下面的sql语句计算 次日重复下单率,三日重复下单率,七日重复下单率 with toDate('2020-01-01') as first_date select sum(ret[1]) as original, arrayFilter(x -> x != '',groupArray(ret_uid[1])) as original_uid, sum(ret[2]) as one_day_ret, arrayFilter(x -> x != '',groupArray(ret_uid[2])) as one_day_uid, if(original = 0, 0, round(one_day_ret/original*100, 2)) as one_day_ratio, sum(ret[3]) as two_day_ret, arrayFilter(x -> x != '',groupArray(ret_uid[3])) as two_day_uid, if(original = 0, 0, round(two_day_ret/original*100, 2)) as two_day_ratio, sum(ret[4]) as three_day_ret, arrayFilter(x -> x != '',groupArray(ret_uid[4])) as three_day_uid, if(original = 0, 0, round(three_day_ret/original*100, 2)) as three_day_ratio, sum(ret[5]) as four_day_ret, arrayFilter(x -> x != '',groupArray(ret_uid[5])) as four_day_uid, if(original = 0, 0, round(four_day_ret/original*100, 2)) as four_day_ratio, sum(ret[6]) as five_day_ret, arrayFilter(x -> x != '',groupArray(ret_uid[6])) as five_day_uid, if(original = 0, 0, round(five_day_ret/original*100, 2)) as five_day_ratio, sum(ret[7]) as six_day_ret, arrayFilter(x -> x != '',groupArray(ret_uid[7])) as six_day_uid, if(original = 0, 0, round(six_day_ret/original*100, 2)) as six_day_ratio, sum(ret[8]) as seven_day_ret, arrayFilter(x -> x != '',groupArray(ret_uid[8])) as seven_day_uid, if(original = 0, 0, round(seven_day_ret/original*100, 2)) as seven_day_ratio from ( select uid, retention( eventTime = first_date, eventTime = first_date + interval 1 day, eventTime = first_date + interval 2 day, eventTime = first_date + interval 3 day, eventTime = first_date + interval 4 day, eventTime = first_date + interval 5 day, eventTime = first_date + interval 6 day, eventTime = first_date + interval 7 day ) as ret, arrayMap(x -> if(x == 1, uid, ''), ret) as ret_uid from ( select * from ( select * from test_retention where (eventId = '签到' and eventTime = first_date and city != '上海') -- 初始事件单独筛选条件 or (eventId = '签到' and eventTime between first_date + interval 1 day and first_date + interval 7 day and city != '上海') -- 回访事件单独筛选条件 ) where city != '海南' -- 全局筛选条件 and eventTime between first_date and first_date + interval 7 day -- 该行是 事件时间筛选区间 ) group by uid );
const { Sequelize } = require('sequelize') const db = require('../models') const uuid = require('uuid') class QuartoService { async cadastrar(dto) { const quarto = await db.quartos.findOne({ where: { numero: dto.numero } }) if (quarto) { throw new Error('Quarto já cadastrado') } try { const novoQuarto = await db.quartos.create({ id: uuid.v4(), nome: dto.nome, descricao: dto.descricao, numero: dto.numero, quartotipo_id: dto.quartotipo_id }) return novoQuarto } catch (error) { throw new Error('Erro ao cadastrar quarto') } } async buscarTodosQuartos() { const quartos = await db.quartos.findAll({ include: [{ model: db.quartostipos, as: 'quarto_tipoquarto', attributes: ['id','nome'] }], order: [['numero','ASC']] }) return quartos } async buscarTodosQuartosLivres() { const quartos = await db.quartos.findAll({ include: [{ model: db.quartostipos, as: 'quarto_tipoquarto', attributes: ['id','nome'] }], where: { estado: 0 }, order: [['numero','ASC']] }) return quartos } async buscarQuartoPorId(id) { const quarto = await db.quartos.findOne({ include: [{ model: db.quartostipos, as: 'quarto_tipoquarto', attributes: ['id','nome'] }], where: { id: id } }) if (!quarto) { throw new Error('Quarto informado não cadastrado') } return quarto } async editarQuarto(dto) { const quarto = await this.buscarQuartoPorId(dto.id) try { quarto.nome = dto.nome, quarto.descricao = dto.descricao, quarto.numero = dto.numero, quarto.estado = dto.estado, quarto.quartotipo_id = dto.quartotipo_id await quarto.save() return quarto } catch (error) { throw new Error('Erro ao editar quarto') } } async removerLimpeza(dto) { const quarto = await this.buscarQuartoPorId(dto.quarto_id) try { quarto.estado = 0 await quarto.save() return quarto } catch (error) { throw new Error('Erro ao remover quarto da limpeza') } } async deletarQuarto(id) { await this.buscarQuartoPorId(id) try { await db.quartos.destroy({ where: { id: id } }) } catch (error) { throw new Error('Erro ao tentar excluir o quarto') } } } module.exports = QuartoService
package uk.gov.pay.ledger.expungeorredact.resource; import com.codahale.metrics.annotation.Timed; import com.google.inject.Inject; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import org.slf4j.MDC; import uk.gov.pay.ledger.expungeorredact.service.ExpungeOrRedactService; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import java.util.UUID; import static uk.gov.service.payments.logging.LoggingKeys.MDC_REQUEST_ID_KEY; @Path("/v1/tasks") @Produces("application/json") @Tag(name = "Tasks") public class ExpungeOrRedactResource { private final ExpungeOrRedactService expungeOrRedactService; @Inject public ExpungeOrRedactResource(ExpungeOrRedactService expungeOrRedactService) { this.expungeOrRedactService = expungeOrRedactService; } @Path("/expunge-or-redact-historical-data") @POST @Timed @Operation( summary = "Redacts/Removes historical data based on `expungeOrRedactHistoricalDataConfig`. Currently redacts PII from transactions and deletes related transaction events", responses = { @ApiResponse(responseCode = "200", description = "OK"), } ) public Response expungeOrRedactData() { String correlationId = MDC.get(MDC_REQUEST_ID_KEY) == null ? "ExpungeOrRedactResource-" + UUID.randomUUID() : MDC.get(MDC_REQUEST_ID_KEY); MDC.put(MDC_REQUEST_ID_KEY, correlationId); expungeOrRedactService.redactOrDeleteData(); MDC.remove(MDC_REQUEST_ID_KEY); return Response.ok().build(); } }
import React, { Component, Fragment } from 'react'; import ReactImageFallback from "react-image-fallback"; import { NavLink } from 'react-router-dom'; import { AJAX_REQUEST, CURRENCY_FORMAT, GET_STORAGE } from "../../../Constants/AppConstants"; import AlertWrapperSuccess from '../../Common/AlertWrapperSuccess'; class SubscriptionCancellationDetails extends Component { constructor(props) { super(props) // Check Tax let settings = ''; if (GET_STORAGE('settings')) { settings = JSON.parse(GET_STORAGE('settings')); } this.state = { loading: true, taxStatus: settings ? settings.tax_status : 0, subscription_id: parseInt(this.props.match.params.subscription_id), items: [], subtotal: 0, shipping_charge: 0, tax_amount: 0, shipping_method: "", payment_method: "", subscription_type: "", duration: "", total: 0, error_meg: '', success_alert_wrapper_show: false } document.title = "Subscription Item Details -Prestige Labs"; } componentDidMount() { document.querySelector("body").scrollIntoView() // Scroll to Top document.getElementById("pageTitle").innerHTML = "SUBSCRIPTION #" + this.state.subscription_id; this.getSubscriptionDetails(); } getSubscriptionDetails = () => { let data = { subscription_id: this.state.subscription_id } AJAX_REQUEST("POST", "subscription/getDetails", data).then(results => { if (parseInt(results.response.code) === 1000) { let subs = results.response.data.subscription this.setState({ items: subs.items, subtotal: subs.subtotal, shipping_charge: subs.shipping_charge, tax_amount: subs.tax_amount, shipping_method: subs.shipping_method, payment_method: subs.payment_method, subscription_type: subs.subscription_type, duration: subs.duration, total: subs.total, loading: false, }); } else { this.setState({ error_meg: results.response.message, loading: false, }); } }); } removeSubscriptionItem = (itemId) => { if (window.confirm('Are you sure you want remove this item from your subscription?')) { document.querySelector("body").scrollIntoView() // Scroll to Top this.setState({ loading: true, error_meg: '', success_alert_wrapper_show: false }); let data = { subscription_id: this.state.subscription_id, subscription_item_id: itemId } AJAX_REQUEST("POST", "subscription/removedItem", data).then(results => { if (parseInt(results.response.code) === 1000) { this.setState({ error_meg: results.response.message, loading: false, success_alert_wrapper_show: true }); this.getSubscriptionDetails(); setTimeout(function () { this.setState({ success_alert_wrapper_show: false }); }.bind(this), 3000); } else { this.setState({ error_meg: results.response.message, loading: false, success_alert_wrapper_show: false }); } }); } } render() { return ( <Fragment> { this.state.loading ? <div className="loading"></div> : <div className="MyAccount-content"> <AlertWrapperSuccess errors_data={this.state.error_meg} success_alert_wrapper_show={this.state.success_alert_wrapper_show} /> <section className="woocommerce-order-details"> <h2 className=" montserrat page-title">SUBSCRIPTION ITEM DETAILS { (this.state.subscription_type == 'supplement') ? <NavLink to={`/subscription-item/${this.state.subscription_id}`} className="pull-right roboto_condensed wc-forward">Add New Item</NavLink> : <NavLink to={`/meals?subscription_id=${this.state.subscription_id}`} className="pull-right roboto_condensed wc-forward">Change Meal Item</NavLink> } </h2> <table className="my_account_orders my_account_orders_view "> <colgroup> <col width="5%" /> <col width="" /> <col width="40%" /> </colgroup> <thead> <tr> <th></th> <th className="text-center"><b>{(this.state.subscription_type == 'supplement') ? "Product" : "Meal Item"}</b></th> <th className="text-center"><b>Total</b></th> </tr> </thead> <tbody> { this.state.items.length <= 0 ? <tr><td className="text-center" colSpan="3">No Item Found!</td></tr> : this.state.items.map(function (item, key) { if ((this.state.status === "Cancelled") || (this.state.status === "Failed")) { return ( <tr key={key}> <td className="product_name"><a data-item={item.hasOwnProperty('item_id') ? item.item_id : ''} className="remove"><i className="fa fa-times" aria-hidden="true"></i></a> </td> <td className="product_name"> {item.hasOwnProperty('name') ? item.name : ''} <strong className="product-quantity">&nbsp;× {item.hasOwnProperty('quantity') ? item.quantity : ''}</strong> </td> <td> <span>{item.hasOwnProperty('total_price') ? CURRENCY_FORMAT(item.total_price) : ''}</span> / {item.duration} </td> </tr> ) } else { return ( <tr key={key}> <td className="product_name"> { (this.state.subscription_type == 'supplement') ? <a data-item={item.hasOwnProperty('item_id') ? item.item_id : ''} onClick={() => this.removeSubscriptionItem(item.item_id)} className="remove"><i className="fa fa-times" aria-hidden="true"></i></a> : "" } </td> <td className="product_name"> {item.hasOwnProperty('name') ? item.name : ''} <strong className="product-quantity">&nbsp;× {item.hasOwnProperty('quantity') ? item.quantity : ''}</strong> </td> <td> <span>{item.hasOwnProperty('total_price') ? CURRENCY_FORMAT(item.total_price) : ''}</span> / {item.duration} </td> </tr> ) } }.bind(this)) } <tr> <td colSpan="2">Subtotal:</td> <td><span><strong>{CURRENCY_FORMAT(this.state.subtotal)}</strong></span></td> </tr> <tr> <td colSpan="2">Shipping:</td> <td><span>{CURRENCY_FORMAT(this.state.shipping_charge)}</span><small className="shipped_via">&nbsp; via {this.state.shipping_method}</small></td> </tr> { (this.state.taxStatus == 1) ? <Fragment> <tr> <td colSpan="2">Tax:</td> <td><span>{CURRENCY_FORMAT(this.state.tax_amount)}</span></td> </tr> </Fragment> : null } <tr> <td colSpan="2">Payment method:</td> <td><span>{this.state.payment_method}</span></td> </tr> <tr> <td colSpan="2">Total:</td> <td><span><strong>{CURRENCY_FORMAT(this.state.total)}</strong></span> / {this.state.duration} </td> </tr> </tbody> </table> </section> </div> } </Fragment> ); } } export default SubscriptionCancellationDetails;
import { createContext, useContext, useState, useEffect } from 'react'; const CartContext = createContext(); export const useCart = () => useContext(CartContext); export const CartProvider = ({ children }) => { const savedCart = localStorage.getItem('YoursCart'); const parsedCart = JSON.parse(savedCart) ?? []; const [amount, setAmount] = useState(0); const [cart, setCart] = useState(parsedCart); useEffect(() => { const summ = cart.reduce( (acc, product) => acc + Number(product.quantity), 0 ); setAmount(summ); localStorage.setItem('YoursCart', JSON.stringify(cart)); }, [cart]); const changeAmount = items => { setAmount(items); }; const addToCart = (idProduct, product, quantity) => { if (cart.some(i => i._id === idProduct)) { setCart( cart.map(item => { if (item._id === product._id) { return { ...item, quantity: Number(item.quantity) + Number(quantity), }; } return item; }) ); return; } setCart([...cart, { ...product, quantity }]); }; return ( <CartContext.Provider value={{ amount, changeAmount, cart, setCart, addToCart }} > {children} </CartContext.Provider> ); };
import pandas as pd import numpy as np from typing import Union, Iterable, Optional from functools import partial from scipy.stats import linregress from collections.abc import Iterable from concurrent.futures import ProcessPoolExecutor """ Technical Indicators documentation: ### Volume Based Indicators: 1. **volume_adi (Accumulation/Distribution Index)** - **Calculation:** The ADI is computed by calculating the Money Flow Multiplier, which is then multiplied by the period's volume. This product is then added to the previous period's ADI value. - Money Flow Multiplier = ((Close - Low) - (High - Close)) / (High - Low) - ADI = Previous ADI + (Money Flow Multiplier * Volume) 2. **volume_obv (On-Balance Volume)** - **Calculation:** OBV is a cumulative total of volume. Volume is added to the indicator if closing price moves up and subtracted if closing price moves down. - If today's close > yesterday's close, OBV = previous OBV + today's volume. - If today's close < yesterday's close, OBV = previous OBV - today's volume. 3. **volume_cmf (Chaikin Money Flow)** - **Calculation:** CMF combines price and volume to measure the buying and selling pressure over a set period. It is the sum of Accumulation/Distribution for 20 periods divided by the sum of volume for 20 periods. - CMF = ∑[(Close - Low) - (High - Close)] / (High - Low) * Volume / ∑ Volume 4. **volume_fi (Force Index)** - **Calculation:** The Force Index uses price and volume to measure the power behind a price move. The shorter the period, the more volatile the indicator. - FI = Volume * (Current Close - Previous Close) 5. **volume_em (Ease of Movement)** - **Calculation:** EoM indicates how easily prices move. A large positive value indicates the price moved up on low volume. - EoM = [(High + Low)/2 - (Previous High + Previous Low)/2] / (Volume / 10^6 / (High - Low)) 6. **volume_sma_em (Simple Moving Average of Ease of Movement)** - **Calculation:** This is simply the SMA of the EoM values over a specified period, often 14 days. - SMA of EoM = Sum of EoM over N periods / N 7. **volume_vpt (Volume-Price Trend)** - **Calculation:** VPT is a cumulative volume-based indicator used to show the direction of the trend. - VPT = Previous VPT + (Volume * (Today’s Close - Previous Close) / Previous Close) 8. **volume_vwap (Volume Weighted Average Price)** - **Calculation:** VWAP gives the average price a security has traded at throughout the day, based on volume and price. It is often used as a trading benchmark. - VWAP = ∑ (Typical Price * Volume) / ∑ Volume - Where Typical Price = (High + Low + Close) / 3 9. **volume_mfi (Money Flow Index)** - **Calculation:** MFI uses both price and volume to measure buying and selling pressure. Often called the volume-weighted RSI. - Raw Money Flow = Typical Price * Volume - Money Ratio = Positive Money Flow / Negative Money Flow - MFI = 100 - (100 / (1 + Money Ratio)) 10. **volume_nvi (Negative Volume Index)** - **Calculation:** NVI focuses on days where the volume decreases from the previous day. If volume decreases, NVI is adjusted by the percentage change in price. - If today's volume < yesterday's volume, NVI = yesterday's NVI + (today's close - yesterday's close) / yesterday's close * yesterday's NVI. - If today's volume ≥ yesterday's volume, NVI is unchanged. ### Momentum Indicators: 1. **momentum_rsi (Relative Strength Index)** - **Calculation:** RSI measures the speed and change of price movements. It is calculated using average gains and losses over a specified period, typically 14 days. - RSI = 100 - (100 / (1 + (Average Gain / Average Loss))) 2. **momentum_stoch_rsi (Stochastic RSI)** - **Calculation:** The Stoch RSI applies the Stochastic formula to RSI values, instead of price values, to measure RSI's momentum. - Stoch RSI = (RSI - Lowest Low RSI) / (Highest High RSI - Lowest Low RSI) 3. **momentum_stoch_rsi_k (Stochastic RSI K)** - **Calculation:** Represents the current value of the Stochastic RSI. It's essentially the same as the Stoch RSI value and can sometimes refer to a smoothed version using a moving average. 4. **momentum_stoch_rsi_d (Stochastic RSI D)** - **Calculation:** The D line is the simple moving average of the Stochastic RSI K line. It's used to smooth out the K line for better signal interpretation. - Stoch RSI D = 3-day SMA of Stoch RSI K 5. **momentum_tsi (True Strength Index)** - **Calculation:** TSI is a momentum oscillator that blends the price momentum with its moving average. It is calculated by taking a double smoothed moving average of the price momentum. - TSI = (Double Smoothed Price Change / Double Smoothed Absolute Price Change) * 100 6. **momentum_uo (Ultimate Oscillator)** - **Calculation:** The UO combines short, medium, and long-term market trends in one indicator. It uses three different time frames and weights them into a final oscillating value. - UO = [(4 x SMA1) + (2 x SMA2) + SMA3] / (4 + 2 + 1) - Where SMA1, SMA2, and SMA3 are the average ratios of buying pressure to true range over their respective periods. 7. **momentum_stoch (Stochastic Oscillator)** - **Calculation:** This indicator measures the current price relative to its price range over a given time period. - %K = [(Current Close - Lowest Low) / (Highest High - Lowest Low)] * 100 8. **momentum_stoch_signal (Stochastic Oscillator Signal)** - **Calculation:** The signal line is typically a 3-day simple moving average of the Stochastic Oscillator (%K). - %D = 3-day SMA of %K 9. **momentum_wr (Williams %R)** - **Calculation:** Williams %R is similar to the Stochastic Oscillator but inverted. It measures overbought and oversold levels. - %R = [(Highest High - Close) / (Highest High - Lowest Low)] * -100 10. **momentum_ao (Awesome Oscillator)** - **Calculation:** AO is a 34-period simple moving average, subtracted from a 5-period simple moving average. These moving averages are based on the midpoint of the bars (not the closing prices). - AO = SMA(Midpoint, 5 periods) - SMA(Midpoint, 34 periods) - Where Midpoint = (High + Low) / 2 11. **momentum_roc (Rate of Change)** - **Calculation:** The ROC measures the percentage change between the current price and the price a certain number of periods ago. - ROC = [(Current Close - Close N periods ago) / Close N periods ago] * 100 12. **momentum_ppo (Percentage Price Oscillator)** - **Calculation:** The PPO calculates the percentage difference between two exponential moving averages (EMAs), typically the 26-period EMA and the 12-period EMA. - PPO = [(12-period EMA - 26-period EMA) / 26-period EMA] * 100 13. **momentum_ppo_signal (Percentage Price Oscillator Signal Line)** - **Calculation:** The PPO signal line is usually a 9-period EMA of the PPO itself. It is used to generate trading signals. - PPO Signal = 9-period EMA of PPO 14. **momentum_ppo_hist (Percentage Price Oscillator Histogram)** - **Calculation:** The PPO histogram represents the difference between the PPO and its signal line. It's used to identify bullish or bearish momentum. - PPO Histogram = PPO - PPO Signal 15. **momentum_pvo (Percentage Volume Oscillator)** - **Calculation:** Similar to the PPO but for volume. The PVO measures the difference between two volume EMAs as a percentage of the longer EMA, typically the 26-period EMA and the 12-period EMA. - PVO = [(12-period Volume EMA - 26-period Volume EMA) / 26-period Volume EMA] * 100 16. **momentum_pvo_signal (Percentage Volume Oscillator Signal Line)** - **Calculation:** The PVO signal line is a 9-period EMA of the PVO, used to generate trading signals based on volume. - PVO Signal = 9-period EMA of PVO 17. **momentum_pvo_hist (Percentage Volume Oscillator Histogram)** - **Calculation:** The PVO histogram is the difference between the PVO and its signal line, indicating changes in volume momentum. - PVO Histogram = PVO - PVO Signal 18. **momentum_kama (Kaufman's Adaptive Moving Average)** - **Calculation:** KAMA adjusts its sensitivity based on market volatility. It starts with an Efficiency Ratio (ER) and then applies smoothing constants to an EMA based on the ER, to calculate the moving average. - ER = Absolute value of [(Current Close - Close N periods ago) / Sum of N period Absolute Price Changes] - KAMA = Previous KAMA + SC * (Current Price - Previous KAMA) - Where SC (Smoothing Constant) is calculated based on the ER and specified fast/slow EMA constants. """ # To Implement!! """ ### Volatility Indicators: #### Bollinger Bands Indicators: 1. **volatility_bbm (Bollinger Bands Middle Band)** - **Calculation:** The middle band is typically a 20-period simple moving average (SMA) of the closing prices. - BBM = 20-period SMA of Close 2. **volatility_bbh (Bollinger Bands Upper Band)** - **Calculation:** The upper band is calculated by adding (a specified number of standard deviations, usually 2) to the middle band (SMA). - BBH = BBM + (2 * 20-period Standard Deviation of Close) 3. **volatility_bbl (Bollinger Bands Lower Band)** - **Calculation:** The lower band is calculated by subtracting (a specified number of standard deviations, usually 2) from the middle band (SMA). - BBL = BBM - (2 * 20-period Standard Deviation of Close) 4. **volatility_bbw (Bollinger Bands Width)** - **Calculation:** The bandwidth quantifies the width of the Bollinger Bands. It is calculated by subtracting the lower band from the upper band, and often expressed as a percentage of the middle band. - BBW = (BBH - BBL) / BBM 5. **volatility_bbp (Bollinger Bands Percentage)** - **Calculation:** BBP measures where the last price is relative to the bands. It is calculated by taking the difference between the close and the lower band and dividing by the difference between the upper and lower bands. - BBP = (Close - BBL) / (BBH - BBL) 6. **volatility_bbhi (Bollinger Bands High Indicator)** - **Calculation:** BBHI is a binary indicator that shows if the closing price is above the upper Bollinger Band. - BBHI = 1 if Close > BBH else 0 7. **volatility_bbli (Bollinger Bands Low Indicator)** - **Calculation:** BBLI is a binary indicator that shows if the closing price is below the lower Bollinger Band. - BBLI = 1 if Close < BBL else 0 #### Keltner Channel-Related Indicators: 8. **volatility_kcc (Keltner Channel Middle Line)** - **Calculation:** The middle line of Keltner Channel is a 20-period Exponential Moving Average (EMA) of the closing prices. - KCC = 20-period EMA of Close 9. **volatility_kch (Keltner Channel Upper Line)** - **Calculation:** The upper line is determined by adding the value of the Average True Range (ATR) of the past 10 periods, multiplied by a factor (commonly 2), to the middle line. - KCH = KCC + (2 * 10-period ATR) 10. **volatility_kcl (Keltner Channel Lower Line)** - **Calculation:** The lower line is calculated by subtracting the value of the 10-period ATR, multiplied by a factor (commonly 2), from the middle line. - KCL = KCC - (2 * 10-period ATR) 11. **volatility_kcw (Keltner Channel Width)** - **Calculation:** The width of the Keltner Channel, calculated as the difference between the upper and lower bands, often expressed as a percentage of the middle line. - KCW = (KCH - KCL) / KCC 12. **volatility_kcp (Keltner Channel Percentage)** - **Calculation:** Measures the closing price's position within the Keltner Channel, expressed as a percentage. - KCP = (Close - KCL) / (KCH - KCL) 13. **volatility_kchi (Keltner Channel High Indicator)** - **Calculation:** A binary indicator that signals if the close is above the upper Keltner Channel. - KCHI = 1 if Close > KCH else 0 14. **volatility_kcli (Keltner Channel Low Indicator)** - **Calculation:** A binary indicator that signals if the close is below the lower Keltner Channel. - KCLI = 1 if Close < KCL else 0 #### Donchian Channel-Related Indicators: 15. **volatility_dcl (Donchian Channel Lower)** - **Calculation:** The lowest low of the past N periods. - DCL = Lowest Low over last N periods 16. **volatility_dch (Donchian Channel High)** - **Calculation:** The highest high of the past N periods. - DCH = Highest High over last N periods 17. **volatility_dcm (Donchian Channel Middle)** - **Calculation:** The average of the Donchian Channel High and Low. - DCM = (DCH + DCL) / 2 18. **volatility_dcw (Donchian Channel Width)** - **Calculation:** The difference between the upper and lower Donchian Channel lines. - DCW = DCH - DCL 19. **volatility_dcp (Donchian Channel Percentage)** - **Calculation:** Measures where the current closing price is within the Donchian Channel, as a percentage. - DCP = (Close - DCL) / (DCH - DCL) #### Other Volatility Indicators: 20. **volatility_atr (Average True Range)** - **Calculation:** ATR measures market volatility by decomposing the entire range of an asset for the period. It takes the maximum of the following three values: current high minus current low, absolute value of current high minus previous close, and absolute value of current low minus previous close. The ATR is typically a moving average of these true ranges. - ATR = Moving average (typically 14-period) of the True Ranges 21. **volatility_ui (Ulcer Index)** - **Calculation:** The Ulcer Index measures downside risk over a given period. It is calculated by squaring the percentage drawdowns (from the highest point) and then computing the square root of the average of these squares over the period. - UI = sqrt(Sum of squared percentage drawdowns / N) Exploring the calculation details for trend indicators using OHLC (Open, High, Low, Close) data provides insights into market direction and momentum. Here’s how each listed trend indicator is typically calculated: ### Trend Indicators: 1. **trend_macd (Moving Average Convergence Divergence)** - **Calculation:** MACD is calculated by subtracting the 26-period Exponential Moving Average (EMA) from the 12-period EMA. - MACD = 12-period EMA - 26-period EMA 2. **trend_macd_signal** - **Calculation:** The MACD Signal line is a 9-period EMA of the MACD line itself, serving as a trigger for buy and sell signals. - MACD Signal = 9-period EMA of MACD 3. **trend_macd_diff (MACD Histogram)** - **Calculation:** The MACD Histogram represents the difference between the MACD and its signal line. It's used to anticipate MACD crossovers. - MACD Histogram = MACD - MACD Signal 4. **trend_sma_fast (Fast Simple Moving Average)** - **Calculation:** A simple moving average (SMA) calculated over a shorter period, often used to identify quick, recent trends. - Fast SMA = Sum of Close / N (where N is the period, e.g., 10 days) 5. **trend_sma_slow (Slow Simple Moving Average)** - **Calculation:** A simple moving average (SMA) calculated over a longer period than the Fast SMA, often used to identify longer-term market trends. - Slow SMA = Sum of Close / N (where N is the period, e.g., 50 days) 6. **trend_ema_fast (Fast Exponential Moving Average)** - **Calculation:** Similar to the Fast SMA but gives more weight to recent prices, making it more responsive to new information. - Fast EMA = (Close - Previous EMA) * (2 / (N + 1)) + Previous EMA 7. **trend_ema_slow (Slow Exponential Moving Average)** - **Calculation:** Similar to the Slow SMA but gives more weight to recent prices, suitable for identifying long-term trends with a greater reaction to recent price changes. - Slow EMA = (Close - Previous EMA) * (2 / (N + 1)) + Previous EMA 8. **trend_vortex_ind_pos (Positive Vortex Indicator)** - **Calculation:** Measures upward trend movement by comparing the current high to the previous low, often smoothed over a period. - VI+ = (Sum of positive VMIs over N periods / Sum of TRs over N periods) 9. **trend_vortex_ind_neg (Negative Vortex Indicator)** - **Calculation:** Measures downward trend movement by comparing the current low to the previous high, often smoothed over a period. - VI- = (Sum of negative VMIs over N periods / Sum of TRs over N periods) 10. **trend_vortex_ind_diff** - **Calculation:** The difference between the Positive and Negative Vortex Indicators, indicating the dominance of a trend direction. - Vortex Indicator Difference = VI+ - VI- 11. **trend_trix (Triple Exponential Average)** - **Calculation:** TRIX smooths the minor fluctuations in the market and highlights the underlying trend. It's the rate of change of a triple exponentially smoothed moving average. - TRIX = 1-period percent change of a 15-period Triple EMA of Close 12. **trend_mass_index** - **Calculation:** The Mass Index detects trend reversals by measuring the narrowing and widening between the high and low prices. It involves a 9-period EMA of the high-low range divided by a 9-period EMA of the 9-period EMA of the high-low range. - MI = Sum of 9-period EMA of (High - Low) / 9-period EMA of the EMA over 25 periods 13. **trend_dpo (Detrended Price Oscillator)** - **Calculation:** DPO removes long-term trends from price data, allowing a focus on short-term patterns and cycles by comparing past prices to a shifted moving average. - DPO = Price N/2 + 1 periods ago - N-period SMA of Price 14. **trend_kst (Know Sure Thing)** - **Calculation:** KST is a momentum oscillator that combines multiple smoothed rates of change of the closing price. It sums four different time frames of the ROC, each weighted. - KST = ROC1 * 1 + ROC2 * 2 + ROC3 * 3 + ROC4 * 4 15. **trend_kst_sig (KST Signal Line)** - **Calculation:** The KST signal line is typically a 9-period SMA of the KST indicator, used to generate buy and sell signals. - KST Signal = 9-period SMA of KST 16. **trend_kst_diff** - **Calculation:** The difference between the KST and its signal line. This can indicate momentum shifts. - KST Difference = KST - KST Signal 17. **trend_ichimoku_conv (Ichimoku Conversion Line)** - **Calculation:** The conversion line is calculated as the midpoint between the 9-period high and the 9-period low. - Ichimoku Conversion Line = (9-period High + 9-period Low) / 2 18. **trend_ichimoku_base (Ichimoku Base Line)** - **Calculation:** The base line is the midpoint between the 26-period high and the 26-period low. - Ichimoku Base Line = (26-period High + 26-period Low) / 2 19. **trend_ichimoku_a (Ichimoku Leading Span A)** - **Calculation:** Leading Span A is the average of the conversion line and the base line. This line is plotted 26 periods into the future. - Ichimoku A = (Conversion Line + Base Line) / 2 20. **trend_ichimoku_b (Ichimoku Leading Span B)** - **Calculation:** Leading Span B is calculated as the midpoint between the 52-period high and the 52-period low, plotted 26 periods into the future. - Ichimoku B = (52-period High + 52-period Low) / 2 31. **trend_stc (Schaff Trend Cycle)** - **Calculation:** The STC is a combination of the MACD and stochastic oscillators, designed to improve accuracy in identifying trend changes. It involves calculating the MACD for price, then applying a stochastic oscillator formula to the MACD. - First, calculate the MACD line as you normally would. - Next, apply the Stochastic formula to the MACD values: STC = %K stochastic of MACD. 32. **trend_adx (Average Directional Index)** - **Calculation:** The ADX quantifies trend strength regardless of direction. It is derived from the directional movement indicators (DMI) (+DI and -DI) and smoothed by the average true range. - ADX = 14-period exponential moving average of the absolute value of (+DI - -DI) / (+DI + -DI). 33. **trend_adx_pos (+DI, Positive Directional Indicator)** - **Calculation:** +DI measures the upward trend strength. It's calculated as the 14-period exponential moving average of +DM (positive directional movement) divided by the average true range. - +DI = 14-period EMA of +DM / ATR. 34. **trend_adx_neg (-DI, Negative Directional Indicator)** - **Calculation:** -DI measures the downward trend strength. It's similar to +DI but uses -DM (negative directional movement). - -DI = 14-period EMA of -DM / ATR. 35. **trend_cci (Commodity Channel Index)** - **Calculation:** The CCI compares the current price to the average price over a specific time period. It's designed to identify cyclical trends. - CCI = (Typical Price - 20-period SMA of TP) / (0.015 * Mean Deviation), - where TP (Typical Price) = (High + Low + Close) / 3. 36. **trend_visual_ichimoku_a** - **Explanation:** This typically refers to a visualization aspect of the Ichimoku Cloud (Ichimoku Kinko Hyo), representing the Leading Span A (Senkou Span A), which is the midpoint of the Conversion Line and the Base Line plotted 26 periods ahead. 37. **trend_visual_ichimoku_b** - **Explanation:** Similar to `trend_visual_ichimoku_a`, this refers to the visualization of the Leading Span B (Senkou Span B) of the Ichimoku Cloud, plotted 26 periods into the future. It's the midpoint of the 52-period high and low. 38. **trend_aroon_up** - **Calculation:** The Aroon Up indicator measures the time since the last 25-period high, expressed as a percentage of the total period. - Aroon Up = [(25 - Periods Since 25-period High) / 25] * 100 39. **trend_aroon_down** - **Calculation:** The Aroon Down indicator measures the time since the last 25-period low, expressed as a percentage. - Aroon Down = [(25 - Periods Since 25-period Low) / 25] * 100 40. **trend_aroon_ind (Aroon Indicator)** - **Calculation:** The Aroon Indicator is often represented by the Aroon Up and Aroon Down lines. However, some calculations might represent it as the difference between Aroon Up and Aroon Down to provide a consolidated view of the trend. - Aroon Indicator = Aroon Up - Aroon Down #### Parabolic SAR Components: 41. **trend_psar_up** - **Calculation:** This value is calculated during a downtrend when the trend reverses to uptrend. The Parabolic SAR for the next period is calculated using the previous period's SAR, the extreme point (EP, which is the highest high during the current uptrend), and the acceleration factor (AF). For an uptrend, the SAR is calculated as: - `PSAR = Previous PSAR + AF * (EP - Previous PSAR)` - The initial PSAR when a trend turns up is the lowest low of the previous downtrend. 42. **trend_psar_down** - **Calculation:** Similar to `trend_psar_up`, but for when the trend is downward. The calculation involves the previous period's SAR, the lowest low (EP) during the current downtrend, and the acceleration factor (AF). The formula for a downtrend is: - `PSAR = Previous PSAR - AF * (Previous PSAR - EP)` - The initial PSAR when a trend turns down is the highest high of the previous uptrend. 43. **trend_psar_up_indicator** - **Calculation:** This is a binary indicator that signals when the Parabolic SAR switches to below the price, indicating a potential uptrend. If the current PSAR value is below the current price, it signals an uptrend. - `PSAR Up Indicator = 1 if Current PSAR < Current Price else 0` 44. **trend_psar_down_indicator** - **Calculation:** This is a binary indicator that signals when the Parabolic SAR switches to above the price, indicating a potential downtrend. If the current PSAR value is above the current price, it signals a downtrend. - `PSAR Down Indicator = 1 if Current PSAR > Current Price else 0` ### 1. others_dr (Daily Return) - **Definition:** Daily Return measures the percentage change in the price of a financial instrument from one day to the next. It is a simple way to gauge the day-to-day fluctuation in the price. - **Calculation:** The formula for calculating the Daily Return (`others_dr`) is: - `Daily Return = [(Current Day's Close - Previous Day's Close) / Previous Day's Close] * 100` - This calculation provides the return for a specific day as a percentage change from the previous day's closing price. ### 2. others_dlr (Daily Log Return) - **Definition:** Daily Log Return is another way to measure the price change of a financial instrument, using the natural logarithm. Log returns are useful for mathematical analysis, particularly because they are time additive. - **Calculation:** The formula for calculating the Daily Log Return (`others_dlr`) is: - `Daily Log Return = ln(Current Day's Close / Previous Day's Close) * 100` - Where `ln` denotes the natural logarithm. Log returns are especially handy in portfolio analysis and are time additive, which means you can sum log returns over time to get a cumulative return. ### 3. others_cr (Cumulative Return) - **Definition:** Cumulative Return measures the total change in the price of a financial instrument over a specified period. It represents the aggregate effect of price movements on the initial investment over time. - **Calculation:** The formula for calculating the Cumulative Return (`others_cr`) when starting from 0 and expressed as a percentage might look like this: - `Cumulative Return = [(Current Price / Initial Price) - 1] * 100` - This calculation gives the total percentage return on the investment from the beginning of the period to the current date. """ class TechnicalIndicators: @staticmethod def assert_timeseries(df: pd.DataFrame, add_col: list = []): """ Assert the pandas DataFrame input structure Parameters: - df (pd.DataFrame): DataFrame with a datetime index and columns ['Open', 'High', 'Low', 'Close', 'Volume']. """ required_columns = ['Open', 'High', 'Low', 'Close', 'Volume'] + add_col if not all(column in df.columns for column in required_columns): raise ValueError(f"DataFrame must contain columns: {required_columns}") if not isinstance(df.index, pd.DatetimeIndex): raise ValueError("DataFrame index must be a DatetimeIndex.") @staticmethod def assert_price(price: Union[float, int]): if not ((isinstance(price, (int, float)) and price > 0) or (price is None)): raise ValueError("price must be strictly positive float or int, or it should be None") @staticmethod def assert_span(span: Union[float, int, list, np.ndarray]) -> Iterable: """ Assert the span which has to be an Iterable composed of float or int, or it should be a float or int Parameters: - span (float, int, List[float,int], numpy.ndarray): window size for moving averages (each span >= 1) Returns: - Itearable[float,int >= 1]: span """ # Check if span is already an iterable (but not a string, as strings are also iterable) if isinstance(span, Iterable) and not isinstance(span, str): # Convert numpy arrays to lists for consistent handling if isinstance(span, np.ndarray): span = span.tolist() # Check all elements are int or float and greater than 1 if not all(isinstance(item, (int, float)) and item >= 1 for item in span): raise ValueError("All elements in span must be int or float and greater than 1") # If span is a single int or float, check it's greater than 1 and make it a list elif isinstance(span, (int, float)): if span <= 1: raise ValueError("span must be greater than 1") span = [span] # Convert to list for consistency else: raise ValueError("span must be an int, float, or an iterable of int/float") return span @staticmethod def assert_float(para: float, para_name: str): if not isinstance(para, float): raise ValueError(f"{para_name} must be float") @staticmethod def append_from_parallelize(df: pd.DataFrame, processes: list, n_process: int = 5): with ProcessPoolExecutor(max_workers=np.minimum(n_process, len(processes))) as executor: futures = [executor.submit(p, df) for p in processes] results = [f.result() for f in futures] # Append results to df for res in results: df.loc[res.index, res.columns] = res return df @staticmethod def get_sub_series(x: pd.Series, q1: Union[float, int], q2: Union[float, int]): return x[(x > q1) & (x < q2)] def get_sub_series_up(self, x: pd.Series, q1: Union[float, int], q2: Union[float, int]): x_ = self.get_sub_series(x, q1, q2) return x_[x_ > 0] def get_sub_series_low(self, x: pd.Series, q1: Union[float, int], q2: Union[float, int]): x_ = self.get_sub_series(x, q1, q2) return x_[x_ < 0] def get_slope_up(self, x: pd.Series, q1: Union[float, int], q2: Union[float, int]): x_ = self.get_sub_series(x, q1, q2) mean = x_.mean() std = x_.std() x_ = np.sort(x_) - mean ccdf = (np.cumsum(np.ones(len(x_))).astype(float)/len(x_))[::-1] mask = np.where(x_ > 3*std)[0] slope_pos = 0. if len(mask) > 2: slope_pos, _, _, _, _ = linregress(np.log(x_[mask]), np.log(ccdf[mask])) return slope_pos def get_slope_low(self, x: pd.Series, q1: Union[float, int], q2: Union[float, int]): x_ = self.get_sub_series(x, q1, q2) mean = x_.mean() std = x_.std() x_ = np.sort(x_) - mean ccdf = (np.cumsum(np.ones(len(x_))).astype(float)/len(x_))[::-1] mask = np.where(x_ < -3*std)[0] slope_neg = 0. if len(mask) > 2: slope_neg, _, _, _, _ = linregress(np.log(-1.*x_[mask]), np.log(ccdf[mask])) return slope_neg def get_previous_data(self, df: pd.DataFrame, df_last: Optional[pd.DataFrame], cols: list): # If we have previous data, append them if not df_last is None: self.assert_timeseries(df_last, cols) df = pd.concat([df_last.iloc[-1:][cols], df[cols]]) return df def get_prices(self, df: pd.DataFrame, last_price: Optional[Union[float, int]]) -> pd.DataFrame: """ Calculate Price ... Parameters: - df (pd.DataFrame): DataFrame with a datetime index and columns ['Open', 'High', 'Low', 'Close', 'Volume']. Returns: - pd.DataFrame: DataFrame indexed similarly to the input with columns for each technical indicator. Raises: - ValueError: If the input DataFrame does not meet the requirements. """ # Validate input DataFrame self.assert_timeseries(df) # Validate last_price self.assert_price(last_price) prices = pd.DataFrame(columns=["Typical", "Diff", "Midd", "Money", "PC"], index = df.index) prices["Typical"] = df[["Close", "High", "Low"]].sum(axis=1)/3. # Typical price = (Close + High + Low)/3 prices["Diff"] = df["High"] - df["Low"] # Max difference = High - Low prices["Midd"] = (df["High"] + df["Low"])/2. # Middle Price = (High + Low)/2 prices["Money"] = prices["Typical"]*df["Volume"] # Money Traded = Typical Price x Volume prices["PC"] = df["Close"].shift(1) # Previous Close Price # Append last price if any if not last_price is None: prices.loc[prices.index[0], "PC"] = last_price return prices def get_price_flow(self, df: pd.DataFrame) -> pd.DataFrame: """ Calculate Price Flow ... Parameters: - df (pd.DataFrame): DataFrame with a datetime index and columns ['Open', 'High', 'Low', 'Close', 'Volume']. Returns: - pd.DataFrame: DataFrame indexed similarly to the input with columns for each technical indicator. Raises: - ValueError: If the input DataFrame does not meet the requirements. """ # Validate input DataFrame self.assert_timeseries(df, add_col=["PC", "Money"]) evolves = pd.DataFrame(columns=["Evolve", "Return", "Positive Flow", "Negative Flow"], index = df.index) evolves["Evolve"] = df["Close"] - df["PC"] # Close Price Evolution t = Close_t - Close_{t-1} evolves["Return"] = df["Close"]/df["PC"] - 1. # Period return t = Close_t/Close_{t-1} - 1 evolves['Positive Flow'] = np.where(evolves["Return"] > 0, df['Money'], 0.) # Positive Money Flow t = Money Flow t where Close t > Close t-1 evolves['Negative Flow'] = np.where(evolves["Return"] < 0, df['Money'], 0.) # Negative Money Flow t = Money Flow t where Close t < Close t-1 evolves['Positive Evolve'] = np.where(evolves["Return"] > 0, evolves['Evolve'], 0.) # Positive Evolve Flow t = Money Flow t where Close t > Close t-1 evolves['Negative Evolve'] = np.where(evolves["Return"] < 0, -1*evolves['Evolve'], 0.) # Negative Evolve Flow t = Money Flow t where Close t < Close t-1 return evolves def get_price_pressure(self, df: pd.DataFrame) -> pd.DataFrame: """ Calculate Price Pressure ... Parameters: - df (pd.DataFrame): DataFrame with a datetime index and columns ['Open', 'High', 'Low', 'Close', 'Volume']. Returns: - pd.DataFrame: DataFrame indexed similarly to the input with columns for each technical indicator. Raises: - ValueError: If the input DataFrame does not meet the requirements. """ # Validate input DataFrame self.assert_timeseries(df, add_col=["PC"]) pressure = pd.DataFrame(columns=["minLPC", "maxHPC", "BP", "TR"], index = df.index) pressure["minLPC"] = df[["Low", "PC"]].min(axis=1) # Minimum between Previous Price and Current Low pressure["maxHPC"] = df[["High", "PC"]].min(axis=1) # Maximum between Previous Price and Current High pressure["BP"] = df["Close"] - pressure["minLPC"] # Buying Pressure pressure["TR"] = pressure["maxHPC"] - pressure["minLPC"] # True Range return pressure[["BP", "TR"]] def get_diffAdi(self, df: pd.DataFrame) -> pd.DataFrame: # Validate input DataFrame self.assert_timeseries(df, add_col=["Money", "Diff"]) # Difference of ADI = ((Close - Low) - (High - Close)) x Money / (High - Low) diff_adi = pd.DataFrame(columns=["DiffADI"], index = df.index) diff_adi["DiffADI"] = (2.*df["Close"] - df["High"] - df["Low"])*df["Money"]/df["Diff"] return diff_adi def get_force_index(self, df: pd.DataFrame) -> pd.DataFrame: # Validate input DataFrame self.assert_timeseries(df, add_col=["Money", "Return"]) # Regularized Force Index = Money x Period Return force_index = pd.DataFrame(columns=["FI"], index = df.index) force_index["FI"] = df["Money"]*df["Return"] return force_index def get_ease_of_movement(self, df: pd.DataFrame, df_last: Optional[pd.DataFrame]) -> pd.DataFrame: # Validate input DataFrame self.assert_timeseries(df, add_col=["Money", "Return"]) # Measure Previous Midd = (High + Low) / 2 midd_shift = df["Midd"].shift(1) # If we have previous data, append the last Midd point if not df_last is None: self.assert_timeseries(df_last) midd_shift.loc[midd_shift.index[0]] = (df_last["High"].iloc[-1] + df_last["Low"].iloc[-1])/2. # Ease of Movement t = ((High_t + Low_t) - (High_{t-1} + Low_{t-1})) / Money_t / (High_t - Low_t) / 2 ease_of_movement = pd.DataFrame(columns=["EOM"], index = df.index) ease_of_movement["EOM"] = (df["Midd"] - midd_shift)/df["Money"]/df["Diff"] return ease_of_movement def get_chaikin_money_flow(self, df: pd.DataFrame, df_last: Optional[pd.DataFrame], span: int = 10) -> pd.DataFrame: # Validate input DataFrame self.assert_timeseries(df, add_col=["DiffADI", "Money"]) # Initialize EWM df_ = self.get_previous_data(df[["DiffADI", "Money"]], df_last, cols = [f"DiffADI-{span}", f"Money-{span}"]) # Chaikin Money Flow = Average over Past Difference of ADI / Average over Past Volume in Money cmf = pd.DataFrame(columns=[f"{c}-{span}" for c in ["CMF", "DiffADI", "Money"]], index=df.index) cmf[[f"DiffADI-{span}", f"Money-{span}"]] = df_.ewm(span=span, axis=0).mean().iloc[1:] cmf[f"CMF-{span}"] = cmf[f"DiffADI-{span}"]/cmf[f"Money-{span}"] return cmf def get_ewm_ease_of_movement(self, df: pd.DataFrame, df_last: Optional[pd.DataFrame], span: int = 10) -> pd.DataFrame: # Validate input DataFrame self.assert_timeseries(df, add_col=["EOM"]) # Initialize EWM df_ = self.get_previous_data(df[["EOM"]], df_last, cols = [f"EOM-{span}"]) # EWM Average of Ease of Movement eom = pd.DataFrame(columns=[f"EOM-{span}"], index=df.index) eom[f"EOM-{span}"] = df_["EOM"].ewm(span=span).mean().iloc[1:] return eom def get_money_flow(self, df: pd.DataFrame, df_last: Optional[pd.DataFrame], span: int = 10) -> pd.DataFrame: # Validate input DataFrame self.assert_timeseries(df, add_col=['Positive Flow', 'Negative Flow']) # Initialize EWM df_ = self.get_previous_data(df[['Positive Flow', 'Negative Flow']], df_last, cols = [f'Positive Flow-{span}', f'Negative Flow-{span}']) money_flow = pd.DataFrame(columns=[f"MFI-{span}", f'Positive Flow-{span}', f'Negative Flow-{span}']) money_flow[[f'Positive Flow-{span}', f'Negative Flow-{span}']] = df_.ewm(span=span, axis=0).mean().iloc[1:] # Money Flow Ratio = Average Positive Money Flow / Average Negative Money Flow mfr = money_flow[f'Positive Flow-{span}']/money_flow[f'Negative Flow-{span}'] # Money Flow Index = 1 - 1/(1 + Money Flow Ratio) money_flow[f"MFI-{span}"] = 1. - 1./(1.+mfr) return money_flow def get_buying_pressure_strength(self, df: pd.DataFrame, df_last: Optional[pd.DataFrame], span: int = 10) -> pd.DataFrame: # Validate input DataFrame self.assert_timeseries(df, add_col=['BP', 'TR']) # Initialize EWM df_ = self.get_previous_data(df[['BP', 'TR']], df_last, cols = [f'BP-{span}', f'TR-{span}']) # Strength between Buying Pressure and True Range strength = pd.DataFrame(columns=[f"BP/TR-{span}", f'BP-{span}', f'TR-{span}']) strength[f"BP-{span}"] = df_["BP"].ewm(span=span).mean().iloc[1:] strength[f"TR-{span}"] = df_["TR"].ewm(span=span).mean().iloc[1:] strength[f"BP/TR-{span}"] = strength[f"BP-{span}"] / strength[f"TR-{span}"] return strength def get_ultimate_oscillator(self, df: pd.DataFrame, span: int = 10) -> pd.DataFrame: # Validate input DataFrame self.assert_timeseries(df, add_col=[f"BP/TR-{i*span}" for i in [1, 2, 4]]) # Ultimate Oscillator = Average over different time scale of Buying Pressure / True Range uo = pd.DataFrame(columns=[f"UO-{span}"]) uo[f"UO-{span}"] = (df[[f"BP/TR-{i*span}" for i in [1, 2, 4]]]*np.array([1, 2, 4])).sum(axis=1) / 7 return uo def get_stochastic_oscillator(self, df: pd.DataFrame, df_last: Optional[pd.DataFrame], span: int = 10) -> pd.DataFrame: # Validate input DataFrame self.assert_timeseries(df) # Initialize EWM df_ = self.get_previous_data(df[['High', 'Low']], df_last, cols = [f"maxHigh-{span}", f"minLow-{span}"]) # Stochastic Oscillator = (Close - Lowest Low) / (Highest High - Lowes Low) so = pd.DataFrame(columns=[f"SO-{span}", f"maxHigh-{span}", f"minLow-{span}"]) so[f"minLow-{span}"] = df_["Low"].rolling(window=span, min_periods=1).min().iloc[1:] # Lowest Low so[f"maxHigh-{span}"] = df["High"].rolling(window=span, min_periods=1).max().iloc[1:] # Highest High so[f"SO-{span}"] = (df["Close"] - so[f"minLow-{span}"])/(so[f"maxHigh-{span}"] - so[f"minLow-{span}"]) return so def get_relative_strength(self, df: pd.DataFrame, df_last: Optional[pd.DataFrame], span: int = 10) -> pd.DataFrame: # Validate input DataFrame self.assert_timeseries(df, add_col=['Positive Evolve', 'Negative Evolve']) # Initialize EWM df_ = self.get_previous_data(df[['Positive Evolve', 'Negative Evolve']], df_last, cols = [f"Positive Evolve-{span}", f"Negative Evolve-{span}"]) rsi = pd.DataFrame(columns=[f"RSI-{span}", f"Positive Evolve-{span}", f"Negative Evolve-{span}"]) rsi[[f"Positive Evolve-{span}", f"Negative Evolve-{span}"]] = df_[["Positive Evolve", "Negative Evolve"]].ewm(span=span).mean() rs = rsi[f"Positive Evolve-{span}"]/rsi[f"Negative Evolve-{span}"] # Relative Strenght = Average Positive Evolution / Average Negative Evolution rsi[f"RSI-{span}"] = 1. - 1./(1. + rs) # Relative Strength Index = 1 - 1/(1 + RS) return rsi def get_true_strength(self, df: pd.DataFrame, df_last: Optional[pd.DataFrame], span: int = 10) -> pd.DataFrame: # Validate input DataFrame self.assert_timeseries(df, add_col=['Evolve']) # Get min & max ts = df[["Evolve"]] ts["EvolveAbs"] = np.abs(ts["Evolve"]) if not df_last is None: self.assert_timeseries(df_last) ts = pd.concat([df_last.iloc[-1:][[f"Evolve-{span}", f"EvolveAbs-{span}"]], ts], axis=0) tsi = pd.DataFrame(columns=[f"TSI-{span}", f"Evolve-{span}", f"EvolveAbs-{span}"]) tsi[[f"Evolve-{span}", f"EvolveAbs-{span}"]] = ts[["Evolve", "EvolveAbs"]].ewm(span=span).mean().loc[df.index[0]:] tsi[f"TSI-{span}"] = tsi[f"Evolve-{span}"]/tsi[f"EvolveAbs-{span}"] return tsi def get_stochastic_index(self, df: pd.DataFrame, index: str, df_last: Optional[pd.DataFrame], span: int = 10) -> pd.DataFrame: # Validate input DataFrame self.assert_timeseries(df, add_col=[f"{index}-{span}"]) # Get min & max max_min = df[[f"{index}-{span}", f"{index}-{span}"]] max_min.columns = [f"max{index}-{span}", f"min{index}-{span}"] if not df_last is None: self.assert_timeseries(df_last) max_min = pd.concat([df_last.iloc[-1:][[f"max{index}-{span}", f"min{index}-{span}"]], max_min], axis=0) # Stochastic Measure of an Index si = pd.DataFrame(columns=[f"Stoch{index}-{span}", f"max{index}-{span}", f"min{index}-{span}"]) si[f"max{index}-{span}"] = max_min[f"max{index}-{span}"].rolling(window=span, min_periods=1).max().loc[df.index[0]:] si[f"min{index}-{span}"] = max_min[f"min{index}-{span}"].rolling(window=span, min_periods=1).min().loc[df.index[0]:] si[f"Stoch{index}-{span}"] = (df[f"{index}-{span}"] - si[f"min{index}-{span}"])/(si[f"max{index}-{span}"] - si[f"min{index}-{span}"]) return si def get_quantile(self, df: pd.Series, q: float, span: int = 10) -> pd.DataFrame: data = pd.DataFrame(columns=[f"{int(q*100)}%-Q-{span}"]) data[f"{int(q*100)}%-Q-{span}"] = df["Return"].rolling(window=span).quantile(q) return data def get_skweness(self, df: pd.Series, span: int = 10) -> pd.DataFrame: data = pd.DataFrame(columns=[f"skw-{span}"]) data[f"skw-{span}"] = df["Return"].rolling(window=span).skew() return data def get_kurtosis(self, df: pd.Series, span: int = 10) -> pd.DataFrame: data = pd.DataFrame(columns=[f"kts-{span}"]) data[f"kts-{span}"] = df["Return"].rolling(window=span).kurt() return data def get_mean(self, df: pd.Series, span: int = 10) -> pd.DataFrame: data = pd.DataFrame(columns=[f"mean-{span}"]) data[f"mean-{span}"] = df["Return"].rolling(window=span).apply(lambda x: self.get_sub_series(x, df[f"5%-Q-{span}"][x.index[-1]], df[f"95%-Q-{span}"][x.index[-1]]).mean()) return data def get_std(self, df: pd.Series, span: int = 10) -> pd.DataFrame: data = pd.DataFrame(columns=[f"std-{span}"]) data[f"std-{span}"] = df["Return"].rolling(window=span).apply(lambda x: self.get_sub_series(x, df[f"5%-Q-{span}"][x.index[-1]], df[f"95%-Q-{span}"][x.index[-1]]).std()) return data def get_std_up(self, df: pd.Series, span: int = 10) -> pd.DataFrame: data = pd.DataFrame(columns=[f"std(+)-{span}"]) data[f"std(+)-{span}"] = df["Return"].rolling(window=span).apply(lambda x: self.get_sub_series_up(x, df[f"5%-Q-{span}"][x.index[-1]], df[f"95%-Q-{span}"][x.index[-1]]).std()) return data def get_std_low(self, df: pd.Series, span: int = 10) -> pd.DataFrame: data = pd.DataFrame(columns=[f"std(-)-{span}"]) data[f"std(-)-{span}"] = df["Return"].rolling(window=span).apply(lambda x: self.get_sub_series_low(x, df[f"5%-Q-{span}"][x.index[-1]], df[f"95%-Q-{span}"][x.index[-1]]).std()) return data def get_all_slope_up(self, df: pd.Series, span: int = 10) -> pd.DataFrame: data = pd.DataFrame(columns=[f"slope(+)-{span}"]) data[f"slope(+)-{span}"] = df["Return"].rolling(window=span).apply(lambda x: self.get_slope_up(x, df[f"5%-Q-{span}"][x.index[-1]], df[f"95%-Q-{span}"][x.index[-1]])) return data def get_all_slope_low(self, df: pd.Series, span: int = 10) -> pd.DataFrame: data = pd.DataFrame(columns=[f"slope(-)-{span}"]) data[f"slope(-)-{span}"] = df["Return"].rolling(window=span).apply(lambda x: self.get_slope_low(x, df[f"5%-Q-{span}"][x.index[-1]], df[f"95%-Q-{span}"][x.index[-1]])) return data def measure_draw(self, price: pd.Series) -> pd.DataFrame: if price.iloc[0] > price.iloc[1]: i = price[price > price.iloc[0]] if len(i) >0: i = i.index[0] else: i = -1 i = price[:i].argmin() elif price.iloc[0] < price.iloc[1]: i = price[price < price.iloc[0]] if len(i) >0: i = i.index[0] else: i = -1 i = price[:i].argmax() else: i = price.index[0] return pd.DataFrame({"cum log": [price[i]/price.iloc[0] - 1.], "time start": [price.index[0]], "time end": [i]}) def get_draw(self, price: pd.Series) -> pd.DataFrame: price_last = price.shift(1) price_next = price.shift(-1) I = price.index[(((price > price_last) & (price < price_next)) | ((price < price_last) & (price > price_next)))] bg_wl = [self.measure_draw(price[i:]) for i in I] if len(bg_wl) > 0: bg_wl = pd.concat(bg_wl, axis=0, ignore_index=True) else: bg_wl = pd.DataFrame({"cum log": [0], "time start": [np.nan], "time end": [np.nan]}) return bg_wl def get( self, df: pd.DataFrame, df_last: Optional[pd.DataFrame] = None, span: Union[float, int, list, np.ndarray] = 10, stat_span: Union[float, int, list, np.ndarray] = 20, n_processes: int = 5, ) -> pd.DataFrame: """ Calculate various technical indicators on a pandas DataFrame containing OHLCV data. Parameters: - df (pd.DataFrame): DataFrame with a datetime index and columns ['Open', 'High', 'Low', 'Close', 'Volume']. Returns: - pd.DataFrame: DataFrame indexed similarly to the input with columns for each technical indicator. Raises: - ValueError: If the input DataFrame does not meet the requirements. """ self.assert_timeseries(df) if not df_last is None: self.assert_timeseries(df_last) span = self.assert_span(span) stat_span = self.assert_span(stat_span) # Initialize # Get: Typical price = (Close + High + Low)/3 # Max difference = High - Low, Middle Price = (High + Low)/2 # Middle Price = (High + Low)/2 # Money Traded = Typical Price x Volume # Previous Close Price df = pd.concat([df, self.get_prices(df, last_price= None if df_last is None else df_last["Close"].iloc[-1])], axis = 1) # With get_price_flow, Get: # Close Price Evolution t = Close_t - Close_{t-1} # Period return t = Close_t/Close_{t-1} - 1 # Positive Money Flow t = Money Flow t where Close t > Close t-1 # Negative Money Flow t = Money Flow t where Close t < Close t-1 # With get_price_pressure, Get: # Buying Pressure = Close_t - min(Close_{t-1}, Low_t) # True Range = max(Close_{t-1}, High_t) - Close_t df = self.append_from_parallelize(df, processes=[self.get_price_flow, self.get_price_pressure], n_process = np.minimum(n_processes, 2)) # Money Based Point Indicators df = self.append_from_parallelize(df, processes=[self.get_diffAdi, self.get_force_index, partial(self.get_ease_of_movement, df_last=df_last)], n_process=np.minimum(n_processes, 3)) df = self.append_from_parallelize(df, processes=[self.get_diffAdi, self.get_force_index, partial(self.get_ease_of_movement, df_last=df_last)], n_process=np.minimum(n_processes, 3)) # Money Based Average Indicators money_based_processes = [partial(self.get_chaikin_money_flow, df_last=df_last, span=s) for s in span] money_based_processes += [partial(self.get_ewm_ease_of_movement, df_last=df_last, span=s) for s in span] money_based_processes += [partial(self.get_money_flow, df_last=df_last, span=s) for s in span] df = self.append_from_parallelize(df, processes=money_based_processes, n_process=n_processes) # Money Based Indicators (3 + 3*len(span)) money_cols = ["DiffADI", "FI", "EOM"] + [f"{e}-{s}"for e in ["CMF", "EOM", "MFI"] for s in span] # Momentum Based Average Indicators strength_processes = [partial(self.get_buying_pressure_strength, df_last=df_last, span=s) for s in list(set([i*s for i in [1, 2, 4] for s in span]))] df = self.append_from_parallelize(df, processes=strength_processes, n_process=n_processes) momentum_based_processes = [partial(self.get_ultimate_oscillator, span=s) for s in span] momentum_based_processes += [partial(self.get_stochastic_oscillator, df_last=df_last, span=s) for s in span] momentum_based_processes += [partial(self.get_relative_strength, df_last=df_last, span=s) for s in span] momentum_based_processes += [partial(self.get_true_strength, df_last=df_last, span=s) for s in span] df = self.append_from_parallelize(df, processes=momentum_based_processes, n_process=n_processes) stochastic_processes = [partial(self.get_stochastic_index, index="RSI", df_last=df_last, span=s) for s in span] stochastic_processes += [partial(self.get_stochastic_index, index="TSI", df_last=df_last, span=s) for s in span] df = self.append_from_parallelize(df, processes=stochastic_processes, n_process=n_processes) # Momentum Based Indicators () momentum_cols = [f"{e}-{s}"for e in ["UO", "SO", "RSI", "StochRSI", "TSI", "StochTSI"] for s in span] # Statistics ret, t0 = df[["Return"]], df.index[0] if not df_last is None: self.assert_timeseries(df_last, add_col=["Return"]) ret = pd.concat([df_last[["Return"]].iloc[-np.max(stat_span)], ret], axis=0) stat_process = [partial(self.get_quantile, q=q, span=s) for q in [0.05, 0.25, 0.5, 0.75, 0.95] for s in stat_span] stat_process += [partial(self.get_skweness, span=s) for s in stat_span] stat_process += [partial(self.get_kurtosis, span=s) for s in stat_span] ret = self.append_from_parallelize(ret, processes=stat_process, n_process=n_processes) stat_process = [partial(self.get_mean, span=s) for s in stat_span] stat_process += [partial(self.get_std, span=s) for s in stat_span] stat_process += [partial(self.get_std_up, span=s) for s in stat_span] stat_process += [partial(self.get_std_low, span=s) for s in stat_span] stat_process += [partial(self.get_all_slope_up, span=s) for s in stat_span] stat_process += [partial(self.get_all_slope_low, span=s) for s in stat_span] ret = self.append_from_parallelize(ret, processes=stat_process, n_process=n_processes) statistics_cols = [f"{e}-{s}"for e in ["mean", "std", "std(+)", "std(-)", "slope(+)", "slope(-)", "skw", "kts"] + [f"{i}%-Q" for i in [5, 25, 50, 75, 95]] for s in stat_span] df[statistics_cols] = ret[statistics_cols].loc[t0:] return df[money_cols + momentum_cols + statistics_cols], df.iloc[-np.max(stat_span):]
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> * {margin: 0px; padding: 0;} li {list-style-type: none;} .container { width: 100%; min-width: 480px; margin: 20px 0 0 50px; } h1 { margin: 20px; } div { float: left;} .clear {clear: both;} #lightbox { width: 300px; height: 300px; } #lightbox img { width: 19em; } .pic { width: 70px; height: 70px; } .row li{ display: inline-block; margin: 1em; } button { width: 300px; height: 40px; margin-top: 20px; margin-bottom: 10px; } h4{ color: blue; margin: 20px; } span { display: inline-block; margin-top: 100px; margin-left: 30px ; } span ul { margin-top: 30px;} span li { padding: 5px; } </style> </head> <body> <div class ="container"> <div> <h1> 에디오피아 게뎁 </h1> <div id = "lightbox"> <img src="img/coffee-pink.jpg" alt="" id = "lightboxImage"> </div> <div class="clear"></div> <div class="row"> <ul> <li><img src="img/coffee-pink.jpg" data-src="img/coffee-pink.jpg" class="pic" ></li> <li><img src="img/coffee-blue.jpg" data-src="img/coffee-blue.jpg" class="pic" ></li> <li><img src="img/coffee-gray.jpg" data-src="img/coffee-gray.jpg" class="pic"></li> </ul> </div> </div> <span> <ul> <li> 상품명 : 에티오피아 게뎁</li> <li style="color: blue;"> 판매가 : 9,000원 </li> <li> 배송비 : 3,000원 </li> <li> (50,000원 이상 구매시 무료) </li> <li> 적립금 : 180원(2%)</li> <li> 로스팅 : 2019.06.17</li> </ul> <button type="button">장바구니 담기</button> <h4>상세 설명 보기</h4> </span> </div> <!-- 자바스크립트 --> <script> // class, id 속성을 가져와서 변수에 할당. var pics = document.getElementsByClassName("pic"); var lightbox = document.getElementById("lightbox"); var lightboxImage = document.getElementById("lightboxImage"); //for 루프를 돌리면서 썸네일을 클릭시 showLightbox() 함수를 호출 for ( var i = 0 ; i < pics.length; i++) { pics[i].addEventListener("click", showLightbox); //pics 배열의 i 번째 요소를 클릭시 showLightbox() 함수를 호출 } //썸네일을 클릭시 img 태그의 원본 이미지를 적용하는 함수 , 화면에 출력 하는 함수 function showLightbox() { var bigLocation = this.getAttribute("data-src"); //data-src 의 값을 가져와서 bicLocation 변수에 할당 lightboxImage.setAttribute("src" , bigLocation); lightbox.style.display = "block"; /* 화면에 출력되도록 설정 : none => block */ } </script> </body> </html>
#include <avr/EEPROM.h> #include <phys253.h> #include <avr/interrupt.h> #include <LiquidCrystal.h> //To determine where on course the robot is volatile unsigned int NUM = 0; /* == CLASSES == */ class MenuItem { public: String Name; uint16_t Value; uint16_t* EEPROMAddress; static uint16_t MenuItemCount; MenuItem(String name) { MenuItemCount++; EEPROMAddress = (uint16_t*)(2 * MenuItemCount); Name = name; Value = eeprom_read_word(EEPROMAddress); } void Save() { eeprom_write_word(EEPROMAddress, Value); } }; // Initializing the menu uint16_t MenuItem::MenuItemCount = 0; /* Add the menu items here */ MenuItem Speed = MenuItem("Speed"); MenuItem ProportionalGainTape = MenuItem("P-gain Tape"); MenuItem DerivativeGain = MenuItem("D-gain Tape"); MenuItem IntegralGain = MenuItem("I-gain Tape"); MenuItem ThresholdTape = MenuItem("Thresh Tape"); MenuItem menuItems[] = {Speed, ProportionalGainTape, DerivativeGain, IntegralGain, ThresholdTape}; /* == SETUP == */ void setup() { #include <phys253setup.txt> LCD.clear(); LCD.home(); } /* == TINAH INPUTS == */ //Motor int MOTOR_LEFT = 3; //PWM output for left motor int MOTOR_RIGHT = 2; //PWM output for right motor int MOTOR_CRANE_HEIGHT = 1; //Motor for arm height int MOTOR_CRANE_ANGLE = 0; //Motor for arm angle //Analog int QRD_LEFT = 1; //Left QRD for tape following int QRD_RIGHT = 0; //Right QRD for tape following int QRD_PET_BACK = 2; //QRD for locating pets back int QRD_PET_FRONT = 3; //QRD for locating pets front int POTENTIOMETER_CRANE_HEIGHT = 5; //Rotary potentiometer for crane arm int POTENTIOMETER_CRANE_ANGLE = 4; //Rotary potentiometer for crane arm //Servo int SERVO_PLATE = 0; //Servo to drop pet //Digital int SWITCH_PLATE = 3; //Switch to see if pet is on plate int ROT_LEFT = 0; //Rotary encoder for left wheel int ROT_RIGHT = 1; //Rotary encoder for right wheel /* == CONSTANTS == */ //For Arm PID int MAX_ANALOG = 1023; int SPEED_HEIGHT = 120; int SPEED_ANGLE = 65; int P_HEIGHT = 20; int P_ANGLE = 1; int I_HEIGHT = 24; int I_ANGLE = 1; int I_MAX_HEIGHT = 150; int I_MAX_ANGLE = 150; int D_HEIGHT = 0; int D_ANGLE = 4; int ARM_UP = 950; int ARM_HOR = 830; int ARM_DOWN = 700; int ARM_PICKUP = 600; int ARM_LEFT = 250; int ARM_CENTRE = 500; int ARM_RIGHT = 700; int DEADBAND = 15; int PET_QRD_THRESHOLD = 400; //For reference int HEIGHT = 1; int ANGLE = 2; //For rot encoder float DIST_PER_TAPE = PI; //Distance wheel moves per tape hit (cm) float LENGTH_OF_AXLE = 24.2; //Length of axle (cm) int TURNS_LEFT = 0; int TURNS_RIGHT = 0; int prev_enc_left = 0; int prev_enc_right = 0; int cur_enc_left = 0; int cur_enc_right = 0; /* == HOME SCREEN == */ void loop() { stopDrive(); setServo(SERVO_PLATE, 0); LCD.clear(); LCD.home(); LCD.print("Start: Menu"); LCD.setCursor(0, 1); LCD.print("Stop: PID"); delay(100); // opens the menu if (startbutton()) { delay(100); if (startbutton()) { Menu(); } } // runs the control loop if (stopbutton()) { delay(100); if (stopbutton()) { mainStart(); } } } /* == CONTROL LOOP == */ /* Main loop that controls the robot and the specific code required to get each pet. NUM represents the pet/location NUM == 0; start of course NUM == 1; past 1st pet NUM == 2; Past 2nd pet NUM == 3; Past 3rd pet NUM == 4; At 4th pet NUM == 5; On way back from 4th pet NUM == 6; At 3rd pet NUM == 7; At 2nd pet NUM == 8; At 1st pet */ void mainStart() { LCD.clear(); LCD.home(); LCD.print("NUM"); while(true) { // at the start, sets the arm to fit in the door then runs PID code if (NUM == 0) { ArmPID(HEIGHT,ARM_UP); ArmPID(ANGLE,ARM_CENTRE); ArmPID(HEIGHT,ARM_HOR); PIDTape(); } if (NUM == 4) { stopDrive(); moveTo(-30, 30, false); moveTo(200, 30, true); NUM++; PIDTape(); } if (NUM == 6) { stopDrive(); moveTo(0, 10, false); ArmPID(HEIGHT,ARM_UP); pickup(ARM_LEFT); findTape(); PIDTape(); } if (NUM == 7 || NUM == 8) { stopDrive(); moveTo(0, 20, false); moveTo(-5, 5, false); ArmPID(HEIGHT,ARM_UP); pickup(ARM_LEFT); findTape(); PIDTape(); } } } /* == MOTOR CONTROL == */ /* Stops the drive motors. */ void stopDrive() { motor.speed(MOTOR_LEFT, 0); motor.speed(MOTOR_RIGHT, 0); } /* Moves left and right until it finds tape again */ void findTape() { int THRESHOLD = menuItems[4].Value; moveTo(-30,0,true); while(analogRead(QRD_LEFT) < THRESHOLD) { moveTo(60,0,true); if(analogRead(QRD_LEFT) > THRESHOLD) {return;} moveTo(-60,0,true); } } /* Move the robot to a position based on a given angle and distance +ve angle turns left -ve angle turns right */ void moveTo(int angle, float distance, bool tape) { //Vars int THRESHOLD = menuItems[4].Value; int DELAY = 500; //First change angle int angleSpeed = 100; int linSpeed = 150; int angleTurns = ceil((abs(angle)*((LENGTH_OF_AXLE*PI)/360))/DIST_PER_TAPE); int linTurns = ceil(abs(distance)/DIST_PER_TAPE); bool leftDone = false; bool rightDone = false; TURNS_RIGHT = 0; TURNS_LEFT = 0; if (angle > 0) { motor.speed(MOTOR_LEFT, -1*angleSpeed); motor.speed(MOTOR_RIGHT, angleSpeed); } else if (angle == 0) { stopDrive(); } else { motor.speed(MOTOR_LEFT, angleSpeed); motor.speed(MOTOR_RIGHT, -1*angleSpeed); } long startTurn = millis(); LCD.clear(); LCD.home(); LCD.print("Turning"); while((leftDone == false || rightDone == false) && angle != 0) { if(tape && analogRead(QRD_LEFT) > THRESHOLD && millis() - startTurn > DELAY) {return;} checkEnc(); LCD.setCursor(0,1); LCD.print(TURNS_LEFT); LCD.print(" "); LCD.print(TURNS_RIGHT); if(TURNS_LEFT == angleTurns) {motor.speed(MOTOR_LEFT,0); leftDone = true;} if(TURNS_RIGHT == angleTurns) {motor.speed(MOTOR_RIGHT,0); rightDone = true;} } TURNS_LEFT = 0; TURNS_RIGHT = 0; leftDone = false; rightDone = false; if (distance > 0) { motor.speed(MOTOR_LEFT,linSpeed); motor.speed(MOTOR_RIGHT, linSpeed); } else if (distance == 0) { stopDrive(); } else { motor.speed(MOTOR_LEFT,-1*linSpeed); motor.speed(MOTOR_RIGHT,-1*linSpeed); } LCD.clear(); LCD.home(); LCD.print("Moving"); while((leftDone == false || rightDone == false) && distance != 0) { if(tape && analogRead(QRD_LEFT) > THRESHOLD) {return;} checkEnc(); LCD.setCursor(0,1); LCD.print(TURNS_LEFT); LCD.print(" "); LCD.print(TURNS_RIGHT); if(TURNS_LEFT == linTurns) {motor.speed(MOTOR_LEFT,0); leftDone = true;} if(TURNS_RIGHT == linTurns) {motor.speed(MOTOR_RIGHT,0); rightDone = true;} } } /* Check encoders and update turns */ void checkEnc() { cur_enc_left = digitalRead(ROT_LEFT); cur_enc_right = digitalRead(ROT_RIGHT); if(prev_enc_left == HIGH && cur_enc_left == LOW) { TURNS_LEFT++; } if(prev_enc_right == HIGH && cur_enc_right == LOW) { TURNS_RIGHT++; } prev_enc_left = cur_enc_left; prev_enc_right = cur_enc_right; } /* == ARM CONTROL == */ /* Sets the position of a servo to the specified angle Params: Servo - servo we want to control Angle - sets the servo to this angle */ void setServo(int servo, int angle) { if(servo == 0) {RCServo0.write(angle);} else if(servo == 1) {RCServo1.write(angle);} else {RCServo2.write(angle);} } /* The arm moves up and to the centre of the box and then releases the pet into the box */ void dropoff() { ArmPID(HEIGHT, ARM_UP); ArmPID(ANGLE, ARM_CENTRE); setServo(SERVO_PLATE, 90); while(digitalRead(SWITCH_PLATE) == LOW) {} delay(500); setServo(SERVO_PLATE, 0); } /* The arm will move to either the right or the left and then moves down. The arm will then dropoff the pet in the box. Params: Side - the side of the robot we want to pick up on */ void pickup(int side) { ArmPID(HEIGHT, ARM_UP); ArmPID(ANGLE, side); ArmPID(HEIGHT, ARM_DOWN); dropoff(); } /* == TAPE FOLLOWING PID == */ // TODO: CLEAN UP MESSY CONTROL IF STATEMENTS /* PID control for tape following. For reference: P - if too high can cause osscillations D - acts as damping */ void PIDTape() { LCD.clear(); LCD.home(); LCD.print("NUM"); //Variables int P = menuItems[1].Value; //Proportional gain value int D = menuItems[2].Value; //Derivative gain value int S = menuItems[0].Value; //Speed int THRESHOLD = menuItems[4].Value; //threshold for switch from white to black int qrd_left = 0; //Value of left qrd int qrd_right = 0; //Value of right qrd int qrd_pet_front = 0; //Value of pet qrd int qrd_pet_back = 0; //Value of back pet QRD int error = 0; //Current error int last_error = 0; int recent_error = 0; //Recent error int proportional = 0; //Proportional control int derivative = 0; //Derivative control int duration_recent = 0; //Number of loops on recent error int duration_last = 0; //Number of loops on last error int compensation = 0; //Compensation // converting S into a value that is <255 int spd = (int)((float)S*((float)255/(float)MAX_ANALOG)); int WAIT_TIME = 600; int WAIT_TIME_LONG = 3500; int WAIT_TIME_SHORT = 400; long start_time = 0; long start_time_2 = 0; int count = 0; //PID loop while (true) { //Read QRD's qrd_left = analogRead(QRD_LEFT); qrd_right = analogRead(QRD_RIGHT); qrd_pet_front = analogRead(QRD_PET_FRONT); if(count == 0){start_time = millis(); count++;} if((millis() - start_time) > WAIT_TIME) { if(qrd_pet_front > PET_QRD_THRESHOLD) { NUM++; count--; LCD.setCursor(0,1); LCD.print(NUM); if(NUM == 4 || NUM == 6 || NUM == 7 || NUM == 8) {return;} } } /*Determine error * <0 its to the left * >0 its to the right * 0 its dead on */ //left on white if(qrd_left < THRESHOLD) { //right on white if(qrd_right < THRESHOLD) { if(last_error < 0) {error = -5;} //LCD.setCursor(0,1);LCD.print("L2"); else {error = 5;} //LCD.setCursor(0,1);LCD.print("R2"); } //right on black else{error = -1;} //LCD.setCursor(0,1);LCD.print("L1"); } //left on black else { //right on white if(qrd_right < THRESHOLD){error = 1;} //LCD.setCursor(0,1);LCD.print("R1"); //right on black else{error = 0;} //LCD.setCursor(0,1);LCD.print("CE"); } //determine control factors //Proportional control proportional = P*error; //Derivative if(error != last_error) { recent_error = last_error; duration_recent = duration_last; last_error = error; duration_last = 1; } else { duration_last++; } derivative = (int)(((float)D*(float)(error - recent_error))/((float)(duration_recent + duration_last))); //Compensation compensation = proportional + derivative; //Plant control (compensation +ve means move right) motor.speed(MOTOR_LEFT,spd + compensation); motor.speed(MOTOR_RIGHT,spd - compensation); } } /* == ARM PID == */ // TODO: TUNE THIS CODE SO IT IS MORE RELIABLE /* PID control that operates on the homebrew servos. For reference: P - value decreases as it gets closer to the deadband D - acts as the damping force as we move closer to the deadband I - helps push us into the deadband if the location is just outside Params: dim - specifies which motor to use, either the horizontal (angle) or the vertical (hieght) pos - the position to set the arm too */ void ArmPID(int dim, int pos) { //Set variables int P_gain; int I_gain; int max_speed; int maxI; int MOTOR; int PIN; int D_gain = 0; //Height if(dim == HEIGHT) { P_gain = P_HEIGHT; D_gain = D_HEIGHT; I_gain = I_HEIGHT; max_speed = SPEED_HEIGHT; maxI = I_MAX_HEIGHT; MOTOR = MOTOR_CRANE_HEIGHT; PIN = POTENTIOMETER_CRANE_HEIGHT; } //Angle else { P_gain = P_ANGLE; I_gain = I_ANGLE; // I_angle = 1 D_gain = D_ANGLE; max_speed = SPEED_ANGLE; maxI = I_MAX_ANGLE; MOTOR = MOTOR_CRANE_ANGLE; PIN = POTENTIOMETER_CRANE_ANGLE; } // Variables int pot = 0; int count = 0; int target = 0; int deadband = DEADBAND; // PID variables float proportional = 0; float integral = 0; float derivative = 0; float compensator = 0; // Errors float error = 0; float last_error = 0; unsigned long last_integral_update_ms = 0; const unsigned int integral_update_delay_ms = 5; while(true){ pot = analogRead(PIN); error = (pot - pos) / 10.0; if( pot <= ( pos + deadband ) && pot >= ( pos - deadband)) { error = 0; target++; } else { target = 0; } proportional = P_gain * error; derivative = D_gain * (error - last_error); integral = I_gain * (error) + integral; // handling integral gain if ( integral > maxI) { integral = maxI;} if ( integral < -maxI) { integral = -maxI;} if( error == 0) { integral = 0; } compensator = proportional + integral + derivative; // setting max speed for the small motor if( compensator > max_speed) compensator = max_speed; if( compensator < -max_speed) compensator = -max_speed; motor.speed(MOTOR, compensator); last_error = error; if ( target > 1000 ) { return; } if(digitalRead(SWITCH_PLATE) == LOW && pos == ARM_DOWN) {return;} } } /* ========== == MENU == ========== */ /* Control code for the menu where we can adjust values to tune PID control (only for tape following) */ void Menu() { LCD.clear(); LCD.home(); LCD.print("Entering menu"); delay(500); while (true) { /* Show MenuItem value and knob value */ int menuIndex = knob(6) * (MenuItem::MenuItemCount) / 1024; LCD.clear(); LCD.home(); LCD.print(menuItems[menuIndex].Name); LCD.print(" "); LCD.print(menuItems[menuIndex].Value); LCD.setCursor(0, 1); LCD.print("Set to "); LCD.print(knob(7)); LCD.print("?"); delay(100); /* Press start button to save the new value */ if (startbutton()) { delay(100); if (startbutton()) { menuItems[menuIndex].Value = knob(7); menuItems[menuIndex].Save(); delay(250); } } /* Press stop button to exit menu */ if (stopbutton()) { delay(100); if (stopbutton()) { LCD.clear(); LCD.home(); LCD.print("Leaving menu"); delay(500); return; } } } }
import React from 'react'; import { millisecondsToHuman } from '../../utils/TimerUtils'; import Button from '../Button'; import './Timer.css'; const Timer = ({ id,title, project, time, isRunning, onEdit, onRemove, onPlayChange }) => { //static page const buttonLabel = isRunning ? 'STOP' : 'START'; const handleEdit = () => { onEdit(); }; return ( <div className='App-component'> <p>{title}</p> <p>{project}</p> <p>{millisecondsToHuman(time)}</p> <div> <Button className="edit" onClick={handleEdit}>EDIT</Button> <Button className="remove" onClick={()=>onRemove(id)}>REMOVE</Button> </div> <Button className={`btn--${buttonLabel}`} onClick={()=>onPlayChange(id)}>{buttonLabel}</Button> </div> ); }; export default Timer;
import React from 'react'; import {FlatList, View, Text, TouchableOpacity, Image} from "react-native"; import tw from "tailwind-react-native-classnames/dist"; import {Icon} from "react-native-elements"; import {useNavigation} from "@react-navigation/core"; import {useSelector} from "react-redux"; import {selectOrigin} from "../navSlice/navSlice"; const data = [ { id: "123", title: "get a ride", image: "https://links.papareact.com/3pn", screen: "MapScreen", }, { id: "455", title: "Order food", image: "https://links.papareact.com/28w", screen: "EatsScreen", } ]; const NavOptions = () => { const navigation = useNavigation(); const origin = useSelector(selectOrigin); return ( <FlatList data={data} horizontal keyExtractor={(item) => item.id} renderItem={( {item} ) => ( <TouchableOpacity style={tw`p-2 pl-6 pb-8 pt-4 bg-gray-200 m-2 w-40`} onPress={() => navigation.navigate(item.screen)} disabled={!origin} > <View style={tw`${!origin && "opacity-20"}`}> <Text>{item.title}</Text> <Image style={{width: 120, height: 120, resizeMode: "contain"}} source={{uri: item.image}} /> <Text style={tw`mt-2 text-lg font-semibold`}>{item.title}</Text> <Icon style={tw`p-2 bg-black rounded-full w-10 mt-4`} name="arrowright" color="white" type='antdesign' /> </View> </TouchableOpacity> )} /> ); }; export default NavOptions;
// @ts-strict-ignore import React, { type ReactNode, createContext, useState, useContext, useEffect, useCallback, } from 'react'; import debounce from 'debounce'; type IScrollContext = { scrollY: number | undefined; hasScrolledToBottom: (tolerance?: number) => boolean; }; const ScrollContext = createContext<IScrollContext | undefined>(undefined); type ScrollProviderProps = { children?: ReactNode; }; export function ScrollProvider({ children }: ScrollProviderProps) { const [scrollY, setScrollY] = useState(undefined); const [scrollHeight, setScrollHeight] = useState(undefined); const [clientHeight, setClientHeight] = useState(undefined); const hasScrolledToBottom = useCallback( (tolerance = 1) => scrollHeight - scrollY <= clientHeight + tolerance, [clientHeight, scrollHeight, scrollY], ); useEffect(() => { const listenToScroll = debounce(e => { const target = e.target; setScrollY(target?.scrollTop || 0); setScrollHeight(target?.scrollHeight || 0); setClientHeight(target?.clientHeight || 0); }, 10); window.addEventListener('scroll', listenToScroll, { capture: true, passive: true, }); return () => window.removeEventListener('scroll', listenToScroll, { capture: true, }); }, []); return ( <ScrollContext.Provider value={{ scrollY, hasScrolledToBottom }}> {children} </ScrollContext.Provider> ); } export function useScroll(): IScrollContext { return useContext(ScrollContext); }
'use client'; import { zodResolver } from '@hookform/resolvers/zod'; import { useForm } from 'react-hook-form'; import * as z from 'zod'; import { Button } from '@/components/ui/button'; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from '@/components/ui/form'; import { Input } from '@/components/ui/input'; import { registration } from './registration-service'; import { signIn } from 'next-auth/react'; import { useRouter, useSearchParams } from 'next/navigation'; import { useState } from 'react'; import { RotateCw } from 'lucide-react'; import { toast } from 'react-toastify'; import { RegisterDataType, RegisterValidator, } from '@/validators/register-validator'; //здесь использую библиотеку компонентов shadcn/ui,классая штука export const FormRegistration = () => { const [isLoading, setIsLoading] = useState(false); //хуки Next для роутинга const router = useRouter(); const searchParams = useSearchParams(); const callbackUrl = searchParams.get('callbackUrl') || '/'; const form = useForm<RegisterDataType>({ resolver: zodResolver(RegisterValidator), defaultValues: { name: '', email: '', password: '', }, }); async function onSubmit(data: RegisterDataType) { //console.log('data:', data); setIsLoading(true); try { // отправляем данные о пользователе в базу const register = await registration(data); //если удачно зарегистрировались, логинемся if (register) { const login = await signIn('credentials', { email: data.email, password: data.password, redirect: false, }); // так обрабатываем ошибку для логина(т.к. для credentials это не ошибка ) if (login?.error) { toast.error('Email or password is incorrect'); } if (!login?.error) { //если удачно залогинились,редиректим const url = callbackUrl.slice(callbackUrl.lastIndexOf('/') + 1); // window.location.href = `/${url}`; router.push(`/${url}`); } } } catch (error) { console.log(error); } finally { setIsLoading(false); } } return ( <Form {...form}> <form noValidate onSubmit={form.handleSubmit(onSubmit)} className=" flex flex-col gap-3 w-full " > <FormField control={form.control} name="name" render={({ field }) => ( <FormItem> <FormLabel className="text-gray-700 text-sm font-normal"> Name </FormLabel> <FormControl> <Input type="text" placeholder=" Your name" {...field} className=" placeholder:text-zinc-400 text-sm font-normal" /> </FormControl> </FormItem> )} /> <FormField control={form.control} name="email" render={({ field }) => ( <FormItem className=" relative"> <FormLabel className="text-gray-700 text-sm font-normal"> Email </FormLabel> <FormControl> <Input type="email" placeholder="Your working email" {...field} className=" placeholder:text-zinc-400 text-sm font-normal" /> </FormControl> <FormMessage className=" absolute text-[11px] top-[62px] " /> </FormItem> )} /> <FormField control={form.control} name="password" render={({ field }) => ( <FormItem className=" relative"> <FormLabel className="text-gray-700 text-sm font-normal"> Password </FormLabel> <FormControl> <Input type="password" placeholder="Password" {...field} className=" placeholder:text-zinc-400 text-sm font-normal" /> </FormControl> <FormMessage className=" absolute text-[11px] top-[62px] " /> </FormItem> )} /> <div> <Button disabled={isLoading} type="submit" className=" w-full bg-cyan-800 hover:bg-cyan-900 mt-[12px] " > {isLoading ? ( <RotateCw size={20} color="#ffffff" strokeWidth={1.5} absoluteStrokeWidth className="mr-4 animate-spin" /> ) : null} Sung up </Button> </div> </form> </Form> ); };
#! /usr/bin/env python3 import att26a from att26a.simulator import Att26aSimBase from PyQt5 import QtCore from PyQt5 import QtWidgets from PyQt5 import QtGui import logging # Parse the ui file once. import sys, os.path from PyQt5 import uic thisdir = os.path.dirname(os.path.abspath(__file__)) sys.path.append(thisdir) # Needed to load ui Att26aSimUi, Att26aSimUiBase = uic.loadUiType(os.path.join(thisdir, 'main.ui')) del sys.path[-1] # Remove the now unnecessary path entry __title__ = 'att26aguisim' __version__ = '0.0.1' __author__ = 'Jessy Diamond Exum' palette_blink1 = QtGui.QPalette() palette_blink1.setColor(QtGui.QPalette.Highlight, QtGui.QColor(QtCore.Qt.blue)) palette_blink2 = QtGui.QPalette() palette_blink2.setColor(QtGui.QPalette.Highlight, QtGui.QColor(QtCore.Qt.green)) palette_off_on = QtGui.QPalette() palette_off_on.setColor(QtGui.QPalette.Highlight, QtGui.QColor(QtCore.Qt.red)) class Att26ASimQt(QtWidgets.QMainWindow): signal_set_led_state = QtCore.pyqtSignal(int, int) signal_set_led_range_state = QtCore.pyqtSignal(int, list) class Att26aSimInstrumentor(Att26aSimBase): def __init__(self, serialdev, qtsim): super().__init__(serialdev) self.qtsim = qtsim def on_set_led_range_state(self, start_ledid, states_on_off): self.qtsim.signal_set_led_range_state.emit(start_ledid, states_on_off) def on_set_led_state(self, state, ledID): self.qtsim.signal_set_led_state.emit(state, ledID) def on_set_factory_test_mode_enable(self, enable): self.qtsim.on_set_factory_test_mode_enable(enable) def on_set_IO_enable(self, enable): self.qtsim.on_set_IO_enable(enable) def on_get_led_status(self, ledID): return self.on_get_led_status(ledID) def on_set_led_range_state(self, start_ledid, states_on_off): self._log.info("Setting %d LEDs starting at %d"%(len(states_on_off), start_ledid)) for i, state in enumerate(states_on_off): led = self.leds[(start_ledid + i) % 100] led.setPalette(palette_off_on) led.setValue(state) def on_set_led_state(self, state, ledID): self._log.info("Setting led %d's state to %d IN PASS THROUGH"%(ledID, state)) led = self.leds[ledID] ison = True if state == att26a.LED_ON: led.setPalette(palette_off_on) elif state == att26a.LED_BLINK1: led.setPalette(palette_blink1) elif state == att26a.LED_BLINK2: led.setPalette(palette_blink2) else: led.setPalette(palette_off_on) ison = False led.setValue(ison) def on_set_factory_test_mode_enable(self, enable): self._log.info("%s factory test" % "Enable" if enable else "Disable") self._factory_test = enable def on_set_IO_enable(self, enable): self._log.info("%s IO driver" % "Enable" if enable else "Disable") self._io_enabled = enable def on_get_led_status(self, ledID): self._log.info("Reading led %d state" % ledID) return self.leds[ledID].value() def __init__(self, serialdev, log=None): super(Att26ASimQt, self).__init__() self.ui = Att26aSimUi() self.ui.setupUi(self) # Set the signals for button presses for btn_num in range(120): btn = self.findChild(QtWidgets.QPushButton, "btn_%03d"%btn_num) btn.pressed.connect(self.on_any_btn_press) self.leds = [self.findChild(QtWidgets.QProgressBar, "led_%03d"%btn_num) for btn_num in range(120)] self._factory_test = False self._io_enabled = True self.signal_set_led_state.connect(self.on_set_led_state) self.signal_set_led_range_state.connect(self.on_set_led_range_state) self.__sim = Att26ASimQt.Att26aSimInstrumentor(serialdev, self) self._log = logging.getLogger('att26aguisim') if not log else log @QtCore.pyqtSlot() def on_any_btn_press(self): btn_num = int(self.sender().text()) self.__sim.send_btn_press(btn_num) def run(app, serialdev): window = Att26ASimQt(serialdev) window.show() return app.exec_() # Start the event loop. def main_bootstrap(serialdev): import sys # Initialize the QApplication object, and free it last. # Not having this in a different function than other QT # objects can cause segmentation faults as app is freed # before the QWidgets. app = QtWidgets.QApplication(sys.argv) # Allow Ctrl-C to interrupt QT by scheduling GIL unlocks. timer = QtCore.QTimer() timer.start(500) timer.timeout.connect(lambda: None) # Let the interpreter run. sys.exit(run(app, serialdev)) def main_api(address="", port=7778, log=None): from att26a.serial_adapter import RFC2217SerialAdapter r = RFC2217SerialAdapter(address, port, log) main_bootstrap(r) def main_cli(): import argparse from att26a.clihelper import VAction parser = argparse.ArgumentParser(description='AT&T 26A graphical simulator') parser.add_argument('--port', type=int, nargs='?', default=7778, help='Port to host rfc2217 server.') parser.add_argument('--addr', type=str, default="localhost", help='Address to host rfc2217 server.') parser.add_argument('-v', nargs='?', action=VAction, dest='verbose', default=0, help="Provide debug information. More than one v supported") args = parser.parse_args() logging.basicConfig(level=logging.INFO) # Enable root filter to see serial logs logging.getLogger('RFC2217SerialAdapter').setLevel(logging.INFO) if args.verbose >= 2: loglevel = logging.DEBUG logging.basicConfig(level=loglevel) elif args.verbose >= 1: loglevel = logging.INFO else: loglevel = logging.WARNING logging.getLogger('att26aguisim').setLevel(loglevel) main_api(args.addr, args.port) def _main_subprocess_bootstrap(q): q.put(23) main_api(port=0) def start_subprocess(): import multiprocessing as mp mp.set_start_method("spawn") q = mp.Queue() p = mp.Process(target=_main_subprocess_bootstrap, args=(q,)) p.start() return q.get() if __name__ == "__main__": main_cli()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Panda E-commerce</title> <!-- Bootstrap css --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <!-- custom style --> <link rel="stylesheet" href="css/style.css"> </head> <body> <header> <nav class="container navbar navbar-expand-lg navbar-light panda-nav-bg extra-margin"> <div class="container"> <a class="navbar-brand" href="#"> <img src="./images/logo.png" alt=""> </a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav"> <a class="nav-link active" aria-current="page" href="#">Home</a> <a class="nav-link" href="#shoes">Shoes</a> <a class="nav-link" href="#backpack">Backpack</a> <a class="nav-link" href="#subscribe">Subscribe</a> </div> </div> </div> </nav> <!-- image slider --> <section class="container extra-margin"> <div id="carouselExampleControls" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-inner rounded-3"> <div class="carousel-item active"> <div class="row panda-slides-bg d-flex align-items-center p-5 py-3 row-cols-md-2"> <div class="col-lg-7"> <h1> Cool Dude Headphone </h1> <p>This is the best headphone in the world for people who just want to waste time in front of funky world. </p> <h1>$422</h1> <div class="btn buy-now-btn ps-4 pe-4">Buy Now</div> </div> <div class="col-lg-5"> <img src="./images/banner-images/headphone.png" class="d-block w-100" alt="..."> </div> </div> </div> <div class="carousel-item"> <div class="row panda-slides-bg d-flex align-items-center p-5 py-3 row-cols-md-2"> <div class="col-lg-7"> <h1> Mega LCD TV For Sports </h1> <p> This is the best tv in the world for people who just want to waste time in front of tv. </p> <h1>$1422</h1> <div class="btn buy-now-btn ps-4 pe-4">Buy Now</div> </div> <div class="col-lg-5"> <img src="./images/banner-images/tv.png" class="d-block w-100" alt="..."> </div> </div> </div> <div class="carousel-item"> <div class="row panda-slides-bg d-flex align-items-center p-5 py-3 row-cols-md-2"> <div class="col-lg-7"> <h1> X-Box for your living room </h1> <p> This is the best x-box in the world for people who just want to waste time in front of fake sports. </p> <h1>$690</h1> <div class="btn buy-now-btn ps-4 pe-4">Buy Now</div> </div> <div class="col-lg-5"> <img src="./images/banner-images/xbox.png" class="d-block w-100" alt="..."> </div> </div> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> </section> </header> <main> <!-- categories --> <section class="container extra-margin"> <div class="row g-4 row-cols-md-3 row-cols-sm-2 row-cols-1"> <div class="col-lg-4"> <div class="p-3 border d-flex align-items-center justify-content-around bg-danger bg-gradient rounded-3"> <h1 class="text-white">Watch</h1> <img class="w-25" src="./images/categories/watch.png" alt=""> </div> </div> <div class="col-lg-4"> <div class="p-3 border d-flex align-items-center justify-content-around bg-warning bg-gradient rounded-3"> <h1 class="text-white">Bag</h1> <img class="w-25" src="./images/categories/bag.png" alt=""> </div> </div> <div class="col-lg-4"> <div class="p-3 border d-flex align-items-center justify-content-around bg-primary bg-gradient rounded-3"> <h1 class="text-white">Shoes</h1> <img class="w-25" src="./images/categories/shoes.png" alt=""> </div> </div> </div> </section> <!-- shoes card --> <section class="container extra-margin" id="shoes"> <h2>Shoes</h2> <div class="row row-cols-1 row-cols-sm-2 row-cols-md-2 row-cols-lg-3 g-4"> <div class="col"> <div class="card border-0 h-100 shadow"> <img src="./images/shoes/shoe-1.png" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">Supply 350</h5> <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> </div> <div> <div class="btn buy-now-btn ms-3 mb-3 px-4">Buy Now</div> </div> </div> </div> <div class="col"> <div class="card border-0 h-100 shadow"> <img src="./images/shoes/shoe-2.png" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">Nike 360</h5> <p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p> </div> <div> <div class="btn buy-now-btn ms-3 mb-3 px-4">Buy Now</div> </div> </div> </div> <div class="col"> <div class="card border-0 h-100 shadow"> <img src="./images/shoes/shoe-3.png" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">Red Airmax</h5> <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p> </div> <div> <div class="btn buy-now-btn ms-3 mb-3 px-4">Buy Now</div> </div> </div> </div> </div> </section> <!-- bags card --> <section class="container extra-margin" id="backpack"> <h2>Backpack</h2> <div class="row row-cols-1 row-cols-sm-2 row-cols-md-2 row-cols-lg-3 g-4"> <div class="col"> <div class="card border-0 h-100 shadow"> <img src="./images/bags/bag-1.png" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">Laltu Bag</h5> <h4>$360</h4> <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> </div> <div class="mt-5"> <div class="btn buy-now-btn ms-3 mb-3 px-4">Buy Now</div> </div> </div> </div> <div class="col"> <div class="card border-0 h-100 shadow"> <img src="./images/bags/bag-2.png" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">Niltu Bag</h5> <h4>$543</h4> <p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p> </div> <div class="mt-5"> <div class="btn buy-now-btn ms-3 mb-3 px-4">Buy Now</div> </div> </div> </div> <div class="col"> <div class="card border-0 h-100 shadow"> <img src="./images/bags/bag-3.png" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">Kaltu Bag</h5> <h4>$431</h4> <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p> </div> <div class="mt-5"> <div class="btn buy-now-btn ms-3 mb-3 px-4">Buy Now</div> </div> </div> </div> </div> </section> <!-- subscribe part --> <section id="subscribe" style="height: 300px;" class="container d-flex justify-content-center align-items-center panda-slides-bg extra-margin rounded-3"> <div> <h1>LET'S STAY IN TOUCH</h1> <h6>Get updates on sales, specials and more</h6> <input class="form-control" type="text" placeholder="Your E-mail"> <br> <div class="btn buy-now-btn">Submit</div> </div> </section> </main> <footer class="text-center mt-5 mb-3"> <small>©2020. Panda Commerce. All rights reserved. Sofia, Bulgaria.</small> </footer> <!-- bootstrap script --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> </body> </html>
# Extending the Connect 4 Project Implement these features into your version of the Connect 4 project. 1. Locking board after a win. If clicking your board after a winner has been declared causes a stone to be placed, or the winner to be declared again, make it so that clicking the board does nothing. 2. If your project doesn't have one, implement a reset button, so that at any stage in the game, the user can reset the game. When a winner has been declared, overlay a reset button over the board. 3. Implement a way to keep score over various games. For instance, you could have a box that counts the number of games won by black or red in that session. 4. Implement an introduction screen that lets you choose a board size before starting to play. 5. Implement a way to undo a move with an button next to the board. 6. Implement a way to _replay_ the game once it's over. That is, the moves played during the game should appear quickly on screen, showing you every move that was played.
/* * Copyright (c) 2022-2023 Huawei Device Co., Ltd. * 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. */ #ifndef FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_NG_PATTERNS_OPTION_OPTION_PATTERN_H #define FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_NG_PATTERNS_OPTION_OPTION_PATTERN_H #include <optional> #include "base/memory/referenced.h" #include "core/components/select/select_theme.h" #include "core/components/text/text_theme.h" #include "core/components_ng/base/frame_node.h" #include "core/components_ng/pattern/option/option_accessibility_property.h" #include "core/components_ng/pattern/option/option_event_hub.h" #include "core/components_ng/pattern/option/option_layout_algorithm.h" #include "core/components_ng/pattern/option/option_paint_method.h" #include "core/components_ng/pattern/option/option_paint_property.h" #include "core/components_ng/pattern/pattern.h" #include "core/components_ng/render/paint_property.h" #include "core/pipeline_ng/ui_task_scheduler.h" namespace OHOS::Ace::NG { class OptionPattern : public Pattern { DECLARE_ACE_TYPE(OptionPattern, Pattern); public: explicit OptionPattern(int index) : index_(index) {} ~OptionPattern() override = default; RefPtr<NodePaintMethod> CreateNodePaintMethod() override { return MakeRefPtr<OptionPaintMethod>(); } RefPtr<PaintProperty> CreatePaintProperty() override { return MakeRefPtr<OptionPaintProperty>(); } RefPtr<EventHub> CreateEventHub() override { return MakeRefPtr<OptionEventHub>(); } RefPtr<AccessibilityProperty> CreateAccessibilityProperty() override { return MakeRefPtr<OptionAccessibilityProperty>(); } RefPtr<LayoutAlgorithm> CreateLayoutAlgorithm() override { return MakeRefPtr<OptionLayoutAlgorithm>(); } bool IsAtomicNode() const override { return false; } void SetTextNode(const RefPtr<FrameNode>& text) { text_ = text; } void SetIconNode(const RefPtr<FrameNode>& icon) { icon_ = icon; } void SetPasteButton(const RefPtr<FrameNode>& pasteButton) { pasteButton_ = pasteButton; } void SetBgColor(const Color& color); // set font props void SetFontSize(const Dimension& value); void SetItalicFontStyle(const Ace::FontStyle& value); void SetFontWeight(const FontWeight& value); void SetFontFamily(const std::vector<std::string>& value); void SetFontColor(const Color& color); Color GetBgColor(); // get font props Dimension GetFontSize(); Ace::FontStyle GetItalicFontStyle(); FontWeight GetFontWeight(); std::vector<std::string> GetFontFamily(); Color GetFontColor(); std::string GetText(); // XTS inspector functions std::string InspectorGetFont(); float GetSelectOptionWidth(); void SetIcon(const std::string& src) { iconSrc_ = src; } const std::string& GetIcon() { return iconSrc_; } FocusPattern GetFocusPattern() const override { return { FocusType::NODE, true, FocusStyleType::INNER_BORDER }; } void UpdateNextNodeDivider(bool needDivider); void SetBgBlendColor(const Color& color) { bgBlendColor_ = color; } Color GetBgBlendColor() const { return bgBlendColor_; } void SetIsHover(bool isHover) { isHover_ = isHover; } bool IsHover() const { return isHover_; } void PlayBgColorAnimation(bool isHoverChange = true); void UpdateText(const std::string& content); void UpdateIcon(const std::string& src); void SetMenu(const WeakPtr<FrameNode>& menuWeak) { menuWeak_ = menuWeak; } const WeakPtr<FrameNode>& GetMenu() const { return menuWeak_; } void SetIsWidthModifiedBySelect(bool isModified) { isWidthModifiedBySelect_ = isModified; } bool IsWidthModifiedBySelect() const { return isWidthModifiedBySelect_; } void SetIsSelectOption(bool isSelect) { isSelectOption_ = isSelect; } bool IsSelectOption() const { return isSelectOption_; } private: void OnAttachToFrameNode() override; void OnModifyDone() override; // make render after measure and layout bool OnDirtyLayoutWrapperSwap(const RefPtr<LayoutWrapper>& dirty, const DirtySwapConfig& config) override { return !(config.skipMeasure && config.skipLayout); } // register option's callback void RegisterOnClick(); void RegisterOnTouch(); void RegisterOnHover(); void RegisterOnKeyEvent(); // change option paint props on press void OnPress(const TouchEventInfo& info); void OnHover(bool isHover); bool OnKeyEvent(const KeyEvent& event); void OnSelectProcess(); bool UpdateOptionFocus(KeyCode code); void SetAccessibilityAction(); void UpdatePasteFontColor(const Color& fontColor); std::optional<Color> bgColor_; // src of icon image, used in XTS inspector std::string iconSrc_; WeakPtr<FrameNode> menuWeak_; RefPtr<FrameNode> text_; RefPtr<FrameNode> icon_; RefPtr<FrameNode> pasteButton_; RefPtr<TextTheme> textTheme_; RefPtr<SelectTheme> selectTheme_; // this option node's index in the menu int index_ = -1; Color bgBlendColor_ = Color::TRANSPARENT; bool isHover_ = false; bool isWidthModifiedBySelect_ = false; bool isSelectOption_ = false; ACE_DISALLOW_COPY_AND_MOVE(OptionPattern); }; } // namespace OHOS::Ace::NG #endif // FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_NG_PATTERNS_OPTION_OPTION_PATTERN_H
// // CategoriesView.swift // CakesHub // // Created by Dmitriy Permyakov on 17.02.2024. // Copyright 2024 © VK Team CakesHub. All rights reserved. // import SwiftUI struct CategoriesView: View { // MARK: View Model typealias ViewModel = CategoriesViewModel @State private(set) var viewModel = ViewModel() @EnvironmentObject private var root: RootViewModel @EnvironmentObject private var nav: Navigation @Environment(\.modelContext) private var modelContext // MARK: View var body: some View { MainViewBlock .onAppear(perform: onAppear) .navigationDestination(for: ViewModel.Screens.self) { screen in switch screen { case var .sectionCakes(products): let productModels: [ProductModel] = products.map { product in RootViewModel.getProductSimilarProducts(for: product, data: products) } let vm = AllProductsCategoryViewModel(products: productModels) AllProductsCategoryView(viewModel: vm) } } } } // MARK: - Network private extension CategoriesView { func onAppear() { viewModel.setRootViewModel(with: root) viewModel.setModelContext(with: modelContext) viewModel.fetchSections() } } // MARK: - Actions extension CategoriesView { /// Нажали на ячейку секции func didTapSectionCell(title: String) { let products = viewModel.didTapSectionCell(title: title) nav.addScreen(screen: ViewModel.Screens.sectionCakes(products)) } } // MARK: - Preview #Preview { CategoriesView() .environmentObject(Navigation()) .environmentObject(RootViewModel.mockData) .modelContainer( Preview(SDCategoryModel.self).container ) }
package mm221162023Veterinariaspring.VetPet.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.ui.Model; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.ResponseBody; import java.time.LocalDate; import mm221162023Veterinariaspring.VetPet.entidades.Paciente; import mm221162023Veterinariaspring.VetPet.entidades.Raza; import mm221162023Veterinariaspring.VetPet.servicios.ServicioPaciente; import mm221162023Veterinariaspring.VetPet.utilidades.RespuestaEstandard; import mm221162023Veterinariaspring.VetPet.servicios.ServicioRaza; import mm221162023Veterinariaspring.VetPet.servicios.ServicioTipoPaciente; import mm221162023Veterinariaspring.VetPet.utilidades.Validador; @Controller public class PacienteController { @Autowired private ServicioPaciente sPaciente; @Autowired private ServicioRaza sRaza; @Autowired private ServicioTipoPaciente sTipoPaciente; @GetMapping("/pacientes") public String Pacientes(Model model) { var pacientes = sPaciente.ObtenerPacientesActivos(); model.addAttribute("pacientes", pacientes); return "Paciente/InicioPacientes"; } @GetMapping("/crear-paciente") public String CrearPaciente(Model model) { Paciente p = new Paciente(); p.setFechaInscripcion(LocalDate.now()); model.addAttribute("paciente", p); var razas = sRaza.ObtenerRazasActivas(); model.addAttribute("razas", razas); var tipos = sTipoPaciente.ObtenerTipoPacientesActivos(); model.addAttribute("tipoPacientes", tipos); return "Paciente/CrearPaciente"; } @PostMapping("/post-paciente") public String PostPaciente(Paciente p, Model model) { p.setActivo(true); p.setFechaInscripcion(LocalDate.now()); if (!Validador.ValidarPaciente(p)) { model.addAttribute("paciente", p); model.addAttribute("mensaje", "Todos los campos son requeridos."); var razas = sRaza.ObtenerRazasActivas(); model.addAttribute("razas", razas); var tipos = sTipoPaciente.ObtenerTipoPacientesActivos(); model.addAttribute("tipoPacientes", tipos); return "Paciente/CrearPaciente"; } Raza r = sRaza.ObtenerRazaPorId(p.getRazaId()); p.setTipoPaciente(r.getTipoPaciente()); sPaciente.CrearPaciente(p); return "redirect:pacientes"; } @PostMapping("/delete-paciente/{idPaciente}") @ResponseBody() public RespuestaEstandard DeletePaciente(@PathVariable("idPaciente") int idPaciente, Model model) { sPaciente.EliminarPaciente(idPaciente); RespuestaEstandard res = new RespuestaEstandard(false, "Exitoso."); return res; } @GetMapping("/editar-paciente/{idPaciente}") public String EditarPaciente(@PathVariable("idPaciente") int idPaciente, Model model) { Paciente p = sPaciente.ObtenerPacientePorId(idPaciente); model.addAttribute("paciente", p); var razas = sRaza.ObtenerRazasActivas(); model.addAttribute("razas", razas); return "Paciente/EditarPaciente"; } @PostMapping("/put-paciente") public String PutPaciente(Paciente p, Model model) { Raza r = sRaza.ObtenerRazaPorId(p.getRazaId()); p.setTipoPaciente(r.getTipoPaciente()); if (!Validador.ValidarPaciente(p)) { model.addAttribute("paciente", p); model.addAttribute("mensaje", "Todos los campos son requeridos."); var razas = sRaza.ObtenerRazasActivas(); model.addAttribute("razas", razas); var tipos = sTipoPaciente.ObtenerTipoPacientesActivos(); model.addAttribute("tipoPacientes", tipos); return "Paciente/EditarPaciente"; } sPaciente.ActualizarPaciente(p); return "redirect:pacientes"; } }
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { QAGuard } from 'src/app/Core/guards/QAPermission/qa.guard'; import { QAWorkPermissionComponent } from './components/qawork-permission/qawork-permission.component'; import { NonConformanceMaterialComponent } from './components/non-conformance-material/non-conformance-material.component'; import { AddNonConformanceComponent } from './components/add-non-conformance/add-non-conformance.component'; import { DeveloperPermissionGuard } from 'src/app/Core/guards/developer/developer-permission.guard'; const routes: Routes = [ { path:'WorkPermissionHistory', component:QAWorkPermissionComponent, canActivate:[QAGuard] }, { path:'NonConformanceMaterial', component:NonConformanceMaterialComponent, canActivate:[QAGuard] }, { path:'AddNonConformance', component:AddNonConformanceComponent, canActivate:[DeveloperPermissionGuard] }, ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class QARoutingModule { static components = [ QAWorkPermissionComponent, NonConformanceMaterialComponent,AddNonConformanceComponent]; }
package com.example.finaaseat; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Logger; import com.google.firebase.database.ValueEventListener; public class Register extends AppCompatActivity { FirebaseDatabase root = FirebaseDatabase.getInstance(); DatabaseReference dreference = root.getReference(); private final String defaultProfilePicUrl = "https://firebasestorage.googleapis.com/v0/b/findaseat-a81b4.appspot.com/o/trojan.jpg?alt=media&token=32d699ea-5fc8-41a5-9905-c87529b2e9b3"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); final EditText name = findViewById((R.id.name)); final EditText email = findViewById((R.id.email)); final EditText uscid = findViewById((R.id.uscid_register)); final EditText password = findViewById((R.id.password_register)); final Button registerButton = findViewById((R.id.register_button)); final TextView loginacc = findViewById((R.id.login_account)); registerButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final String nameTxt = name.getText().toString(); final String emailTxt = email.getText().toString(); final String passwordTxt = password.getText().toString(); final String uscTxt = uscid.getText().toString(); if(nameTxt.isEmpty() || emailTxt.isEmpty() || passwordTxt.isEmpty() || uscTxt.isEmpty()){ Toast.makeText(Register.this, "Please fill all fields", Toast.LENGTH_SHORT).show(); } if(!uscTxt.matches("\\d{10}")) { Toast.makeText(Register.this, "Invalid USC ID. Must be 10 digit number.", Toast.LENGTH_SHORT).show(); // Stop further processing return; } else { // dreference.child("users").setValue("111"); dreference.child("users").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { if(snapshot.hasChild(uscTxt)){ Toast.makeText(Register.this, "USCID is already registered", Toast.LENGTH_SHORT).show(); } else { // use email as unique identity dreference.child("users").child(uscTxt).child("name").setValue(nameTxt); dreference.child("users").child(uscTxt).child("email").setValue(emailTxt); dreference.child("users").child(uscTxt).child("uscid").setValue(uscTxt); dreference.child("users").child(uscTxt).child("password").setValue(passwordTxt); dreference.child("users").child(uscTxt).child("profile").setValue(defaultProfilePicUrl); Toast.makeText(Register.this, "Registered Successfully.", Toast.LENGTH_SHORT).show(); finish(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } } }); loginacc.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(Register.this, Login.class)); } }); } }
package com.interceptors; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AfterInterceptor implements HandlerInterceptor { /*** * preHandle() 方法:该方法会在控制器方法前执行,其返回值表示是否中断后续操作。当其返回值为true时,表示继续向下执行; * 当其返回值为false时,会中断后续的所有操作(包括调用下一个拦截器和控制器类中的方法执行等)。 * * postHandle()方法:该方法会在控制器方法调用之后,且解析视图之前执行。可以通过此方法对请求域中的模型和视图做出进一步的修改。 * * afterCompletion()方法:该方法会在整个请求完成,即视图渲染结束之后执行。可以通过此方法实现一些资源清理、记录日志信息等工作。 * @param request * @param response * @param handler * @return * @throws Exception */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { System.out.println("preHandle22在控制器之前执行---"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { System.out.println(" postHandler:控制器之后处理222 "); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { System.out.println("afterCompletion:完成后干什么,(渲染)222"); } }
Date: Tue, 13 Jan 2009 18:40:12 -0500 From: Nelson <> Subject: [PATCH 5/5] Add linear filter Sender: linux-kernel-owner@vger.kernel.org Precedence: bulk List-ID: <linux-kernel.vger.kernel.org> X-Mailing-List: linux-kernel@vger.kernel.org X-Lkml-Link: https://lkml.org/lkml/2009/1/13/513 From: Nelson Castillo <arhuaco@freaks-unidos.net> * Linearly scale touchscreen values. * Expose the constants for the linear transformation using sysfs. This patch allow programs to gather data directly from /dev/input/eventX. This is optional, you can use TSLIB to do the linear transformation if you prefer. Signed-off-by: Nelson Castillo <arhuaco@freaks-unidos.net> --- drivers/input/touchscreen/Kconfig | 8 + drivers/input/touchscreen/Makefile | 1 drivers/input/touchscreen/ts_filter_linear.c | 178 ++++++++++++++++++++++++++ include/linux/ts_filter_linear.h | 64 +++++++++ 4 files changed, 251 insertions(+), 0 deletions(-) create mode 100644 drivers/input/touchscreen/ts_filter_linear.c create mode 100644 include/linux/ts_filter_linear.h diff --git a/drivers/input/touchscreen/Kconfig b/drivers/input/touchscreen/Kconfig index 3f725d4..a3ed1dc 100644 --- a/drivers/input/touchscreen/Kconfig +++ b/drivers/input/touchscreen/Kconfig @@ -45,6 +45,14 @@ config TOUCHSCREEN_FILTER_MEAN Say Y here if you want to use the Mean touchscreen filter, it can further improve decent quality data by removing jitter +config TOUCHSCREEN_FILTER_LINEAR + bool "Linear Touchscreen Filter" + depends on INPUT_TOUCHSCREEN && TOUCHSCREEN_FILTER + default Y + help + Say Y here if you want to use the Linear touchscreen filter, it + enables the use of calibration data for the touchscreen. + endif config TOUCHSCREEN_ADS7846 diff --git a/drivers/input/touchscreen/Makefile b/drivers/input/touchscreen/Makefile index 84651c2..180b557 100644 --- a/drivers/input/touchscreen/Makefile +++ b/drivers/input/touchscreen/Makefile @@ -35,3 +35,4 @@ obj-$(CONFIG_TOUCHSCREEN_FILTER) += ts_filter.o obj-$(CONFIG_TOUCHSCREEN_FILTER_GROUP) += ts_filter_group.o obj-$(CONFIG_TOUCHSCREEN_FILTER_MEDIAN) += ts_filter_median.o obj-$(CONFIG_TOUCHSCREEN_FILTER_MEAN) += ts_filter_mean.o +obj-$(CONFIG_TOUCHSCREEN_FILTER_LINEAR) += ts_filter_linear.o diff --git a/drivers/input/touchscreen/ts_filter_linear.c b/drivers/input/touchscreen/ts_filter_linear.c new file mode 100644 index 0000000..4803e17 --- /dev/null +++ b/drivers/input/touchscreen/ts_filter_linear.c @@ -0,0 +1,178 @@ +/* + * 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; 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 + * + * Copyright (C) 2008 by Openmoko, Inc. + * Author: Nelson Castillo <arhuaco@freaks-unidos.net> + * All rights reserved. + * + * Linearly scale touchscreen values. + * + * Expose the TS_FILTER_LINEAR_NCONSTANTS for the linear transformation + * using sysfs. + * + */ + +#include <linux/ts_filter_linear.h> +#include <linux/kernel.h> +#include <linux/slab.h> +#include <linux/string.h> + + +/* + * sysfs functions + */ + + +static ssize_t const_attr_show(struct kobject *kobj, + struct attribute *attr, + char *buf) +{ + struct const_attribute *a = to_const_attr(attr); + + return a->show(to_const_obj(kobj), a, buf); +} + +static ssize_t const_attr_store(struct kobject *kobj, + struct attribute *attr, + const char *buf, size_t len) +{ + struct const_attribute *a = to_const_attr(attr); + + return a->store(to_const_obj(kobj), a, buf, len); +} + +static struct sysfs_ops const_sysfs_ops = { + .show = const_attr_show, + .store = const_attr_store, +}; + +static void const_release(struct kobject *kobj) +{ + kfree(to_const_obj(kobj)->tsfl); +} + +static ssize_t const_show(struct const_obj *obj, struct const_attribute *attr, + char *buf) +{ + int who; + + sscanf(attr->attr.name, "%d", &who); + return sprintf(buf, "%d\n", obj->tsfl->constants[who]); +} + +static ssize_t const_store(struct const_obj *obj, struct const_attribute *attr, + const char *buf, size_t count) +{ + int who; + + sscanf(attr->attr.name, "%d", &who); + sscanf(buf, "%d", &obj->tsfl->constants[who]); + return count; +} + +/* + * filter functions + */ + +static struct ts_filter *ts_filter_linear_create(struct platform_device *pdev, + void *conf, int count_coords) +{ + struct ts_filter_linear *tsfl; + int i; + int ret; + + tsfl = kzalloc(sizeof(struct ts_filter_linear), GFP_KERNEL); + if (!tsfl) + return NULL; + + tsfl->config = (struct ts_filter_linear_configuration *)conf; + tsfl->tsf.count_coords = count_coords; + + for (i = 0; i < TS_FILTER_LINEAR_NCONSTANTS; ++i) { + tsfl->constants[i] = tsfl->config->constants[i]; + + /* sysfs */ + sprintf(tsfl->attr_names[i], "%d", i); + tsfl->kattrs[i].attr.name = tsfl->attr_names[i]; + tsfl->kattrs[i].attr.mode = 0666; + tsfl->kattrs[i].show = const_show; + tsfl->kattrs[i].store = const_store; + tsfl->attrs[i] = &tsfl->kattrs[i].attr; + } + tsfl->attrs[i] = NULL; + + tsfl->const_ktype.sysfs_ops = &const_sysfs_ops; + tsfl->const_ktype.release = const_release; + tsfl->const_ktype.default_attrs = tsfl->attrs; + tsfl->c_obj.tsfl = tsfl; /* kernel frees tsfl in const_release */ + + /* TODO: /sys/ts-calibration is not OK */ + ret = kobject_init_and_add(&tsfl->c_obj.kobj, &tsfl->const_ktype, + &pdev->dev.kobj, "calibration"); + if (ret) { + kobject_put(&tsfl->c_obj.kobj); + return NULL; + } + + printk(KERN_INFO" Created Linear ts filter depth %d\n", count_coords); + + return &tsfl->tsf; +} + +static void ts_filter_linear_destroy(struct platform_device *pdev, + struct ts_filter *tsf) +{ + struct ts_filter_linear *tsfl = (struct ts_filter_linear *)tsf; + + /* kernel frees tsfl in const_release */ + kobject_put(&tsfl->c_obj.kobj); +} + +static void ts_filter_linear_clear(struct ts_filter *tsf) +{ + if (tsf->next) /* chain */ + (tsf->next->api->clear)(tsf->next); +} + + +static void ts_filter_linear_scale(struct ts_filter *tsf, int *coords) +{ + struct ts_filter_linear *tsfl = (struct ts_filter_linear *)tsf; + int *k = tsfl->constants; + int c0 = coords[tsfl->config->coord0]; + int c1 = coords[tsfl->config->coord1]; + + coords[tsfl->config->coord0] = (k[2] + k[0] * c0 + k[1] * c1) / k[6]; + coords[tsfl->config->coord1] = (k[5] + k[3] * c0 + k[4] * c1) / k[6]; + + if (tsf->next) + (tsf->next->api->scale)(tsf->next, coords); +} + +static int ts_filter_linear_process(struct ts_filter *tsf, int *coords) +{ + if (tsf->next) + return (tsf->next->api->process)(tsf->next, coords); + + return 1; +} + +struct ts_filter_api ts_filter_linear_api = { + .create = ts_filter_linear_create, + .destroy = ts_filter_linear_destroy, + .clear = ts_filter_linear_clear, + .process = ts_filter_linear_process, + .scale = ts_filter_linear_scale, +}; diff --git a/include/linux/ts_filter_linear.h b/include/linux/ts_filter_linear.h new file mode 100644 index 0000000..dab5390 --- /dev/null +++ b/include/linux/ts_filter_linear.h @@ -0,0 +1,64 @@ +#ifndef __TS_FILTER_LINEAR_H__ +#define __TS_FILTER_LINEAR_H__ + +#include <linux/ts_filter.h> +#include <linux/kobject.h> + +/* + * touchscreen linear filter. + * + * Copyright (C) 2008 by Openmoko, Inc. + * Author: Nelson Castillo <arhuaco@freaks-unidos.net> + * + */ + +#define TS_FILTER_LINEAR_NCONSTANTS 7 + +/* sysfs */ + +struct ts_filter_linear; + +struct const_obj { + struct ts_filter_linear *tsfl; + struct kobject kobj; +}; + +#define to_const_obj(x) container_of(x, struct const_obj, kobj) + +struct const_attribute { + struct attribute attr; + ssize_t (*show)(struct const_obj *const, struct const_attribute *attr, + char *buf); + ssize_t (*store)(struct const_obj *const, struct const_attribute *attr, + const char *buf, size_t count); +}; + +#define to_const_attr(x) container_of(x, struct const_attribute, attr) + +/* filter configuration */ + +struct ts_filter_linear_configuration { + int constants[TS_FILTER_LINEAR_NCONSTANTS]; + int coord0; + int coord1; +}; + +/* the filter */ + +struct ts_filter_linear { + struct ts_filter tsf; + struct ts_filter_linear_configuration *config; + + int constants[TS_FILTER_LINEAR_NCONSTANTS]; + + /* sysfs */ + struct const_obj c_obj; + struct kobj_type const_ktype; + struct const_attribute kattrs[TS_FILTER_LINEAR_NCONSTANTS]; + struct attribute *attrs[TS_FILTER_LINEAR_NCONSTANTS + 1]; + char attr_names[TS_FILTER_LINEAR_NCONSTANTS][2]; +}; + +extern struct ts_filter_api ts_filter_linear_api; + +#endif
import { RequestHandler, Request, Response } from 'express'; import * as admin from 'firebase-admin'; export const isAuthenticated: RequestHandler = async (req, res, next) => { const { authorization } = req.headers; if (!authorization) { res.status(401).send({ message: 'Unauthorized' }); } else if (!authorization.startsWith('Bearer')) { res.status(401).send({ message: 'Unauthorized' }); } else { const split = authorization.split('Bearer '); if (split.length !== 2) { res.status(401).send({ message: 'Unauthorized' }); } else { const token = split[1]; try { const decodedToken: admin.auth.DecodedIdToken = await admin .auth() .verifyIdToken(token); res.locals = { ...res.locals, uid: decodedToken.uid, role: decodedToken.role, email: decodedToken.email, }; next(); } catch (err) { console.error(`${err.code} - ${err.message}`); res.status(401).send({ message: 'Unauthorized' }); } } } }; export const isAuthorized = (opts: { hasRole: Array<'admin' | 'realtor' | 'client'>; allowSameUser?: boolean; }) => (req: Request, res: Response, next: Function) => { const { role, uid } = res.locals; const { id } = req.params; if (opts.allowSameUser && id && uid === id) { next(); } else if (!role) { res.status(403).send(); } else if (opts.hasRole.includes(role)) { next(); } else { res.status(403).send(); } };
/* Copyright 1999-2013 Visualization Sciences Group, SAS Copyright 1995-2013, ZIB Berlin ALL RIGHTS RESERVED. amira(R) is a registered trademark of ZIB. amira(R) is being jointly developed by Zuse Institute Berlin and Visualization Sciences Group, SAS. Avizo® is a registered trademark of Visualization Sciences Group, SAS HardCopy, MeshViz, VolumeViz, TerrainViz are marks of Visualization Sciences Group, SAS Visualization Sciences Group, SAS is a source licensee of OpenGL®, Open Inventor® from Silicon Graphics, Inc. OpenGL® and Open Inventor® are registered trademark of Silicon Graphics, Inc. All other products and company names are trademarks or registered trademarks of their respective companies. FEI Visualization Sciences Group accepts no liability to any party for loss or damage caused by errors or omissions or by statements of any kind in this publication, whether such errors result from accident, negligence or any other cause. FEI Visualization Sciences Group assumes no liability for incidental or consequential damages arising from the use of information in this publication. FEI Visualization Sciences Group provides no warranties regarding the information contained in this publication, whether expressed, implied, or statutory, including implied warranties of merchantability or fitness for a particular purpose. FEI Visualization Sciences Group also does not assume any liability for links from this publication to publications from other companies, organizations or individuals. FEI Visualization Sciences Group does not imply endorsement of any specific company, organization or individual through offering links to this content. All information provided within this publication is subject to change at any time and is provided for informational purposes only by FEI Visualization Sciences Group. Copyright 1994-2012 by Visualization Sciences Group, SAS Merignac, France. */ /// @addtogroup hxregistration hxregistration /// @{ #ifndef REG_CUBIC_SPLINE_TRANSFORM #define REG_CUBIC_SPLINE_TRANSFORM #include <mclib/McMalloc.h> #include <hxregistration/RegSplineTransform.h> #include <hxregistration/hxregistrationAPI.h> #include <hxlandmark/HxLandmarkSet.h> /** B-spline-based local deformation. In this class, all the stuff independent * form data type of deformed objects is represented i.e. the things related * to the control grid only. */ class HXREGISTRATION_API RegCubicSplineTransform : public RegSplineTransform { public: RegCubicSplineTransform(int imgDim, bool fastMode); virtual ~RegCubicSplineTransform() { } virtual HxLandmarkSet *createControlPoints(HxLandmarkSet *controlPoints = NULL); virtual void getGridSpacing(); /// Refine transformation. virtual void refineNoInterpolants ( const int factor = 2 ); virtual void setModel( HxSpatialData *model ); /// Return bending energy of the current transformation grid. virtual double getGridEnergy( McDVector<double> &pV ) ; /** Return grid bending energy at one control point. *@param cp The control point where the bending energy is to be evaluated. */ virtual double getGridEnergy( const double *cp ) ; double getGlobalScaling() {return GlobalScaling;} /// Compute the value of a given approximating spline function. static double approxSpline ( const int k, const double t ) { switch (k) { case 0: return approxSpline0( t ); case 1: return approxSpline1( t ); case 2: return approxSpline2( t ); case 3: return approxSpline3( t ); default: return 0; } } /// Compute a value of the 0th approximating spline function. static double approxSpline0 ( const double t ) { return (( (1-t) * (1-t) * (1-t) ) / 6); }; /// Compute a value of the 1st approximating spline function. static double approxSpline1 ( const double t ) { return (( 4 + t * t * ( 3 * t - 6 ) ) / 6); }; /// Compute a value of the 2nd approximating spline function. static double approxSpline2 ( const double t ) { return (( 1 + t * (3 + t * (3 - 3*t))) / 6); }; /// Compute a value of the 3rd approximating spline function. static double approxSpline3 ( const double t ) { return (t*t*t/6); }; /// Compute the derivative of a given approximating spline function. static double derivApproxSpline ( const int k, const double t ) { switch (k) { case 0: return derivApproxSpline0( t ); case 1: return derivApproxSpline1( t ); case 2: return derivApproxSpline2( t ); case 3: return derivApproxSpline3( t ); default: return 0; } } /// Compute the derivative of the 0th approximating spline function. static double derivApproxSpline0 ( const double t ) { return (-(1-t) * (1-t) / 2); }; /// Compute derivative of the 1st approximating spline function. static double derivApproxSpline1 ( const double t ) { return (3*t*t/2-2*t); }; /// Compute derivative of the 2nd approximating spline function. static double derivApproxSpline2 ( const double t ) { return (( 1 + 2*t - 3*t*t ) / 2); }; /// Compute derivative of the 3rd approximating spline function. static double derivApproxSpline3 ( const double t ) { return (t*t/2); }; /// Compute the derivative of a given approximating spline function. static double deriv2ndApproxSpline ( const int k, const double t ) { switch (k) { case 0: return deriv2ndApproxSpline0( t ); case 1: return deriv2ndApproxSpline1( t ); case 2: return deriv2ndApproxSpline2( t ); case 3: return deriv2ndApproxSpline3( t ); default: return 0; } } /// Compute the 2nd derivative of the 0th approximating spline function. static double deriv2ndApproxSpline0 ( const double t ) { return (-t+1); }; /// Compute 2nd derivative of the 1st approximating spline function. static double deriv2ndApproxSpline1 ( const double t ) { return (3*t-2); }; /// Compute 2nd derivative of the 2nd approximating spline function. static double deriv2ndApproxSpline2 ( const double t ) { return (1-3*t); }; /// Compute 2nd derivative of the 3rd approximating spline function. static double deriv2ndApproxSpline3 ( const double t ) { return (t); }; protected: /**@name Precomputed spline coefficients, precomputed derivative spline coefficients. * @param spline Holds the precomputed spline coefficient for deforming the * voxel locations in the associated deformed grid. * @param splineDerivative Holds the precomputed derivative of the spline coefficient. * This allows for rapid evaluation of the Jacobian determinant. */ struct _TCoeff : public RegSplineTransform::TCoeff { double spline[4]; double splineDerivative[4]; double spline2ndDerivative[4]; }; /// Precomputed global scaling of initial affine transformation. double GlobalScaling; /// Relative offsets of all control points in a 4 x 4 x 4 neighbourhood. int GridPointOffset[48]; double JacobianConstraint; ///Store per voxel jacobian constraint values. McDVector<double> JacobianConstraintsCache; }; #endif /// @}
package pattern func defaultOpts() Opts { return Opts{ Attribute1: 10, Attribute2: "default", Attribute3: false, } } func WithAttribute1(n int) OptsFunc { return func(opts *Opts) { opts.Attribute1 = n } } func WithAttribute2(id string) OptsFunc { return func(opts *Opts) { opts.Attribute2 = id } } func WithAttribute3() OptsFunc { return func(o *Opts) { o.Attribute3 = true } } func NewCustomStruct(opts ...OptsFunc) *CustomStruct { o := defaultOpts() for _, fn := range opts { fn(&o) } return &CustomStruct{ Opts: o, } }
import axios from 'axios' import React, { useState } from 'react' import { useNavigate } from 'react-router-dom' import { toast } from 'react-toastify' import { Form, FormGroup, Input, Label } from 'reactstrap' import { useInfoContext } from '../../Context' import "./RegistorForm.css" export const RegistorForm = () => { const navigate = useNavigate() const {baseURL , setToken , setShow} = useInfoContext() const [signup , setSignup] = useState(false) const [data , setData] = useState({ name: "", surname: "", email: "", password: "", }) const handleInput = (e) => { setData({...data , [e.target.name] : e.target.value}) } const submitForm = async (e) => { e.preventDefault() try { toast.loading("Wait...") if(signup) { const res = await axios.post(`${baseURL}login` , data) localStorage.setItem('access_token' , res.data.token) setToken(res.data.token) setShow(true) navigate('/') toast.dismiss() toast.info(res.data.message) }else { const res = await axios.post(`${baseURL}signup` , data) localStorage.setItem('access_token' , res.data.token) setToken(res.data.token) setShow(true) navigate('/') toast.dismiss() toast.info(res.data.message) } } catch (error) { toast.dismiss() toast.error(error.response.data.message) } } return ( <div className='w-75 mx-auto registor-form'> <h1 className='my-5 mx-auto text-center text-white'> {signup ? 'Log In' : 'Sign Up'} </h1> <Form onSubmit={submitForm}> <FormGroup className={signup ? 'd-none' : 'd-block'}> <Label for="exampleName" hidden> Name </Label> <Input onChange={ handleInput } id="exampleName" name="name" placeholder="Name" type="text"/> </FormGroup> {' '} <FormGroup className={signup ? 'd-none' : 'd-block'}> <Label for="exampleSurName" hidden> SurName </Label> <Input onChange={ handleInput } id="exampleSurname" name="surname" placeholder="SurName" type="text"/> </FormGroup> {' '} <FormGroup> <Label for="exampleEmail" hidden> Email</Label> <Input onChange={ handleInput } id="exampleEmail" name="email" placeholder="Email" type="email"/> </FormGroup> {' '} <FormGroup> <Label for="examplePassword" hidden> Password </Label> <Input onChange={ handleInput } id="examplePassword" name="password" placeholder="Password" type="password" /> </FormGroup> {' '} <span onClick={()=> setSignup(!signup)} className='text-white my-3 fw-bold d-block link-info sasha'> {signup ? "I don't have account!" : 'I already have account!'} </span> <button className='bg-primary btn text-white fw-bold'> {signup ? 'Log In' : 'Sign Up'} </button> </Form> </div> ) }
using Moq; using OnlineLibary.Modules.Catalog.Application.Users.UnblockReader; using OnlineLibrary.Modules.Catalog.Domain.LibraryUser.UserSubscription; namespace OnlineLibrary.Modules.Catalog.Application.UnitTest { [TestFixture] public class UnblockReaderCommandHandlerTests { [Test] public void Constructor_WithValidArguments_CreatesInstance() { //Arrange var username = "username"; //Act var command = new UnblockReaderCommand(username); //Assert Assert.That(command.UserName, Is.EqualTo(username)); } [Test] public async Task Handle_ValidCommand_ReturnsSuccessResult() { //Arrange var username = "username"; Reader reader = new Reader { UserName = username, IsBlocked = true }; var readerRepository = new Mock<IReaderRepository>(); readerRepository.Setup(x=>x.GetByUsername(username)).ReturnsAsync(reader); var command = new UnblockReaderCommand(username); var handler = new UnblockReaderCommandHandler(readerRepository.Object); //Act var result = await handler.Handle(command, CancellationToken.None); //Assert Assert.IsTrue(result.IsSuccess); } [Test] public async Task Handle_UserDoesNotExist_ReturnsFailureResult() { //Arrange var username = "username"; var readerRepository = new Mock<IReaderRepository>(); readerRepository.Setup(x => x.GetByUsername(username)).Returns(Task.FromResult<Reader>(null)); var command = new UnblockReaderCommand(username); var handler = new UnblockReaderCommandHandler(readerRepository.Object); //Act var result = await handler.Handle(command, CancellationToken.None); //Assert Assert.IsFalse(result.IsSuccess); Assert.That(result.ErrorMessage, Is.EqualTo("User does not exist.")); } [Test] public async Task Handle_UserAlreadyUnblocked_ReturnsFailureResult() { //Arrange var username = "username"; Reader reader = new Reader { UserName = username, IsBlocked = false }; var readerRepository = new Mock<IReaderRepository>(); readerRepository.Setup(x => x.GetByUsername(username)).ReturnsAsync(reader); var command = new UnblockReaderCommand(username); var handler = new UnblockReaderCommandHandler(readerRepository.Object); //Act var result = await handler.Handle(command, CancellationToken.None); //Assert Assert.IsFalse(result.IsSuccess); Assert.That(result.ErrorMessage, Is.EqualTo("User is already unblocked.")); } } }
import { useState } from "react"; import { Input, Button } from "antd"; import MyComponent from "./MyComponent"; const Section3 = () => { const [myComponentValue, setMyComponentValue] = useState(""); const [value2, setValue2] = useState(""); const [childrenValue, setchildrenValue] = useState(""); const [value4, setValue4] = useState(""); const sendProps = () => { setValue2(myComponentValue); setMyComponentValue(""); }; const sendChildren = () => { setValue4(childrenValue); setchildrenValue(""); }; return ( <> <div className="py-3 pl-4"> <div className="py-2"> <h3 className="text-lg font-semibold"> 2. 컴포넌트를 사용할 때 props 값 지정하기 </h3> <div className="pl-4"> <div className="my-2 w-[400px]"> <Input placeholder="컴포넌트로 전달할 값을 입력하세요." suffix={ <Button onClick={sendProps}>입력</Button> } onChange={(e) => setMyComponentValue(e.target.value) } value={myComponentValue} /> </div> <div className="my-2"> <MyComponent value={value2} /> </div> </div> </div> <div className="py-2"> <h3 className="text-lg font-semibold"> 3. props 기본값 설정: defaultProps </h3> <div className="pl-4"> <div className="my-2"> <MyComponent /> </div> </div> </div> <div className="py-2"> <h3 className="text-lg font-semibold"> 4. 태그 사이의 내용을 보여주는 children </h3> <div className="pl-4"> <div className="my-2 w-[400px]"> <Input placeholder="태그사이에 들어갈 값을 입력하세요." suffix={ <Button onClick={sendChildren}>입력</Button> } onChange={(e) => setchildrenValue(e.target.value) } value={childrenValue} /> </div> <div className="my-2"> <MyComponent>{value4}</MyComponent> </div> </div> </div> </div> </> ); }; export default Section3;
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class NfcNativeSample extends StatefulWidget { const NfcNativeSample({super.key}); @override State<NfcNativeSample> createState() => _NfcNativeSampleState(); } class _NfcNativeSampleState extends State<NfcNativeSample> { static const platform = MethodChannel('samples.flutter.dev/nfc'); static const platformEvent = EventChannel('samples.flutter.dev/nfcevent'); late StreamSubscription<dynamic> _eventSubscription; dynamic res = 'NOT STARTED'; Future<void> checkNfc() async { try { final result = await platform.invokeMethod<bool>('isNfcAvailable'); setState(() { res = 'NFC IS ON : $result'; }); } catch (e) { setState(() { res = 'FAILED $e'; }); } } Future<void> initNfc() async { try { final result = await platform.invokeMethod( 'initNfc', { 'permanentApduResponses': true, 'listenOnlyConfiguredPorts': false, //D4100000030001 티머니 aid 'aid': Uint8List.fromList([0xD4, 0x10, 0x00, 0x00, 0x03, 0x00, 0x01]), 'cla': null, 'ins': null, }, ); setState(() { res = 'NFC INIT : $result'; }); } catch (e) { setState(() { res = 'FAILE TO INIT : $e'; }); } } Future<void> addRes() async { try { final result = await platform.invokeMethod( 'addRes', { 'port': 0, 'data': Uint8List.fromList([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]), }, ); setState(() { res = 'NFC RES ADDED : $result'; }); } catch (e) { setState(() { res = 'FAILED TO ADD NFC RES : $e'; }); } } Future<void> removeRes() async { try { final result = await platform.invokeMethod( 'removeRes', {'port': 0}, ); setState(() { res = 'NFC RES REMOVED : $result'; }); } catch (e) { setState(() { res = 'FAILED TO REMOVE NFC RES : $e'; }); } } @override void initState() { super.initState(); _eventSubscription = platformEvent.receiveBroadcastStream().listen((event) { print(event); }); } @override void dispose() { _eventSubscription.cancel(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('NFC Native'), ), body: Column( children: [ ElevatedButton( onPressed: checkNfc, child: const Text('Check NFC Availability'), ), ElevatedButton( onPressed: initNfc, child: const Text('init NFC'), ), ElevatedButton( onPressed: addRes, child: const Text('ADD NFC RES'), ), ElevatedButton( onPressed: removeRes, child: const Text('remove NFC res'), ), Text(res), ], ), ); } }
import { Injectable } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; import { ethers } from 'ethers'; import { ConfigService } from '@nestjs/config'; import { BlockDto } from './dto'; import { PrismaClientKnownRequestError } from '@prisma/client/runtime/library'; @Injectable() export class BlockService { constructor( private prisma: PrismaService, private config: ConfigService, ) {} INFURA_API = this.config.get('INFURA_API'); network = 'mainnet'; provider = new ethers.InfuraProvider(this.network, this.INFURA_API); // 최신 블럭 넘버 조회 async getRecentBlockNumber() { return this.provider.getBlockNumber(); } // (blockName | blockNumber | blockHash ) 기준으로 블럭 정보 조회 & 데이터베이스에 저장 async retrieveEthersBlockData(dto: BlockDto) { const blockInfo = await this.provider.getBlock(dto.blockHash); const blockData = { hash: blockInfo.hash, parentHash: blockInfo.parentHash, number: blockInfo.number, timestamp: BigInt(blockInfo.timestamp), nonce: blockInfo.nonce, difficulty: blockInfo.difficulty, gasLimit: BigInt(blockInfo.gasLimit), gasUsed: BigInt(blockInfo.gasUsed), miner: blockInfo.miner, extraData: blockInfo.extraData, }; try { await this.saveBlockData(blockData); await this.saveTransactionReceiptData(blockInfo); } catch (error) { if (error instanceof PrismaClientKnownRequestError) { if (error.code === 'P2002') { } } } return JSON.stringify(blockInfo, null, 4); } // 블럭 정보 저장 async saveBlockData(blockData) { await this.prisma.block.create({ data: { ...blockData, }, }); } // 블럭 내에 있는 Transaction Receipt 데이터 저장 async saveTransactionReceiptData(blockInfo) { const transactionHashes = blockInfo.transactions; transactionHashes.forEach(async (transactionHash, _, __) => { const transactionReceipt = await this.provider.getTransactionReceipt(transactionHash); const transactionReceiptData = { transactionHash: transactionReceipt.hash, blockHash: transactionReceipt.blockHash, blockNumber: transactionReceipt.blockNumber, to: transactionReceipt.to, from: transactionReceipt.from, contractAddress: transactionReceipt.contractAddress, transactionIndex: transactionReceipt.index, gasUsed: transactionReceipt.gasUsed, logsBloom: transactionReceipt.logsBloom, cumulativeGasUsed: transactionReceipt.cumulativeGasUsed, status: transactionReceipt.status, }; await this.prisma.transactionReceipt.create({ data: { ...transactionReceiptData, }, }); // Transaction Receipt 내에 있는 Logs 저장 this.saveTransactionReceiptLogs(transactionReceipt); }); } // Logs 저장 async saveTransactionReceiptLogs(transactionReceipt) { const logs = transactionReceipt.logs; for (const log of logs) { const logData = { transactionHash: log.transactionHash, blockHash: log.blockHash, blockNumber: log.blockNumber, address: log.address, data: log.data, topics: log.topics, transactionIndex: log.transactionIndex, logIndex: log.index, removed: log.removed, }; await this.prisma.log.create({ data: { ...logData, }, }); } } // 블럭해시 기준으로 블럭 조회 (TransactionReceipt, Log 포함) async getBlockData(blockHash: string) { const blockData = await this.prisma.block.findUnique({ where: { hash: blockHash, }, include: { TransactionReceipt: { include: { Log: true, }, }, }, }); return blockData; } }
#ifndef ABSTRACT_OBJECT_H #define ABSTRACT_OBJECT_H #include <QGraphicsPixmapItem> #include <QTransform> #include <QPixmap> class AbstractObject : public QGraphicsPixmapItem { public: AbstractObject(QPixmap *pm, double nx, double ny, double w, double h, int hp); virtual void setX(int x); virtual void setY(int y); virtual void setVelX(int vx); virtual void setVelY(int vy); virtual void setHealth(int h); virtual void setRot(int r); virtual void setDir(int d); int getDir(); int getX(); int getY(); int getWidth(); int getHeight(); int getVelX(); int getVelY(); virtual void setBin(bool b); bool getBin(); int getHealth(); int getRot(); /** Object will rotate towards @param x, @param y */ virtual void face(int sx, int sy); virtual void move(int windowMaxX, int windowMaxY); virtual void moveUp(double s); virtual void moveDown(double s); virtual void moveLeft(double s); virtual void moveRight(double s); protected: int x; int y; int width; int height; int velX; int velY; int health; int dir; /** For displaying a binary number */ bool bin; /** Stores the rotation */ int rot; QPixmap *pixMap; QTransform rotate; }; #endif
# Use Naive bayes, K-nearest, and Decision tree classification algorithms and build classifiers. # Divide the data set into training and test set. Compare the accuracy of the different classifiers # under the following situations: # 5.1 a) Training set = 75% Test set = 25% b) Training set = 66.6% (2/3rd of total), Test set = # 33.3% # 5.2 Training set is chosen by i) hold out method ii) Random subsampling iii) Cross-Validation. # Compare the accuracy of the classifiers obtained. # 5.3 Data is scaled to standard format. import pandas as pd from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import accuracy_score from sklearn.preprocessing import StandardScaler import matplotlib.pyplot as plt import statistics from sklearn.model_selection import StratifiedKFold from sklearn.naive_bayes import GaussianNB from sklearn.neighbors import KNeighborsClassifier def get_Score(model,X_train,Y_train,X_test,Y_test): model.fit(X_train,Y_train) return model.score(X_test,Y_test)*100 scale = StandardScaler() data = pd.read_csv('./abalone_csv.csv') X=data[0:].values[:,1:] Y=data[0:].values[:,0] Xval=["Hold-Out","Random Sub-Sampling","Cross-Validation"] # Decision Tree Classifier # 5.1 # Training Size:75% and Test Size:25% print("Decision Tree Classifier") X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.25,random_state=1000) X_train = scale.fit_transform(X_train) X_test = scale.fit_transform(X_test) clf=DecisionTreeClassifier() clf.fit(X_train,Y_train) print(f"Accuracy is {get_Score(clf,X_train,Y_train,X_test,Y_test)} with 75% of training data") # Training Size:66.6% and Test Size:33.3% X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.333,random_state=1000) X_train = scale.fit_transform(X_train) X_test = scale.fit_transform(X_test) clf.fit(X_train,Y_train) print(f"Accuracy is {get_Score(clf,X_train,Y_train,X_test,Y_test)} with 66.6% of training data") # 5.2 # Using Hold-Out method for splitting Accuracy = [] X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.2,random_state=1000) X_train = scale.fit_transform(X_train) X_test = scale.fit_transform(X_test) clf.fit(X_train,Y_train) Accuracy.append(get_Score(clf,X_train,Y_train,X_test,Y_test)) # using Random Subsampling for splitting Accuracy_Random=[] k=6 for i in range(0,k): X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.2,random_state=100) X_train = scale.fit_transform(X_train) X_test = scale.fit_transform(X_test) clf.fit(X_train,Y_train) prediction = clf.predict(X_test) Accuracy_Random.append(accuracy_score(Y_test,prediction)*100) Accuracy.append(statistics.mean(Accuracy_Random)) # using K-Cross-Validation for splitting k=9 kf = StratifiedKFold(n_splits=k) Accuracy_kFold=[] for train_index,test_index in kf.split(X,Y): X_train,X_test,Y_train,Y_test = X[train_index],X[test_index],Y[train_index],Y[test_index] X_train = scale.fit_transform(X_train) X_test = scale.fit_transform(X_test) Accuracy_kFold.append(get_Score(DecisionTreeClassifier(),X_train,Y_train,X_test,Y_test)) Accuracy.append(statistics.mean(Accuracy_kFold)) print("Accuracy: ",Accuracy) # Visualizing the accuracy of the Decision Tree Model for different Splitting models Yval = Accuracy plt.bar(Xval,Yval,color="green",width=0.2) plt.xlabel("Splitting Method") plt.title("Decision Tree Classifier Visualization") plt.show() # Naive Bayes Classifier NBclf = GaussianNB() print("Naive-Bayes Classifier") # Training Size:75% and Test Size:25% X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.25,random_state=1000) X_train = scale.fit_transform(X_train) X_test = scale.fit_transform(X_test) print(f"Accuracy is {get_Score(NBclf,X_train,Y_train,X_test,Y_test)} with 75% of Training Data") # Training Size:66.6% and Test Size:33.3% X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.333,random_state=1000) X_train = scale.fit_transform(X_train) X_test = scale.fit_transform(X_test) print(f"Accuracy is {get_Score(NBclf,X_train,Y_train,X_test,Y_test)} with 66.6% of Training Data") # 5.2 # Using Hold-Out method for splitting Accuracy = [] X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.2,random_state=1000,shuffle=True,stratify=Y) X_train = scale.fit_transform(X_train) X_test = scale.fit_transform(X_test) Accuracy.append(get_Score(NBclf,X_train,Y_train,X_test,Y_test)) # using Random Subsampling for splitting Accuracy_Random=[] k=6 for i in range(0,k): X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.2,random_state=1000,shuffle=True,stratify=Y) X_train = scale.fit_transform(X_train) X_test = scale.fit_transform(X_test) Accuracy_Random.append(get_Score(NBclf,X_train,Y_train,X_test,Y_test)) Accuracy.append(statistics.mean(Accuracy_Random)) # using K-Cross-Validation for splitting k=9 kf = StratifiedKFold(n_splits=k) Accuracy_kFold=[] for train_index,test_index in kf.split(X,Y): X_train,X_test,Y_train,Y_test = X[train_index],X[test_index],Y[train_index],Y[test_index] X_train = scale.fit_transform(X_train) X_test = scale.fit_transform(X_test) Accuracy_kFold.append(get_Score(NBclf,X_train,Y_train,X_test,Y_test)) Accuracy.append(statistics.mean(Accuracy_kFold)) print("Accuracy: ",Accuracy) # Visualizing the accuracy of the Naive-Bayes Classifier Model for different Splitting models Yval = Accuracy plt.bar(Xval,Yval,color="green",width=0.2) plt.xlabel("Splitting Method") plt.title("Naive Bayes Classifier Visualization") plt.show() # K-Nearest Neighbour Classifier knn = KNeighborsClassifier(n_neighbors=8) print("K-Nearest Neighbour") # Training Size:75% and Test Size:25% X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.25,random_state=1000) X_train = scale.fit_transform(X_train) X_test = scale.fit_transform(X_test) print(f"Accuracy is {get_Score(knn,X_train,Y_train,X_test,Y_test)} with 75% of Training Data") # Training Size:66.6% and Test Size:33.3% X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.333,random_state=1000) X_train = scale.fit_transform(X_train) X_test = scale.fit_transform(X_test) print(f"Accuracy is {get_Score(knn,X_train,Y_train,X_test,Y_test)} with 66.6% of Training Data") # 5.2 # Using Hold-Out method for splitting Accuracy = [] X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.2,random_state=1000,shuffle=True,stratify=Y) X_train = scale.fit_transform(X_train) X_test = scale.fit_transform(X_test) Accuracy.append(get_Score(knn,X_train,Y_train,X_test,Y_test)) # using Random Subsampling for splitting Accuracy_Random=[] k=6 for i in range(0,k): X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.2,random_state=1000,shuffle=True,stratify=Y) X_train = scale.fit_transform(X_train) X_test = scale.fit_transform(X_test) Accuracy_Random.append(get_Score(knn,X_train,Y_train,X_test,Y_test)) Accuracy.append(statistics.mean(Accuracy_Random)) # using K-Cross-Validation for splitting k=9 kf = StratifiedKFold(n_splits=k) Accuracy_kFold=[] for train_index,test_index in kf.split(X,Y): X_train,X_test,Y_train,Y_test = X[train_index],X[test_index],Y[train_index],Y[test_index] X_train = scale.fit_transform(X_train) X_test = scale.fit_transform(X_test) Accuracy_kFold.append(get_Score(knn,X_train,Y_train,X_test,Y_test)) Accuracy.append(statistics.mean(Accuracy_kFold)) print("Accuracy: ",Accuracy) # Visualizing the accuracy of the K-Nearest Neighbour Model for different Splitting models Yval = Accuracy plt.bar(Xval,Yval,color="green",width=0.2) plt.xlabel("Splitting Method") plt.title("K-Nearest Neighbor Classifier Visualization") plt.show()
import { AnyAction, createSlice, PayloadAction } from '@reduxjs/toolkit' import { IUser } from 'types/index.types' import { login, verify } from './user.actions' import { AxiosError } from 'axios' import { IVerifyResponse } from 'types/auth.types' import { removeTokensCookie } from 'services/auth/Auth.helper' interface IInitialState { user: IUser | null error: AxiosError | null isLoading: boolean isError: boolean isAuth: boolean } const initialState: IInitialState = { user: null, isLoading: false, isError: false, error: null, isAuth: false } export const UserSlice = createSlice({ name: 'user', initialState, reducers: { logout: (state) => { state.error = null state.isLoading = false state.isError = false state.user = null state.isAuth = false removeTokensCookie() } }, extraReducers: (builder) => { builder.addCase(verify.fulfilled, (state, { payload }: PayloadAction<IVerifyResponse>) => { state.isLoading = false state.user = payload state.isAuth = true state.isError = false state.error = null }) builder.addCase( verify.rejected, (state, { payload }: PayloadAction<AxiosError | undefined>) => { if (payload) { state.error = payload state.isLoading = false state.isError = true state.user = null state.isAuth = false } } ) builder.addCase(login.rejected, (state, { payload }: PayloadAction<AxiosError | undefined>) => { if (payload) { state.error = payload state.isLoading = false state.isError = true state.user = null state.isAuth = false } }) builder.addMatcher(isLoadingAction, (state) => { state.isLoading = true }) } }) function isLoadingAction(action: AnyAction) { return action.type.endsWith('pending') } export const { logout } = UserSlice.actions export default UserSlice.reducer
import unittest import mock from mining_simulator.coordinator import MiningCoordinator from mining_simulator.mining_site import MiningSite from mining_simulator.mining_truck import MiningTruck from mining_simulator.unloading_station import UnloadStation class TestMiningStation(unittest.TestCase): def setUp(self): self.coordinator = MiningCoordinator(num_trucks=1, num_stations=2) def test_instances(self): self.assertTrue(len(self.coordinator.mining_sites) == 1) self.assertTrue(len(self.coordinator.trucks) == 1) self.assertTrue(len(self.coordinator.unloading_stations) == 2) self.assertTrue(isinstance(self.coordinator.mining_sites[0], MiningSite)) self.assertTrue(isinstance(self.coordinator.trucks[0], MiningTruck)) self.assertTrue( isinstance(self.coordinator.unloading_stations[0], UnloadStation) ) @mock.patch.object(MiningSite, "add_truck_to_queue") def test_add_truck_to_mine(self, mock_site: mock.Mock): truck = self.coordinator.trucks[0] truck.timer = 5 truck.current_action = truck.Actions.TRAVEL_TO_MINE self.coordinator.time_step() mock_site.assert_not_called() truck.timer = 0 self.coordinator.time_step() mock_site.assert_called() @mock.patch.object(UnloadStation, "add_truck_to_queue") def test_add_truck_to_unloading_site(self, mock_site: mock.Mock): truck = self.coordinator.trucks[0] truck.timer = 5 truck.current_action = truck.Actions.TRAVEL_TO_UNLOAD self.coordinator.time_step() mock_site.assert_not_called() truck.timer = 0 self.coordinator.time_step() mock_site.assert_called() @mock.patch.object(MiningTruck, "take_action") @mock.patch.object(MiningSite, "manage_queue") @mock.patch.object(UnloadStation, "manage_queue") def test_time_step( self, mock_unload_queue: mock.Mock, mock_mine_queue: mock.Mock, mock_action: mock.Mock, ): self.coordinator.time_step() self.assertTrue(mock_unload_queue.call_count == 2) self.assertTrue(mock_mine_queue.call_count == 1) self.assertTrue(mock_action.call_count == 1)
<script lang="ts"> import { HouseType } from 'src/graphql/@types/types'; import { defineComponent, computed, ref } from 'vue'; import useHouseType from './houseTypeService'; import { useMutation } from '@vue/apollo-composable'; import { deleteHouseTypeMutation, listHouseTypeQuery, createHouseTypeMutation, updateHouseTypeMutation, } from 'src/graphql/query/house.graphql'; import { error, success, beforeRemove } from 'src/helpers/notification'; const columns = [ { name: 'name', label: 'Name', field: 'name', align: 'left', }, { name: 'icon', label: '', field: '', align: 'right' }, ]; export default defineComponent({ setup() { let { list, items, item } = useHouseType(); let { loading: loadinglist } = list(); const { mutate: deleteHouseType, onError, onDone } = useMutation( deleteHouseTypeMutation, () => ({ update: ( cache, { data: { deleteHouseType: { houseType: { id }, }, }, } ) => { let data: Record<string, []> | null = cache.readQuery({ query: listHouseTypeQuery, }); if (data) { items.value = data.houseTypes.filter( (i: { id: string }) => i.id != id ); cache.writeQuery({ query: listHouseTypeQuery, data: { houseTypes: items.value, }, }); } }, }) ); onError((e: Error) => { error(e); }); onDone(() => { success({ message: 'The item have been deleted.' }); }); const { mutate: createHouseType, loading: loadingCreate, onError: onErrorCreate, onDone: onDoneCreate, } = useMutation(createHouseTypeMutation, () => ({ update: ( cache, { data: { createHouseType: { houseType }, }, } ) => { const value: unknown = { ...houseType, ...item.value }; const data: { houseTypes: Partial<HouseType>[]; } | null = cache.readQuery({ query: listHouseTypeQuery, }); cache.writeQuery({ query: listHouseTypeQuery, data: { houseTypes: [...(data?.houseTypes || []), value], }, }); }, })); onErrorCreate((e: Error) => { error(e); }); onDoneCreate(() => { item.value = {}; formRef.value.resetValidation(); }); const { mutate: updateHouseType, onError: onErrorUpdate, onDone: onDoneUpdate, loading: loadingUpdate, } = useMutation(updateHouseTypeMutation, () => ({ update: (cache) => { const data: Record<string, HouseType[]> | null = cache.readQuery({ query: listHouseTypeQuery, }); if (data) items.value = data.houseTypes; }, })); onErrorUpdate((e: Error) => { error(e); }); onDoneUpdate(() => { item.value = {}; formRef.value.resetValidation(); }); const formRef = ref<Record<string, () => void>>({}); return { items, item, columns, deleteHouseType, loading: computed( () => loadinglist.value || loadingCreate.value || loadingUpdate ), formRef, onSubmit() { if (typeof item.value.id == 'undefined') void createHouseType({ input: item.value }); else { const value = Object.assign({}, item.value) as HouseType; delete value.__typename; void updateHouseType({ input: value }); } }, edit(data: HouseType) { item.value = Object.assign({}, data); }, remove(data: HouseType) { beforeRemove().onOk(() => { void deleteHouseType({ input: { id: data.id } }); }); }, }; }, }); </script> <template> <q-page padding> <BaseTable title="House Types" :columns="columns" :rows="items" :loading="loading" :rows-per-page-options="[0]" hide-pagination > <template v-slot:top> <label class="text-h6">Houses Type</label> <q-space /> <q-form @submit="onSubmit" ref="formRef"> <div class="tw-flex tw-justify-items-end tw-items-center tw-w-full tw-mt-5 sm:tw-mt-0 sm:tw-w-auto" > <BaseInput label="Name" v-model="item.name" clearable class="tw-w-full sm:tw-w-auto tw-mr-2" validate ></BaseInput> <div> <BaseButton :loading="loading" round color="primary" icon="add" type="submit" /> </div> </div> </q-form> </template> <template v-slot:body="props"> <q-tr :props="props"> <q-td key="name" :props="props">{{ props.row.name }}</q-td> <q-td key="icon" :props="props"> <q-icon class="q-mr-sm" name="edit" color="teal" style="font-size: 20px; cursor: pointer;" @click="edit(props.row)" /> <q-icon name="delete" color="negative" style="font-size: 20px; cursor: pointer;" @click="remove(props.row)" /> </q-td> </q-tr> </template> </BaseTable> </q-page> </template>
#include "stdafx.h" #include "..\Public\MonsterAxe.h" #include "GameInstance.h" #include "Trail_Obj.h" CMonsterAxe::CMonsterAxe(ID3D11Device * pDevice, ID3D11DeviceContext * pContext) : CWeapon(pDevice, pContext) { } CMonsterAxe::CMonsterAxe(const CMonsterAxe & rhs) : CWeapon(rhs) { } HRESULT CMonsterAxe::Initialize_Prototype() { return S_OK; } HRESULT CMonsterAxe::Initialize(void * pArg) { if (FAILED(Ready_Components())) return E_FAIL; m_pTransformCom->Set_Scale(XMVectorSet(0.01f, 0.01f, 0.01f, 1.f)); m_pTransformCom->Rotation(XMVectorSet(1.f, 0.f, 0.f, 0.f), XMConvertToRadians(-90.0f)); m_pTransformCom->Set_State(CTransform::STATE_POSITION, XMVectorSet(-0.7f, 0.f, 0.f, 1.f)); return S_OK; } void CMonsterAxe::Tick(_float fTimeDelta) { if (m_bColliderOn) m_pColliderCom->Update(m_pTransformCom->Get_WorldMatrix() * m_pParentTransformCom->Get_WorldMatrix()); } void CMonsterAxe::Tick(_float fTimeDelta, CGameObject * _pUser) { m_pTrailCom->Tick(fTimeDelta, m_pTransformCom->Get_WorldMatrix() * m_pParentTransformCom->Get_WorldMatrix()); if (m_bColliderOn) { m_pColliderCom->Update(m_pTransformCom->Get_WorldMatrix() * m_pParentTransformCom->Get_WorldMatrix()); CCollisionMgr::Get_Instance()->Add_CollisoinList(CCollisionMgr::TYPE_MONSTER_WEAPON, m_pColliderCom, _pUser); } } void CMonsterAxe::LateTick(_float fTimeDelta) { if (nullptr == m_pRendererCom) return; } HRESULT CMonsterAxe::Render() { if (nullptr == m_pModelCom || nullptr == m_pShaderCom) return E_FAIL; CGameInstance* pGameInstance = GET_INSTANCE(CGameInstance); _float4x4 WorldMatrix; XMStoreFloat4x4(&WorldMatrix, XMMatrixTranspose(m_pTransformCom->Get_WorldMatrix() * m_pParentTransformCom->Get_WorldMatrix())); if (FAILED(m_pShaderCom->Set_RawValue("g_WorldMatrix", &WorldMatrix, sizeof(_float4x4)))) return E_FAIL; if (FAILED(m_pShaderCom->Set_RawValue("g_ViewMatrix", &pGameInstance->Get_TransformFloat4x4_TP(CPipeLine::D3DTS_VIEW), sizeof(_float4x4)))) return E_FAIL; if (FAILED(m_pShaderCom->Set_RawValue("g_ProjMatrix", &pGameInstance->Get_TransformFloat4x4_TP(CPipeLine::D3DTS_PROJ), sizeof(_float4x4)))) return E_FAIL; if (FAILED(m_pShaderCom->Set_RawValue("g_CamPosition", &pGameInstance->Get_CamPosition(), sizeof(_float4)))) return E_FAIL; RELEASE_INSTANCE(CGameInstance); _uint iNumMeshes = m_pModelCom->Get_NumMesh(); for (_uint i = 0; i < iNumMeshes; ++i) { if (FAILED(m_pModelCom->SetUp_OnShader(m_pShaderCom, m_pModelCom->Get_MaterialIndex(i), aiTextureType_DIFFUSE, "g_DiffuseTexture"))) return E_FAIL; if (FAILED(m_pModelCom->SetUp_OnShader(m_pShaderCom, m_pModelCom->Get_MaterialIndex(i), aiTextureType_NORMALS, "g_NormalTexture"))) return E_FAIL; if (FAILED(m_pShaderCom->Begin(0))) return E_FAIL; if (FAILED(m_pModelCom->Render(i))) return E_FAIL; } #ifdef _DEBUG //if (nullptr != m_pColliderCom && m_bColliderOn) //m_pColliderCom->Render(); #endif return S_OK; } HRESULT CMonsterAxe::Ready_Components() { /* For.Com_Transform */ CTransform::TRANSFORMDESC _Desc; _Desc.fRotationPerSec = XMConvertToRadians(90.f); //_Desc.fSpeedPerSec = 1.5f; _Desc.fSpeedPerSec = 2.5f; if (FAILED(__super::Add_Component(LEVEL_STATIC, TEXT("Prototype_Component_Transform"), TEXT("Com_Transform"), (CComponent**)&m_pTransformCom, &_Desc))) return E_FAIL; /* For.Com_ParentTransform */ if (FAILED(__super::Add_Component(LEVEL_STATIC, TEXT("Prototype_Component_Transform"), TEXT("Com_ParentTransform"), (CComponent**)&m_pParentTransformCom))) return E_FAIL; /* For.Com_Trail */ CTrail::TRAILINFO _tInfo; //_tInfo._Color = CLIENT_RGB(255, 155, 155); _tInfo._Color = CLIENT_RGB(255, 255, 255); _tInfo._HighAndLow.vHigh = _float3(115.0f, 0.f, 0.f); _tInfo._HighAndLow.vLow = _float3(15.f, 0.f, 0.f); _tInfo._eOption = CTrail::TRAILOPTION_DEFAULT; AUTOINSTANCE(CGameInstance, _pInstance); m_pTrailCom = static_cast<CTrail_Obj*>(_pInstance->Clone_GameObject(TEXT("Prototype_GameObject_Trail"), &_tInfo)); if (m_pTrailCom == nullptr) return E_FAIL; /* For.Com_Renderer */ if (FAILED(__super::Add_Component(LEVEL_STATIC, TEXT("Prototype_Component_Renderer"), TEXT("Com_Renderer"), (CComponent**)&m_pRendererCom))) return E_FAIL; /* For.Com_Shader */ if (FAILED(__super::Add_Component(LEVEL_GAMEPLAY, TEXT("Prototype_Component_Shader_Model"), TEXT("Com_Shader"), (CComponent**)&m_pShaderCom))) return E_FAIL; /* For.Com_Model */ if (FAILED(__super::Add_Component(LEVEL_STAGE_02_1, TEXT("Prototype_Component_Model_Monster_Weapon_Axe"), TEXT("Com_Model"), (CComponent**)&m_pModelCom))) return E_FAIL; /* For.Com_OBB */ CCollider::COLLIDERDESC ColliderDesc; ZeroMemory(&ColliderDesc, sizeof(CCollider::COLLIDERDESC)); ColliderDesc.vSize = _float3(80.0f, 50.f, 20.f); ColliderDesc.vCenter = _float3(65.f, ColliderDesc.vSize.y * 0.5f - 30.f, 0.f); ColliderDesc.vRotation = _float3(0.f, XMConvertToRadians(0.f), 0.f); if (FAILED(__super::Add_Component(LEVEL_GAMEPLAY, TEXT("Prototype_Component_Collider_OBB"), TEXT("Com_OBB"), (CComponent**)&m_pColliderCom, &ColliderDesc))) return E_FAIL; return S_OK; } CMonsterAxe * CMonsterAxe::Create(ID3D11Device * pDevice, ID3D11DeviceContext * pContext) { CMonsterAxe* pInstance = new CMonsterAxe(pDevice, pContext); if (FAILED(pInstance->Initialize_Prototype())) { MSG_BOX(TEXT("Failed To Created : CMonsterAxe")); Safe_Release(pInstance); } return pInstance; } CGameObject * CMonsterAxe::Clone(void * pArg) { CMonsterAxe* pInstance = new CMonsterAxe(*this); if (FAILED(pInstance->Initialize(pArg))) { MSG_BOX(TEXT("Failed To Cloned : CMonster")); Safe_Release(pInstance); } return pInstance; } void CMonsterAxe::Free() { __super::Free(); }
import sys import pandas as pd from sklearn.feature_selection import SelectKBest, f_classif, mutual_info_classif from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, BaggingClassifier from sklearn.naive_bayes import GaussianNB from sklearn.tree import DecisionTreeClassifier from sklearn.linear_model import LogisticRegression from sklearn.svm import SVC from sklearn.neural_network import MLPClassifier from sklearn.model_selection import StratifiedKFold, cross_validate from sklearn.metrics import make_scorer, accuracy_score, cohen_kappa_score, mean_absolute_error, mean_squared_error import numpy as np import os from joblib import dump, load from pyAgrum.skbn import BNClassifier kfile = '/home/nyuad/Capstone/Scikit/Optimal k/' def print_and_save_evaluation_results(results, model_info, filename): with open(filename, 'w') as f: f.write(model_info + '\n\n') print(model_info + '\n') for key, value in results.items(): if "Instances" in key: line = "{}: {}".format(key, int(value)) else: line = "{}: {:.4f}".format(key, value) if isinstance(value, float) else "{}: {}".format(key, value) print(line) f.write(line + '\n') if len(sys.argv) < 4: print("Usage: python3 feature_selection_training.py -s [F/M/N/feature_subset_filename] -t [RF/NB/DT/LR/SVM/model_filename] -k [number of top features to select (optional, only for F or M)]") sys.exit(1) # Load data data = pd.read_csv("master_otu.tsv", sep="\t") X = data.drop(columns=['sra_name', 'Class']) y = data['Class'] # Feature selection k_range = None if '-k' in sys.argv: k_index = sys.argv.index('-k') + 1 if k_index < len(sys.argv): k_values = sys.argv[k_index].split(':') if len(k_values) == 2 and all(val.isdigit() for val in k_values): k_range = range(int(k_values[0]), int(k_values[1]) + 1) else: print("Invalid value for -k. Please provide a range in the format start:end.") sys.exit(1) else: print("Invalid value for -k. Please provide a range in the format start:end.") sys.exit(1) feature_subset_loaded = False if sys.argv[1] == "-s": if sys.argv[2] in ["F", "M", "N"]: if k_range is None and sys.argv[2] in ["F", "M"]: print("You must provide a value for -k when using feature selection methods 'F' or 'M'.") sys.exit(1) if sys.argv[2] == "N": X_new = X k_range = [X.shape[1]] feature_selection_method = "Baseline" elif os.path.isfile(sys.argv[2]): if k_range is not None: print("You cannot provide a value for -k when loading a feature subset file.") sys.exit(1) if sys.argv[2].endswith('_selected_features.npy'): # Load feature subset X_new = np.load(sys.argv[2]) k_range = [X_new.shape[1]] feature_selection_method = "Loaded Feature Subset" feature_subset_loaded = True print(f"Feature subset loaded from {sys.argv[2]}") else: print("Invalid feature subset file provided.") sys.exit(1) else: print("Invalid feature selection method or file. Use 'F' for ANOVA F-value based, 'M' for Mutual Information based, 'N' for no feature selection, or provide a valid feature subset filename.") sys.exit(1) else: print("Invalid argument for feature selection. Please use '-s'.") sys.exit(1) # Classifier training, evaluation, and saving/loading if sys.argv[3] == "-t": if sys.argv[4] in ["RF", "NB", "DT", "LR", "SVM", "AdaBoost_RF", "Bagging_RF", "Bagging_NB", "MLP", "BN"]: if sys.argv[4] == "RF": clf = RandomForestClassifier(n_estimators=100, random_state=1) classifier_name = "Random Forest" elif sys.argv[4] == "NB": clf = GaussianNB() classifier_name = "Naive Bayes" elif sys.argv[4] == "DT": clf = DecisionTreeClassifier(random_state=1) classifier_name = "Decision Tree" elif sys.argv[4] == "LR": clf = LogisticRegression(random_state=1) classifier_name = "Logistic Regression" elif sys.argv[4] == "SVM": clf = SVC(random_state=1) classifier_name = "SVM" elif sys.argv[4] == "AdaBoost_RF": clf = AdaBoostClassifier(base_estimator=RandomForestClassifier(n_estimators=100), random_state=1) classifier_name = "AdaBoost with Random Forest" elif sys.argv[4] == "Bagging_RF": clf = BaggingClassifier(base_estimator=RandomForestClassifier(n_estimators=100), random_state=1) classifier_name = "Bagging with Random Forest" elif sys.argv[4] == "Bagging_NB": clf = BaggingClassifier(base_estimator=GaussianNB(), random_state=1) classifier_name = "Bagging with Naive Bayes" elif sys.argv[4] == "MLP": clf = MLPClassifier(hidden_layer_sizes=(100,), max_iter=1000, activation='relu', solver='adam', random_state=1) classifier_name = "Multilayer Perceptron" elif sys.argv[4] == "BN": clf = BNClassifier(learningMethod='MIIC', prior='Smoothing', priorWeight=1, discretizationNbBins=3,discretizationStrategy="kmeans",discretizationThreshold=10) classifier_name = "Bayes Net" elif os.path.isfile(sys.argv[4]): clf = load(sys.argv[4]) classifier_name = "Loaded Model" print(f"Model loaded from {sys.argv[4]}") else: print("Invalid classifier or model filename. Use 'RF' for Random Forest, 'NB' for Naive Bayes, 'DT' for Decision Tree, or provide a valid model filename.") sys.exit(1) else: print("Invalid argument for classifier or model loading. Please use '-t'.") sys.exit(1) # Custom evaluation cv = StratifiedKFold(n_splits=10, shuffle=True, random_state=1) scoring = {'accuracy': make_scorer(accuracy_score), 'kappa': make_scorer(cohen_kappa_score), 'mae': make_scorer(mean_absolute_error), 'rmse': make_scorer(lambda y, y_pred: np.sqrt(mean_squared_error(y, y_pred))), 'rae': make_scorer(lambda y, y_pred: np.mean(np.abs(y - y_pred)) / np.mean(np.abs(y - np.mean(y))) * 100), 'rrse': make_scorer(lambda y, y_pred: np.sqrt(np.mean((y - y_pred) ** 2)) / np.sqrt(np.mean((y - np.mean(y)) ** 2)) * 100)} best_k = None best_accuracy = 0 best_evaluation_results = None for k in k_range: if sys.argv[2] in ["F", "M"]: if sys.argv[2] == "F": selector = SelectKBest(score_func=f_classif, k=k) X_new = selector.fit_transform(X, y) feature_selection_method = "ANOVA F-value" elif sys.argv[2] == "M": selector = SelectKBest(score_func=mutual_info_classif, k=k) X_new = selector.fit_transform(X, y) feature_selection_method = "Mutual Information" results = cross_validate(clf, X_new, y, cv=cv, scoring=scoring) # Calculate total instances and incorrect instances total_instances = len(y) correct_instances = np.mean(results['test_accuracy']) * total_instances incorrect_instances = total_instances - correct_instances # Compile results evaluation_results = { "Correctly Classified Instances": correct_instances, "Incorrectly Classified Instances": incorrect_instances, "Accuracy": np.mean(results['test_accuracy']) * 100, "Kappa statistic": np.mean(results['test_kappa']), "Mean absolute error": np.mean(results['test_mae']), "Root mean squared error": np.mean(results['test_rmse']), "Relative absolute error": np.mean(results['test_rae']), "Root relative squared error": np.mean(results['test_rrse']), "Total Number of Instances": total_instances } # Print results model_info = f"Model: {classifier_name}\nFeature Selection Method: {feature_selection_method}\nNumber of Features Selected: {k}" print(model_info) print("Accuracy: {:.4f}".format(evaluation_results['Accuracy'])) # Update best_k if this is the best accuracy so far if evaluation_results['Accuracy'] > best_accuracy: best_accuracy = evaluation_results['Accuracy'] best_k = k best_evaluation_results = evaluation_results print("\nBest Number of Features: {}".format(best_k)) print("Best Accuracy: {:.4f}".format(best_accuracy)) # Save best k evaluation results to a file best_model_info = f"Model: {classifier_name}\nFeature Selection Method: {feature_selection_method}\nNumber of Features Selected: {best_k}" evaluation_filename = f"{feature_selection_method} | {classifier_name} Optimal k value.txt" print_and_save_evaluation_results(best_evaluation_results, best_model_info, kfile + evaluation_filename)
import React, { useState } from 'react' import { Alert } from 'react-bootstrap'; import Button from 'react-bootstrap/Button'; import Form from 'react-bootstrap/Form'; import { useNavigate } from 'react-router-dom'; export default function Register({setPage,setData}) { const login = () => { setPage('login') } const [message, setMessage] = useState() const handleSubmit = (e) => { e.preventDefault() setData({ name:e.target.elements.name.value, email:e.target.elements.email.value, password:e.target.elements.password.value, }) const alert = ( <Alert variant="success" className='rounded-pill'>Register Success</Alert> ); setMessage(alert); login() } return ( <Form onSubmit={handleSubmit}> <h3 className='text-center mb-3' >SIGN UP</h3> {message&&message} <Form.Group className="mb-4" controlId="formBasicName"> <Form.Control className='py-2 rounded-pill' name='name' type="text" placeholder="Enter Name" /> </Form.Group> <Form.Group className="mb-4" controlId="formBasicEmail"> <Form.Control className='py-2 rounded-pill' name='email' type="email" placeholder="Enter email" /> </Form.Group> <Form.Group className="mb-4 " controlId="formBasicPassword"> <Form.Control className='py-2 rounded-pill' name='password' type="password" placeholder="Password" /> </Form.Group> <Button className='w-100 rounded-pill mb-4' variant="primary" type="submit"> Submit </Button> <p>Already Have an Account? <span style={{cursor:'pointer'}} className='fw-bold' onClick={login}>Login Here</span> </p> </Form> ) }
import 'package:ewaste_droppoin_2/main.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; class LoginPage extends StatefulWidget { const LoginPage({Key? key}) : super(key: key); @override State<LoginPage> createState() => LoginPageState(); } class LoginPageState extends State<LoginPage> { late User? user; final TextEditingController _emailController = TextEditingController(); final TextEditingController _passwordController = TextEditingController(); Future<void> _login(String email, String password) async { try { final AuthResponse res = await supabase.auth.signInWithPassword( email: email, password: password, ); user = res.user; if (!mounted) return; context.replace('/afterLoginLayout'); } on AuthException catch (e){ if (e.message == 'Invalid login credentials') { print(e); ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('Email atau password salah'), ), ); } } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(automaticallyImplyLeading: false), body: Padding( padding: const EdgeInsets.symmetric( horizontal: 20, vertical: 10, ), child: Form( child: ListView( shrinkWrap: true, reverse: true, children: [ const Text( 'Login', style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600), ), const Text('Masuk ke akunmu'), TextField( controller: _emailController, decoration: const InputDecoration( labelText: 'Email', ), ), TextField( controller: _passwordController, decoration: const InputDecoration( labelText: 'Password', ), obscureText: true, ), const SizedBox(height: 20), SizedBox( width: double.infinity, child: ElevatedButton( onPressed: () { String email = _emailController.text; String password = _passwordController.text; _login(email, password); if (user != null) { context.go('/sampahDibuang'); } }, child: const Text('Login'), ), ), const SizedBox(height: 20), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text('Belum punya akun? '), TextButton( onPressed: () => context.replace('/signUp'), child: const Text('Daftar'), ), ], ) ].reversed.toList(), ), ), ), ); } }
# Getting Started ## Creating a Python File We can make a simple Python program to do some maths for us. Start by opening a folder in VS Code. ![](./pictures/vscode-open-folder.png) Now, using either Explorer (Windows) or Finder (Mac), create a folder named "python-exercises." Make sure the folder is in a location that is easy to remember. Now open the folder and click "Select Folder". ![](./pictures/create-python-folder.gif) Now we can see that this folder has been opened with VS Code. Click on the "New File" icon to create a new file within the folder. ![](./pictures/create-file-vscode.png) Name this file "calculator.py". By giving it the `.py` extension, VS Code knows to treat it as a Python file. This will cause the new file to then open in the editor area. ![](./pictures/make-calculator-file.gif) ## `print()` and Using Python as a Calculator Now enter the code `2 + 2` in your `calculator.py` file and save it. Ctrl / Command + S is a useful shortcut for saving. Your window should now look like this: ![](./pictures/calculator-code.png) Now we can run our code. We can do this by pressing the Run / Play button in the upper-right corner of the editor region. This will lead to a terminal pane being opened. ![](./pictures/running-calculator-code.gif) The information in the terminal is telling us is that the base Conda / Mamba Python was used to run our file. However, we don't see anything else because this particular file did not generate any output. If we want to see the _result_ of `2 + 2`, we need to use Python's `print()` command. Now, instead have the code run `print(2 + 2)` and then save your file and run it again. ![](./pictures/calculator-output.png) In Python, `print()` is a built-in command used to display output to the console. It takes zero or more values and displays them as text. > **EXTRA**: Try using the division `\` , floor division `\\`, multiplication `*`, modulo `%`, and power `**` operators to perform other calculations. ### Auto Complete and Parameter Hints As you were typing out the `print()` command earlier, you may have noticed a box appear with a list of items. At first it's a list of items beginning with p, and then a list of items with the letters p and r in them, and so-on. This is a feature found in many IDEs known as Auto Complete. The purpose of Auto Complete is to save you some extra keystrokes by presenting you with a list of things it thinks you are in the process of typing out. If the item at the top of the list is what you're after then you can hit the Enter key and the rest will be entered in for you. In the example below, just the letters "pri" are typed out. By pressing Enter, Auto Complete then takes care of the rest and finished writing out the command for me. ![](./pictures/vscode-autocomplete.gif) Another helpful features in IDEs is Parameter Hints. This gives us a description of a command we are working with and some guidance on how it should be used. ![](./pictures/parameter-hints.gif) As you code more in Python, you'll find yourself using more commands that need to be used in a specific way and that expect its inputs to be given in a specific order. Getting a reminder from the IDE on how this should be done can save a bit of Googling time. ## Comments When you run Python code, something called the **Python Interpreter** converts Python code into something the machine can understand. When the interpreter encounters the # symbol it ignores this symbol and any text following it. Comments allow you to clarify your code, which can be especially helpful for your future self or other people you are working with. Getting into the habit of writing comments helps make your code more maintainable in the long-run. ```python # this bit of text will not be run print(1 + 1) # this print statement will be run, but this comment will not ``` ## Summary - VS Code can be used to manage Python projects containing multiple files. - Python can perform basic maths. - The `print()` command in Python can display information on our terminal. - Auto Complete helps shorten the process of typing out something while coding. - Parameter Hints remind us how a command should be used, and what inputs it's expecting. - Commenting your code makes it easier to use and understand. --- [Prev](introduction.md) | [List of Contents](README.md) | [Next](variables.md)