text
stringlengths
184
4.48M
"use client"; import { BsDot } from "react-icons/bs"; import dayjs from "dayjs"; import relativeTime from "dayjs/plugin/relativeTime"; import LikeButton from "./like-button"; import ReplyDialog from "./reply-dialog"; import { useRouter } from "next/navigation"; import { TweetProps } from "types/types"; dayjs.extend(relativeTime); const Tweet = ({ tweet, likesCount, hasLiked, repliesCount }: TweetProps) => { const router = useRouter(); return ( <> <div className="flex gap-2 items-start p-4 border-b border-gray-700"> <div> <div className="rounded-full h-10 w-10 bg-slate-500"></div> </div> <div className="flex flex-col w-full"> <div className="flex items-center w-full justify-between"> <div className="flex items-center space-x-1 w-full"> <div onClick={() => { router.push(`/loggedin/${tweet.userProfile.username}`); }} className="font-bold cursor-pointer text-white" > {tweet.userProfile.fullName ?? ""} </div> <div onClick={() => { router.push(`/loggedin/${tweet.userProfile.username}`); }} className="text-gray-500 cursor-pointer" > @{tweet.userProfile.username} </div> <div className="text-gray-500"> <BsDot /> </div> <div className="text-gray-500"> {dayjs(tweet.tweetDetails.createdAt).fromNow()} </div> </div> <div></div> </div> <div onClick={() => { router.push(`/loggedin/tweet/${tweet.tweetDetails.id}`); }} className="text-white text-base w-full cursor-pointer hover:bg-white/5 transition-all" > {tweet.tweetDetails.text} </div> {/* <div className="bg-slate-400 aspect-square w-full h-80 rounded-xl mt-2"></div> */} <div className="flex items-center justify-start space-x-20 mt-2 w-full"> <ReplyDialog tweet={tweet} repliesCount={repliesCount} /> {/* <div className="rounded-full hover:bg-white/10 transition duration-200 cursor-pointer"> <AiOutlineRetweet /> </div> */} <LikeButton tweetId={tweet.tweetDetails.id} likesCount={likesCount} isUserHasLiked={hasLiked} /> {/* <div className="rounded-full hover:bg-white/10 transition duration-200 cursor-pointer"> <IoStatsChart /> </div> */} {/* <div className="rounded-full hover:bg-white/10 transition duration-200 cursor-pointer"> <IoShareOutline /> </div> */} </div> </div> </div> </> ); }; export default Tweet;
import { type ProviderResource, type ResourceOptions } from "@pulumi/pulumi"; import * as kubernetes from "@pulumi/kubernetes"; import { type BlockConfiguration, type BlockConfig, type ProvidedResource, type StackContext, } from "~/types"; import logo from "./logo.svg"; import { deletedWith, provider } from "../utils"; import { createDeployment } from ".."; type PlatformTopicConfiguration = BlockConfiguration<{ cron: boolean; schedule?: string; image: string; kubernetes: string; env?: { keyvalue: { key: string; value: string } }[]; }>; const program = async ( config: PlatformTopicConfiguration, links: ProvidedResource[], _: StackContext, options?: ResourceOptions // eslint-disable-next-line @typescript-eslint/require-await ) => { const name = config.name.toLowerCase().replaceAll(" ", "_"); const k8s_name = name.replaceAll("_", "-"); const k8s_provider = links.find((l) => l.type === "provider-kubernetes") ?.resource as ProviderResource; if (!k8s_provider) throw new Error("Workers require a configured kubernetes cluster."); const commonOptions = deletedWith( k8s_provider, provider(k8s_provider, options) ); if (!config.cron) { createDeployment( { name: k8s_name, enableServiceLinks: false, noService: true, containers: [ { image: config.image, }, ], }, commonOptions ); } else { const { schedule } = config; if (!schedule) throw new Error("Schedule is not set!"); new kubernetes.batch.v1.CronJob( k8s_name, { metadata: { name: k8s_name, }, spec: { schedule, jobTemplate: { spec: { template: { spec: { restartPolicy: "OnFailure", containers: [ { name: `${k8s_name}-container`, image: config.image, env: config.env?.map(({ keyvalue }) => ({ name: keyvalue.key, value: keyvalue.value, })), }, ], }, }, }, }, }, }, commonOptions ); } }; const Block: BlockConfig<PlatformTopicConfiguration> = { name: "worker", label: "Worker", type: "worker", // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment image: { data: logo, width: 800, height: 800 }, program: program, configuration: [ { name: "Worker", fields: [ { name: "kubernetes", title: "Kubernetes Cluster", type: "dropdown", provides: "provider-kubernetes", required: true, direction: "in", }, { name: "image", title: "Image name", type: "text", required: true, }, { name: "cron", title: "Run this worker periodically?", type: "boolean", required: true, description: "If true the worker will be run according to the defined schedule.", }, { name: "schedule", title: "Schedule", description: "Use crontab syntax to define the schedule", type: "text", required: true, visibleIf: "{cron} = 'true'", }, { name: "env", title: "Environment variables", type: "keyvalue-list", required: false, }, ], }, ], }; export default Block;
const { response } = require("express"); const Employee = require("../models/Employee"); const { error } = require("console"); //shows the list of employee const index = (req, res, next) => { if (req.query.page && req.query.limit) { Employee.paginate({}, { page: req.query.page, limit: req.query.limit }) .then((response) => { res.json({ response, }); }) .catch((error) => { res.json({ message: "An error Occured: " + error }); }); } else { Employee.find() .then((response) => { res.json({ response, }); }) .catch((error) => { res.json({ message: "An error Occured: " + error }); }); } // Employee.find() // .then((response) => { // res.json({ // response, // }); // }) // .catch((error) => { // res.json({ // message: "An error occured!", // }); // }); }; //for single employee const show = (req, res, next) => { let employeeID = req.body.employeeID; Employee.findById(employeeID) .then((response) => { res.json({ response, }); }) .catch((error) => { res.json({ message: "An error occured!", }); }); }; //store employee const store = (req, res, next) => { let employee = new Employee({ name: req.body.name, designation: req.body.designation, email: req.body.email, phone: req.body.phone, age: req.body.age, }); if (req.file) { employee.avatar = req.file.path; } employee .save() .then((response) => { res.json({ message: "Employee Saved Successfully!", }); }) .catch((error) => { res.json({ message: "An error occured while saving employee", }); }); }; //update an employee const update = (req, res, next) => { let employeeID = req.body.employeeID; let updateData = { name: req.body.name, designation: req.body.designation, email: req.body.email, phone: req.body.phone, age: req.body.age, }; Employee.findByIdAndUpdate(employeeID, { $set: updateData }) .then(() => { res.json({ message: "Employee Updated Successfully", }); }) .catch((error) => { res.json({ message: "An error occured when updating data!", }); }); }; //delete an employee const destroy = (req, res, next) => { let employeeID = req.body.employeeID; Employee.findOneAndDelete(employeeID) .then(() => { res.json({ message: "Employee deleted sucessfully", }); }) .catch((error) => { res.json({ message: "An error occured when deleting employee!", }); }); }; module.exports = { index, show, store, update, destroy, };
--- permalink: online-help/reference-performance-all-aggregates-view.html sidebar: sidebar keywords: summary: 'The Performance/Aggregates inventory page displays an overview of the performance events, data, and configuration information for each aggregate that is monitored by an instance of Unified Manager. This page enables you to monitor the performance of your aggregates, and to troubleshoot performance issues and threshold events.' --- = Performance/Aggregates inventory page :icons: font :imagesdir: ../media/ [.lead] The Performance/Aggregates inventory page displays an overview of the performance events, data, and configuration information for each aggregate that is monitored by an instance of Unified Manager. This page enables you to monitor the performance of your aggregates, and to troubleshoot performance issues and threshold events. Depending on how you navigate to this page, a different title may be displayed on the page to indicate whether the list has been filtered. For example, when displaying all aggregates, the title is "`Aggregates`". When displaying a subset of aggregates that are returned from the Threshold Policies page, the title is "`Aggregates on which policy aggr_IOPS is applied`". The buttons along the top of the page enable you to perform searches to locate specific data, create and apply filters to narrow the list of displayed data, export the data on the page to a `.csv` file, and add or remove columns from the page. By default, objects on the object inventory pages are sorted based on object performance event criticality. Objects with critical events are listed first, and objects with warning events are listed second. This provides an immediate visual indication of issues that must be addressed. The values of the performance counters are based on an average from the previous 72 or more hours of data, as indicated on the page. You can click the refresh button to update the object inventory data. You can assign performance threshold policies to, or clear threshold policies from, any object on the object inventory pages using the *Assign Performance Threshold Policy* and *Clear PerformanceThreshold Policy* buttons. [NOTE] ==== Root aggregates are not displayed on this page. ==== == Aggregates inventory page columns The Performance/Aggregates inventory page contains the following columns for each aggregate. * *Status* + A healthy object with no active events displays a green check mark icon (image:../media/sev-normal-um60.png[Icon for event severity – normal]). If the object has an active event, the event indicator icon identifies the event severity: critical events are red (image:../media/sev-critical-um60.png[Icon for event severity – critical]), error events are orange (image:../media/sev-error-um60.png[Icon for event severity – error]), and warning events are yellow (image:../media/sev-warning-um60.png[Icon for event severity – warning]). * *Aggregate* + You can click the aggregate name to navigate to that aggregate's performance details page. * *Aggregate Type* + The type of aggregate: ** HDD ** Hybrid + Combines HDDs and SSDs, but Flash Pool has not been enabled. ** Hybrid (Flash Pool) + Combines HDDs and SSDs, and Flash Pool has been enabled. ** SSD ** SSD (FabricPool) + Combines SSDs and a cloud tier ** VMDisk (SDS) + Virtual disks within a virtual machine ** VMDisk (FabricPool) + Combines virtual disks and a cloud tier ** LUN (FlexArray) This column displays "`Not Available`" when the monitored storage system is running a version of ONTAP earlier than 8.3. * *Latency* + The average response time for all I/O requests on the aggregate, expressed in milliseconds per operation. * *IOPS* + The input/output operations per second on the aggregate. * *MBps* + The throughput on the aggregate, measured in megabytes per second. * *Performance Capacity Used* + The percentage of performance capacity that is being used by the aggregate. + [NOTE] ==== Performance capacity data is available only when the nodes in a cluster are installed with ONTAP 9.0 or later software. ==== * *Utilization* + The percentage of the aggregate's disks that are currently being used. * *Free Capacity* + The unused storage capacity for this aggregate, in gigabytes. * *Total Capacity* + The total storage capacity for this aggregate, in gigabytes. * *Inactive Data Reporting* + Whether the inactive data reporting capability is enabled or disabled on this aggregate. When enabled, volumes on this aggregate display the amount of cold data in the Performance/Volumes inventory page. + The value in this field is "`N/A`" when the version of ONTAP does not support inactive data reporting. * *Cluster* + The cluster to which the aggregate belongs. You can click the cluster name to navigate to that cluster's details page. * *Node* + The node to which the aggregate belongs. You can click the node name to navigate to that node's details page. * *Threshold Policy* + The user-defined performance threshold policy, or policies, that are active on this storage object. You can position your cursor over policy names containing an ellipsis (...) to view the full policy name or the list of assigned policy names. The *Assign Performance Threshold Policy* and *Clear Performance Threshold Policy* buttons remain disabled until you select one or more objects by clicking the check boxes located at the far left.
/** * Copyright (c) 2000-2005 Liferay, LLC. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.liferay.portlet.imagegallery.service.persistence; import com.liferay.portal.SystemException; import com.liferay.portal.service.persistence.BasePersistence; import com.liferay.portal.util.HibernateUtil; import com.liferay.portlet.imagegallery.NoSuchFolderException; import com.liferay.util.dao.hibernate.OrderByComparator; import com.liferay.util.lang.FastStringBuffer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.ScrollableResults; import org.hibernate.Session; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * <a href="IGFolderPersistence.java.html"><b><i>View Source</i></b></a> * * @author Brian Wing Shun Chan * @version $Revision: 1.183 $ * */ public class IGFolderPersistence extends BasePersistence { public com.liferay.portlet.imagegallery.model.IGFolder create( String folderId) { return new com.liferay.portlet.imagegallery.model.IGFolder(folderId); } public com.liferay.portlet.imagegallery.model.IGFolder remove( String folderId) throws NoSuchFolderException, SystemException { Session session = null; try { session = openSession(); IGFolderHBM igFolderHBM = (IGFolderHBM)session.get(IGFolderHBM.class, folderId); if (igFolderHBM == null) { _log.warn("No IGFolder exists with the primary key of " + folderId.toString()); throw new NoSuchFolderException(folderId.toString()); } com.liferay.portlet.imagegallery.model.IGFolder igFolder = IGFolderHBMUtil.model(igFolderHBM); session.delete(igFolderHBM); session.flush(); IGFolderPool.remove(folderId); return igFolder; } catch (HibernateException he) { throw new SystemException(he); } finally { HibernateUtil.closeSession(session); } } public com.liferay.portlet.imagegallery.model.IGFolder update( com.liferay.portlet.imagegallery.model.IGFolder igFolder) throws SystemException { Session session = null; try { if (igFolder.isNew() || igFolder.isModified()) { session = openSession(); if (igFolder.isNew()) { IGFolderHBM igFolderHBM = new IGFolderHBM(igFolder.getFolderId(), igFolder.getGroupId(), igFolder.getCompanyId(), igFolder.getUserId(), igFolder.getCreateDate(), igFolder.getModifiedDate(), igFolder.getParentFolderId(), igFolder.getName()); session.save(igFolderHBM); session.flush(); } else { IGFolderHBM igFolderHBM = (IGFolderHBM)session.get(IGFolderHBM.class, igFolder.getPrimaryKey()); if (igFolderHBM != null) { igFolderHBM.setGroupId(igFolder.getGroupId()); igFolderHBM.setCompanyId(igFolder.getCompanyId()); igFolderHBM.setUserId(igFolder.getUserId()); igFolderHBM.setCreateDate(igFolder.getCreateDate()); igFolderHBM.setModifiedDate(igFolder.getModifiedDate()); igFolderHBM.setParentFolderId(igFolder.getParentFolderId()); igFolderHBM.setName(igFolder.getName()); session.flush(); } else { igFolderHBM = new IGFolderHBM(igFolder.getFolderId(), igFolder.getGroupId(), igFolder.getCompanyId(), igFolder.getUserId(), igFolder.getCreateDate(), igFolder.getModifiedDate(), igFolder.getParentFolderId(), igFolder.getName()); session.save(igFolderHBM); session.flush(); } } igFolder.setNew(false); igFolder.setModified(false); igFolder.protect(); IGFolderPool.put(igFolder.getPrimaryKey(), igFolder); } return igFolder; } catch (HibernateException he) { throw new SystemException(he); } finally { HibernateUtil.closeSession(session); } } public com.liferay.portlet.imagegallery.model.IGFolder findByPrimaryKey( String folderId) throws NoSuchFolderException, SystemException { com.liferay.portlet.imagegallery.model.IGFolder igFolder = IGFolderPool.get(folderId); Session session = null; try { if (igFolder == null) { session = openSession(); IGFolderHBM igFolderHBM = (IGFolderHBM)session.get(IGFolderHBM.class, folderId); if (igFolderHBM == null) { _log.warn("No IGFolder exists with the primary key of " + folderId.toString()); throw new NoSuchFolderException(folderId.toString()); } igFolder = IGFolderHBMUtil.model(igFolderHBM); } return igFolder; } catch (HibernateException he) { throw new SystemException(he); } finally { HibernateUtil.closeSession(session); } } public List findByGroupId(String groupId) throws SystemException { Session session = null; try { session = openSession(); FastStringBuffer query = new FastStringBuffer(); query.append( "FROM IGFolder IN CLASS com.liferay.portlet.imagegallery.service.persistence.IGFolderHBM WHERE "); query.append("groupId = ?"); query.append(" "); query.append("ORDER BY "); query.append("name ASC"); Query q = session.createQuery(query.toString()); int queryPos = 0; q.setString(queryPos++, groupId); Iterator itr = q.list().iterator(); List list = new ArrayList(); while (itr.hasNext()) { IGFolderHBM igFolderHBM = (IGFolderHBM)itr.next(); list.add(IGFolderHBMUtil.model(igFolderHBM)); } return list; } catch (HibernateException he) { throw new SystemException(he); } finally { HibernateUtil.closeSession(session); } } public List findByGroupId(String groupId, int begin, int end) throws SystemException { return findByGroupId(groupId, begin, end, null); } public List findByGroupId(String groupId, int begin, int end, OrderByComparator obc) throws SystemException { Session session = null; try { session = openSession(); FastStringBuffer query = new FastStringBuffer(); query.append( "FROM IGFolder IN CLASS com.liferay.portlet.imagegallery.service.persistence.IGFolderHBM WHERE "); query.append("groupId = ?"); query.append(" "); if (obc != null) { query.append("ORDER BY " + obc.getOrderBy()); } else { query.append("ORDER BY "); query.append("name ASC"); } Query q = session.createQuery(query.toString()); int queryPos = 0; q.setString(queryPos++, groupId); List list = new ArrayList(); if (getDialect().supportsLimit()) { q.setMaxResults(end - begin); q.setFirstResult(begin); Iterator itr = q.list().iterator(); while (itr.hasNext()) { IGFolderHBM igFolderHBM = (IGFolderHBM)itr.next(); list.add(IGFolderHBMUtil.model(igFolderHBM)); } } else { ScrollableResults sr = q.scroll(); if (sr.first() && sr.scroll(begin)) { for (int i = begin; i < end; i++) { IGFolderHBM igFolderHBM = (IGFolderHBM)sr.get(0); list.add(IGFolderHBMUtil.model(igFolderHBM)); if (!sr.next()) { break; } } } } return list; } catch (HibernateException he) { throw new SystemException(he); } finally { HibernateUtil.closeSession(session); } } public com.liferay.portlet.imagegallery.model.IGFolder findByGroupId_First( String groupId, OrderByComparator obc) throws NoSuchFolderException, SystemException { List list = findByGroupId(groupId, 0, 1, obc); if (list.size() == 0) { throw new NoSuchFolderException(); } else { return (com.liferay.portlet.imagegallery.model.IGFolder)list.get(0); } } public com.liferay.portlet.imagegallery.model.IGFolder findByGroupId_Last( String groupId, OrderByComparator obc) throws NoSuchFolderException, SystemException { int count = countByGroupId(groupId); List list = findByGroupId(groupId, count - 1, count, obc); if (list.size() == 0) { throw new NoSuchFolderException(); } else { return (com.liferay.portlet.imagegallery.model.IGFolder)list.get(0); } } public com.liferay.portlet.imagegallery.model.IGFolder[] findByGroupId_PrevAndNext( String folderId, String groupId, OrderByComparator obc) throws NoSuchFolderException, SystemException { com.liferay.portlet.imagegallery.model.IGFolder igFolder = findByPrimaryKey(folderId); int count = countByGroupId(groupId); Session session = null; try { session = openSession(); FastStringBuffer query = new FastStringBuffer(); query.append( "FROM IGFolder IN CLASS com.liferay.portlet.imagegallery.service.persistence.IGFolderHBM WHERE "); query.append("groupId = ?"); query.append(" "); if (obc != null) { query.append("ORDER BY " + obc.getOrderBy()); } else { query.append("ORDER BY "); query.append("name ASC"); } Query q = session.createQuery(query.toString()); int queryPos = 0; q.setString(queryPos++, groupId); com.liferay.portlet.imagegallery.model.IGFolder[] array = new com.liferay.portlet.imagegallery.model.IGFolder[3]; ScrollableResults sr = q.scroll(); if (sr.first()) { while (true) { IGFolderHBM igFolderHBM = (IGFolderHBM)sr.get(0); if (igFolderHBM == null) { break; } com.liferay.portlet.imagegallery.model.IGFolder curIGFolder = IGFolderHBMUtil.model(igFolderHBM); int value = obc.compare(igFolder, curIGFolder); if (value == 0) { if (!igFolder.equals(curIGFolder)) { break; } array[1] = curIGFolder; if (sr.previous()) { array[0] = IGFolderHBMUtil.model((IGFolderHBM)sr.get( 0)); } sr.next(); if (sr.next()) { array[2] = IGFolderHBMUtil.model((IGFolderHBM)sr.get( 0)); } break; } if (count == 1) { break; } count = (int)Math.ceil(count / 2.0); if (value < 0) { if (!sr.scroll(count * -1)) { break; } } else { if (!sr.scroll(count)) { break; } } } } return array; } catch (HibernateException he) { throw new SystemException(he); } finally { HibernateUtil.closeSession(session); } } public List findByG_C(String groupId, String companyId) throws SystemException { Session session = null; try { session = openSession(); FastStringBuffer query = new FastStringBuffer(); query.append( "FROM IGFolder IN CLASS com.liferay.portlet.imagegallery.service.persistence.IGFolderHBM WHERE "); query.append("groupId = ?"); query.append(" AND "); query.append("companyId = ?"); query.append(" "); query.append("ORDER BY "); query.append("name ASC"); Query q = session.createQuery(query.toString()); int queryPos = 0; q.setString(queryPos++, groupId); q.setString(queryPos++, companyId); Iterator itr = q.list().iterator(); List list = new ArrayList(); while (itr.hasNext()) { IGFolderHBM igFolderHBM = (IGFolderHBM)itr.next(); list.add(IGFolderHBMUtil.model(igFolderHBM)); } return list; } catch (HibernateException he) { throw new SystemException(he); } finally { HibernateUtil.closeSession(session); } } public List findByG_C(String groupId, String companyId, int begin, int end) throws SystemException { return findByG_C(groupId, companyId, begin, end, null); } public List findByG_C(String groupId, String companyId, int begin, int end, OrderByComparator obc) throws SystemException { Session session = null; try { session = openSession(); FastStringBuffer query = new FastStringBuffer(); query.append( "FROM IGFolder IN CLASS com.liferay.portlet.imagegallery.service.persistence.IGFolderHBM WHERE "); query.append("groupId = ?"); query.append(" AND "); query.append("companyId = ?"); query.append(" "); if (obc != null) { query.append("ORDER BY " + obc.getOrderBy()); } else { query.append("ORDER BY "); query.append("name ASC"); } Query q = session.createQuery(query.toString()); int queryPos = 0; q.setString(queryPos++, groupId); q.setString(queryPos++, companyId); List list = new ArrayList(); if (getDialect().supportsLimit()) { q.setMaxResults(end - begin); q.setFirstResult(begin); Iterator itr = q.list().iterator(); while (itr.hasNext()) { IGFolderHBM igFolderHBM = (IGFolderHBM)itr.next(); list.add(IGFolderHBMUtil.model(igFolderHBM)); } } else { ScrollableResults sr = q.scroll(); if (sr.first() && sr.scroll(begin)) { for (int i = begin; i < end; i++) { IGFolderHBM igFolderHBM = (IGFolderHBM)sr.get(0); list.add(IGFolderHBMUtil.model(igFolderHBM)); if (!sr.next()) { break; } } } } return list; } catch (HibernateException he) { throw new SystemException(he); } finally { HibernateUtil.closeSession(session); } } public com.liferay.portlet.imagegallery.model.IGFolder findByG_C_First( String groupId, String companyId, OrderByComparator obc) throws NoSuchFolderException, SystemException { List list = findByG_C(groupId, companyId, 0, 1, obc); if (list.size() == 0) { throw new NoSuchFolderException(); } else { return (com.liferay.portlet.imagegallery.model.IGFolder)list.get(0); } } public com.liferay.portlet.imagegallery.model.IGFolder findByG_C_Last( String groupId, String companyId, OrderByComparator obc) throws NoSuchFolderException, SystemException { int count = countByG_C(groupId, companyId); List list = findByG_C(groupId, companyId, count - 1, count, obc); if (list.size() == 0) { throw new NoSuchFolderException(); } else { return (com.liferay.portlet.imagegallery.model.IGFolder)list.get(0); } } public com.liferay.portlet.imagegallery.model.IGFolder[] findByG_C_PrevAndNext( String folderId, String groupId, String companyId, OrderByComparator obc) throws NoSuchFolderException, SystemException { com.liferay.portlet.imagegallery.model.IGFolder igFolder = findByPrimaryKey(folderId); int count = countByG_C(groupId, companyId); Session session = null; try { session = openSession(); FastStringBuffer query = new FastStringBuffer(); query.append( "FROM IGFolder IN CLASS com.liferay.portlet.imagegallery.service.persistence.IGFolderHBM WHERE "); query.append("groupId = ?"); query.append(" AND "); query.append("companyId = ?"); query.append(" "); if (obc != null) { query.append("ORDER BY " + obc.getOrderBy()); } else { query.append("ORDER BY "); query.append("name ASC"); } Query q = session.createQuery(query.toString()); int queryPos = 0; q.setString(queryPos++, groupId); q.setString(queryPos++, companyId); com.liferay.portlet.imagegallery.model.IGFolder[] array = new com.liferay.portlet.imagegallery.model.IGFolder[3]; ScrollableResults sr = q.scroll(); if (sr.first()) { while (true) { IGFolderHBM igFolderHBM = (IGFolderHBM)sr.get(0); if (igFolderHBM == null) { break; } com.liferay.portlet.imagegallery.model.IGFolder curIGFolder = IGFolderHBMUtil.model(igFolderHBM); int value = obc.compare(igFolder, curIGFolder); if (value == 0) { if (!igFolder.equals(curIGFolder)) { break; } array[1] = curIGFolder; if (sr.previous()) { array[0] = IGFolderHBMUtil.model((IGFolderHBM)sr.get( 0)); } sr.next(); if (sr.next()) { array[2] = IGFolderHBMUtil.model((IGFolderHBM)sr.get( 0)); } break; } if (count == 1) { break; } count = (int)Math.ceil(count / 2.0); if (value < 0) { if (!sr.scroll(count * -1)) { break; } } else { if (!sr.scroll(count)) { break; } } } } return array; } catch (HibernateException he) { throw new SystemException(he); } finally { HibernateUtil.closeSession(session); } } public List findByG_C_P(String groupId, String companyId, String parentFolderId) throws SystemException { Session session = null; try { session = openSession(); FastStringBuffer query = new FastStringBuffer(); query.append( "FROM IGFolder IN CLASS com.liferay.portlet.imagegallery.service.persistence.IGFolderHBM WHERE "); query.append("groupId = ?"); query.append(" AND "); query.append("companyId = ?"); query.append(" AND "); query.append("parentFolderId = ?"); query.append(" "); query.append("ORDER BY "); query.append("name ASC"); Query q = session.createQuery(query.toString()); int queryPos = 0; q.setString(queryPos++, groupId); q.setString(queryPos++, companyId); q.setString(queryPos++, parentFolderId); Iterator itr = q.list().iterator(); List list = new ArrayList(); while (itr.hasNext()) { IGFolderHBM igFolderHBM = (IGFolderHBM)itr.next(); list.add(IGFolderHBMUtil.model(igFolderHBM)); } return list; } catch (HibernateException he) { throw new SystemException(he); } finally { HibernateUtil.closeSession(session); } } public List findByG_C_P(String groupId, String companyId, String parentFolderId, int begin, int end) throws SystemException { return findByG_C_P(groupId, companyId, parentFolderId, begin, end, null); } public List findByG_C_P(String groupId, String companyId, String parentFolderId, int begin, int end, OrderByComparator obc) throws SystemException { Session session = null; try { session = openSession(); FastStringBuffer query = new FastStringBuffer(); query.append( "FROM IGFolder IN CLASS com.liferay.portlet.imagegallery.service.persistence.IGFolderHBM WHERE "); query.append("groupId = ?"); query.append(" AND "); query.append("companyId = ?"); query.append(" AND "); query.append("parentFolderId = ?"); query.append(" "); if (obc != null) { query.append("ORDER BY " + obc.getOrderBy()); } else { query.append("ORDER BY "); query.append("name ASC"); } Query q = session.createQuery(query.toString()); int queryPos = 0; q.setString(queryPos++, groupId); q.setString(queryPos++, companyId); q.setString(queryPos++, parentFolderId); List list = new ArrayList(); if (getDialect().supportsLimit()) { q.setMaxResults(end - begin); q.setFirstResult(begin); Iterator itr = q.list().iterator(); while (itr.hasNext()) { IGFolderHBM igFolderHBM = (IGFolderHBM)itr.next(); list.add(IGFolderHBMUtil.model(igFolderHBM)); } } else { ScrollableResults sr = q.scroll(); if (sr.first() && sr.scroll(begin)) { for (int i = begin; i < end; i++) { IGFolderHBM igFolderHBM = (IGFolderHBM)sr.get(0); list.add(IGFolderHBMUtil.model(igFolderHBM)); if (!sr.next()) { break; } } } } return list; } catch (HibernateException he) { throw new SystemException(he); } finally { HibernateUtil.closeSession(session); } } public com.liferay.portlet.imagegallery.model.IGFolder findByG_C_P_First( String groupId, String companyId, String parentFolderId, OrderByComparator obc) throws NoSuchFolderException, SystemException { List list = findByG_C_P(groupId, companyId, parentFolderId, 0, 1, obc); if (list.size() == 0) { throw new NoSuchFolderException(); } else { return (com.liferay.portlet.imagegallery.model.IGFolder)list.get(0); } } public com.liferay.portlet.imagegallery.model.IGFolder findByG_C_P_Last( String groupId, String companyId, String parentFolderId, OrderByComparator obc) throws NoSuchFolderException, SystemException { int count = countByG_C_P(groupId, companyId, parentFolderId); List list = findByG_C_P(groupId, companyId, parentFolderId, count - 1, count, obc); if (list.size() == 0) { throw new NoSuchFolderException(); } else { return (com.liferay.portlet.imagegallery.model.IGFolder)list.get(0); } } public com.liferay.portlet.imagegallery.model.IGFolder[] findByG_C_P_PrevAndNext( String folderId, String groupId, String companyId, String parentFolderId, OrderByComparator obc) throws NoSuchFolderException, SystemException { com.liferay.portlet.imagegallery.model.IGFolder igFolder = findByPrimaryKey(folderId); int count = countByG_C_P(groupId, companyId, parentFolderId); Session session = null; try { session = openSession(); FastStringBuffer query = new FastStringBuffer(); query.append( "FROM IGFolder IN CLASS com.liferay.portlet.imagegallery.service.persistence.IGFolderHBM WHERE "); query.append("groupId = ?"); query.append(" AND "); query.append("companyId = ?"); query.append(" AND "); query.append("parentFolderId = ?"); query.append(" "); if (obc != null) { query.append("ORDER BY " + obc.getOrderBy()); } else { query.append("ORDER BY "); query.append("name ASC"); } Query q = session.createQuery(query.toString()); int queryPos = 0; q.setString(queryPos++, groupId); q.setString(queryPos++, companyId); q.setString(queryPos++, parentFolderId); com.liferay.portlet.imagegallery.model.IGFolder[] array = new com.liferay.portlet.imagegallery.model.IGFolder[3]; ScrollableResults sr = q.scroll(); if (sr.first()) { while (true) { IGFolderHBM igFolderHBM = (IGFolderHBM)sr.get(0); if (igFolderHBM == null) { break; } com.liferay.portlet.imagegallery.model.IGFolder curIGFolder = IGFolderHBMUtil.model(igFolderHBM); int value = obc.compare(igFolder, curIGFolder); if (value == 0) { if (!igFolder.equals(curIGFolder)) { break; } array[1] = curIGFolder; if (sr.previous()) { array[0] = IGFolderHBMUtil.model((IGFolderHBM)sr.get( 0)); } sr.next(); if (sr.next()) { array[2] = IGFolderHBMUtil.model((IGFolderHBM)sr.get( 0)); } break; } if (count == 1) { break; } count = (int)Math.ceil(count / 2.0); if (value < 0) { if (!sr.scroll(count * -1)) { break; } } else { if (!sr.scroll(count)) { break; } } } } return array; } catch (HibernateException he) { throw new SystemException(he); } finally { HibernateUtil.closeSession(session); } } public List findAll() throws SystemException { Session session = null; try { session = openSession(); FastStringBuffer query = new FastStringBuffer(); query.append( "FROM IGFolder IN CLASS com.liferay.portlet.imagegallery.service.persistence.IGFolderHBM "); query.append("ORDER BY "); query.append("name ASC"); Query q = session.createQuery(query.toString()); Iterator itr = q.iterate(); List list = new ArrayList(); while (itr.hasNext()) { IGFolderHBM igFolderHBM = (IGFolderHBM)itr.next(); list.add(IGFolderHBMUtil.model(igFolderHBM)); } return list; } catch (HibernateException he) { throw new SystemException(he); } finally { HibernateUtil.closeSession(session); } } public void removeByGroupId(String groupId) throws SystemException { Session session = null; try { session = openSession(); FastStringBuffer query = new FastStringBuffer(); query.append( "FROM IGFolder IN CLASS com.liferay.portlet.imagegallery.service.persistence.IGFolderHBM WHERE "); query.append("groupId = ?"); query.append(" "); query.append("ORDER BY "); query.append("name ASC"); Query q = session.createQuery(query.toString()); int queryPos = 0; q.setString(queryPos++, groupId); Iterator itr = q.list().iterator(); while (itr.hasNext()) { IGFolderHBM igFolderHBM = (IGFolderHBM)itr.next(); IGFolderPool.remove((String)igFolderHBM.getPrimaryKey()); session.delete(igFolderHBM); } session.flush(); } catch (HibernateException he) { throw new SystemException(he); } finally { HibernateUtil.closeSession(session); } } public void removeByG_C(String groupId, String companyId) throws SystemException { Session session = null; try { session = openSession(); FastStringBuffer query = new FastStringBuffer(); query.append( "FROM IGFolder IN CLASS com.liferay.portlet.imagegallery.service.persistence.IGFolderHBM WHERE "); query.append("groupId = ?"); query.append(" AND "); query.append("companyId = ?"); query.append(" "); query.append("ORDER BY "); query.append("name ASC"); Query q = session.createQuery(query.toString()); int queryPos = 0; q.setString(queryPos++, groupId); q.setString(queryPos++, companyId); Iterator itr = q.list().iterator(); while (itr.hasNext()) { IGFolderHBM igFolderHBM = (IGFolderHBM)itr.next(); IGFolderPool.remove((String)igFolderHBM.getPrimaryKey()); session.delete(igFolderHBM); } session.flush(); } catch (HibernateException he) { throw new SystemException(he); } finally { HibernateUtil.closeSession(session); } } public void removeByG_C_P(String groupId, String companyId, String parentFolderId) throws SystemException { Session session = null; try { session = openSession(); FastStringBuffer query = new FastStringBuffer(); query.append( "FROM IGFolder IN CLASS com.liferay.portlet.imagegallery.service.persistence.IGFolderHBM WHERE "); query.append("groupId = ?"); query.append(" AND "); query.append("companyId = ?"); query.append(" AND "); query.append("parentFolderId = ?"); query.append(" "); query.append("ORDER BY "); query.append("name ASC"); Query q = session.createQuery(query.toString()); int queryPos = 0; q.setString(queryPos++, groupId); q.setString(queryPos++, companyId); q.setString(queryPos++, parentFolderId); Iterator itr = q.list().iterator(); while (itr.hasNext()) { IGFolderHBM igFolderHBM = (IGFolderHBM)itr.next(); IGFolderPool.remove((String)igFolderHBM.getPrimaryKey()); session.delete(igFolderHBM); } session.flush(); } catch (HibernateException he) { throw new SystemException(he); } finally { HibernateUtil.closeSession(session); } } public int countByGroupId(String groupId) throws SystemException { Session session = null; try { session = openSession(); FastStringBuffer query = new FastStringBuffer(); query.append("SELECT COUNT(*) "); query.append( "FROM IGFolder IN CLASS com.liferay.portlet.imagegallery.service.persistence.IGFolderHBM WHERE "); query.append("groupId = ?"); query.append(" "); Query q = session.createQuery(query.toString()); int queryPos = 0; q.setString(queryPos++, groupId); Iterator itr = q.list().iterator(); if (itr.hasNext()) { Integer count = (Integer)itr.next(); if (count != null) { return count.intValue(); } } return 0; } catch (HibernateException he) { throw new SystemException(he); } finally { HibernateUtil.closeSession(session); } } public int countByG_C(String groupId, String companyId) throws SystemException { Session session = null; try { session = openSession(); FastStringBuffer query = new FastStringBuffer(); query.append("SELECT COUNT(*) "); query.append( "FROM IGFolder IN CLASS com.liferay.portlet.imagegallery.service.persistence.IGFolderHBM WHERE "); query.append("groupId = ?"); query.append(" AND "); query.append("companyId = ?"); query.append(" "); Query q = session.createQuery(query.toString()); int queryPos = 0; q.setString(queryPos++, groupId); q.setString(queryPos++, companyId); Iterator itr = q.list().iterator(); if (itr.hasNext()) { Integer count = (Integer)itr.next(); if (count != null) { return count.intValue(); } } return 0; } catch (HibernateException he) { throw new SystemException(he); } finally { HibernateUtil.closeSession(session); } } public int countByG_C_P(String groupId, String companyId, String parentFolderId) throws SystemException { Session session = null; try { session = openSession(); FastStringBuffer query = new FastStringBuffer(); query.append("SELECT COUNT(*) "); query.append( "FROM IGFolder IN CLASS com.liferay.portlet.imagegallery.service.persistence.IGFolderHBM WHERE "); query.append("groupId = ?"); query.append(" AND "); query.append("companyId = ?"); query.append(" AND "); query.append("parentFolderId = ?"); query.append(" "); Query q = session.createQuery(query.toString()); int queryPos = 0; q.setString(queryPos++, groupId); q.setString(queryPos++, companyId); q.setString(queryPos++, parentFolderId); Iterator itr = q.list().iterator(); if (itr.hasNext()) { Integer count = (Integer)itr.next(); if (count != null) { return count.intValue(); } } return 0; } catch (HibernateException he) { throw new SystemException(he); } finally { HibernateUtil.closeSession(session); } } private static final Log _log = LogFactory.getLog(IGFolderPersistence.class); }
import React from 'react'; function FlowerBlock({ title, price, imageUrl, types, sizes }) { // const [activeType, setActiveType] = React.useState(0); const [activeSize, setActiveSize] = React.useState(0); // const typeNames = ['тонкое', 'традиционное']; return ( <div className="flower-block"> <img className="flower-block__image" src={imageUrl} alt="flower" /> <h4 className="flower-block__title">{title}</h4> <div className="flower-block__selector"> {/* <ul> {types.map((type, index) => ( <li onClick={() => setActiveType(type)} key={index} className={activeType === type ? 'active' : ''}> {typeNames[type]} </li> ))} </ul> */} <ul> {sizes.map((size, index) => ( <li key={index} onClick={() => setActiveSize(index)} className={activeSize === index ? 'active' : ''}> {size} шт. </li> ))} </ul> </div> <div className="flower-block__bottom"> <div className="flower-block__price">от {price} ₽</div> <div className="button button--outline button--add"> <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M10.8 4.8H7.2V1.2C7.2 0.5373 6.6627 0 6 0C5.3373 0 4.8 0.5373 4.8 1.2V4.8H1.2C0.5373 4.8 0 5.3373 0 6C0 6.6627 0.5373 7.2 1.2 7.2H4.8V10.8C4.8 11.4627 5.3373 12 6 12C6.6627 12 7.2 11.4627 7.2 10.8V7.2H10.8C11.4627 7.2 12 6.6627 12 6C12 5.3373 11.4627 4.8 10.8 4.8Z" fill="white" /> </svg> <span>Добавить</span> <i>2</i> </div> </div> </div> ); } export default FlowerBlock;
<?php namespace APP\Core\Interfaces; /** * Interfaz que nos garantiza que siempre que la implementemos deberemos sí o sí implémentar el método asociado, * garántizando el correcto funcionamiento de la aplicación para la recepción y procesado de la ruta por URI */ interface IRequest { /** * Función que obtiene la ruta de la URI * @return string */ public function getRoute(): string; /** * Función que obtiene los parámetros de la URI y nos los devuelve en un array * @return array */ public function getParams(): array; }
#include "lists.h" /** * find_listint_loop - Finds the loop in a linked list. * @head: A pointer to the head of the listint_t list. * * Return: The starts, or NULL if there is no loop. */ listint_t *find_listint_loop(listint_t *head) { listint_t *slow = head, *fast = head; while (slow != NULL && fast != NULL && fast->next != NULL) { slow = slow->next; fast = fast->next->next; if (slow == fast) { slow = head; while (slow != fast) { slow = slow->next; fast = fast->next; } return (slow); } } return (NULL); }
import React, { useState } from "react"; import { BrowserRouter as Router, Route } from "react-router-dom"; import Landing from "./pages/Landing"; import SignIn from "./pages/SignIn"; import SignUp from "./pages/SignUp"; import Patients from "./pages/Patients"; import EHR from "./pages/EHR"; import Contacts from "./pages/Contacts"; import NavBar from "./components/Navbar"; import ProtectedRoute from "./ProtectedRoute"; import PatientContext from "./utils/PatientContext"; import "./assets/css/bootstrap.min.css"; import "./App.css"; import Medical from "./components/MedicalAPI/Medical"; import { News } from "./components/MedicalAPI"; export default function App() { const [patient, setPatient] = useState({}), { Provider } = PatientContext, setPatientContext = (patient) => setPatient(patient); return ( <Router> <Provider value={patient}> <Route path="/"> <NavBar />{" "} </Route> <Route exact path="/"> {" "} <Landing />{" "} </Route> <Route exact path="/drugs"> {" "} <Medical />{" "} </Route> <Route exact path="/news"> {" "} <News />{" "} </Route> <Route exact path="/signin"> {" "} <SignIn />{" "} </Route> <Route exact path="/signup"> {" "} <SignUp />{" "} </Route> <ProtectedRoute exact path="/patients" component={Patients} setContext={setPatientContext} /> <ProtectedRoute exact path="/ehr" component={EHR} setContext={setPatientContext} /> <ProtectedRoute exact path="/contacts" component={Contacts} /> </Provider> </Router> ); }
import { getRedundantJobs } from "./lib/getRedundantJobs" import { Logger } from "./lib/logger" import { Scheduler } from "./scheduler" import { Host, HostChange, Provider, Target } from "./types" type OperationParams = { logger: Logger scheduler: Scheduler providers: Provider[] targets: Target[] addTargetRecordDelay: number removeTargetRecordDelay: number } export const makeOperations = (opts: OperationParams) => { const diff = (providerHosts: Host[], targetHosts: Host[]): HostChange<any, any>[] => { const recordsInProviderButNotInTarget = providerHosts .filter((h) => !targetHosts.find((t) => h.name === t.name)) .map( (host) => ({ type: "add", host, providerMeta: host.meta, targetMeta: undefined, } satisfies HostChange) ) logger.debug("[recordsInProviderButNotInTarget]", recordsInProviderButNotInTarget) const recordsInTargetButNotInProvider = targetHosts .filter((h) => !providerHosts.find((t) => t.name === h.name)) .map( (h) => ({ type: "remove", host: h, providerMeta: undefined, targetMeta: h.meta, } satisfies HostChange) ) logger.debug("[recordsInTargetButNotInProvider]", recordsInTargetButNotInProvider) return [...recordsInProviderButNotInTarget, ...recordsInTargetButNotInProvider] } const { providers, targets, logger, scheduler } = opts /** * TODO: need to rethink this. * * As of now if I have provider1 with hosts a,b and * provider2 with hosts c,d, technically I'd expect * target1 and target2 to have hosts a,b,c,d. * * However, how I coded this up, it's not the case. * It'd check provider 1 first, the diff would show that * we need a remove operation for c,d and then go to * provider 2 and diff would show that we need an remove * operation for a,b. * * I somehow need to know which subset of target hosts * belong to which provider If I want multi provider * to work correctly. TXT records maybe? * */ const syncResources = async () => { const hostsInTarget = new Map<Target, Host[]>() for (const t of targets) { const hosts = await t.getHosts() hostsInTarget.set(t, hosts) } for (const provider of providers) { const providerHosts = await provider.getHosts() for (const [target, targetHosts] of hostsInTarget) { const changesForProvider = diff(providerHosts, targetHosts) if (!changesForProvider.length) { logger.debug( `No changes for provider ${provider.getName()} and target ${target.getName()}` ) continue } const currentJobs = Array.from(scheduler.getJobs().values()) const redundantJobOperations = getRedundantJobs(currentJobs, changesForProvider) let changes = changesForProvider if (redundantJobOperations.length) { logger.info(`About to remove ${redundantJobOperations.length} redundant job operations`) redundantJobOperations.forEach(([redundantJob, redundantChange]) => { logger.info( ` - removing redundant job: ${redundantJob.jobId} and skipping change: ${redundantChange.type} ${redundantChange.host.name}` ) scheduler.removeJobIfExists(redundantJob) changes = changes.filter( (c) => !(c.type === redundantChange.type && c.host.name === redundantChange.host.name) ) }) } logger.info(`About to schedule ${changes.length} changes to ${target.getName()}:`) changes.forEach((c) => logger.info(` - ${c.type} ${c.host.name}`)) for (const c of changes) { const delayInSeconds = c.type === "add" ? opts.addTargetRecordDelay : opts.removeTargetRecordDelay scheduler.scheduleJob({ jobId: `${new Date().toISOString()}::${target.getName()}::${c.type}::${c.host.name}`, type: "ApplyChanges", delayInSeconds, fn: async () => { await target.apply([c]) }, meta: { hostName: c.host.name, type: c.type, }, }) } } } } return { syncResources, } }
import {NearestFilter, Texture, TextureLoader} from "three"; import {IsWebUrl, LogError} from "../common.util"; import {GetFileUrl} from "../firebase.util"; import {CommonErrorCode, Module} from "../../enums/common.enum"; import {TextureTone} from "../../types/texture.type"; import { Result } from "../../types/common.type"; class TextureUtil { private static _instance: TextureUtil; private _textureLoader: TextureLoader | undefined; private _textureDb: Record<string, Texture> | undefined; private constructor() { this._textureLoader = undefined; } public static Instance() { if(this._instance === undefined) this._instance = new TextureUtil(); return this._instance; } public TextureLoader() { if(this._textureLoader === undefined) this._textureLoader = new TextureLoader(); return this._textureLoader; } public async GetToneTexture(tone: TextureTone) { if (this._textureDb && this._textureDb[tone]) return this._textureDb[tone].clone(); if (this._textureDb === undefined) this._textureDb = {}; const toneTexture = await TextureUtil.Instance().TextureLoader().loadAsync(`/resources/tones/${tone}.jpg`); toneTexture.minFilter = NearestFilter; toneTexture.magFilter = NearestFilter; this._textureDb[tone] = toneTexture.clone(); return toneTexture; } public async GetTexture(url: string): Promise<Result<Texture>> { try { const newTexture = await TextureUtil.Instance().TextureLoader().loadAsync(url); return {success: true, value: newTexture}; } catch(e) { const msg = `Couldn't make a texture for url: ${url}!`; void LogError(Module.TextureUtil, msg, e); return {success: false, errMessage: msg, errCode: CommonErrorCode.InternalError}; } } public async GetTextureMemory(url: string): Promise<Result<Texture>> { if (this._textureDb && this._textureDb[url]) return {success: true, value: this._textureDb[url].clone()}; if (this._textureDb === undefined) this._textureDb = {}; try { const newTexture = await TextureUtil.Instance().TextureLoader().loadAsync(url); this._textureDb[url] = newTexture.clone(); return {success: true, value: newTexture}; } catch(e) { const msg = `Couldn't make a texture for url: ${url}!`; void LogError(Module.TextureUtil, msg, e); return {success: false, errMessage: msg, errCode: CommonErrorCode.InternalError}; } } } export async function GetToneTexture(tone: TextureTone = 'threeTone' ) { return TextureUtil.Instance().GetToneTexture(tone); } export async function GetTextureFromFile(url: string | undefined): Promise<Result<Texture>> { if (url == undefined) { const msg = "Missing URL to get texture from file!"; void LogError(Module.TextureUtil, msg); return {success: false, errMessage: msg, errCode: CommonErrorCode.MissingInfo}; } let realUrl = url; if (!IsWebUrl(url)) { const result = await GetFileUrl(url); if (result.success) realUrl = result.value; } return TextureUtil.Instance().GetTexture(realUrl); }
package codeforce.div2.r726; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Scanner; import java.util.StringTokenizer; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.ArrayList; import java.util.List; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.HashSet; import static java.lang.System.out; import static java.util.stream.Collectors.joining; /** * @author pribic (Priyank Doshi) * @see <a href="https://codeforces.com/contest/1537/problem/C" target="_top">https://codeforces.com/contest/1537/problem/C</a> * @since 18/06/21 8:41 PM */ public class C { static FastScanner sc = new FastScanner(System.in); public static void main(String[] args) { try (PrintWriter out = new PrintWriter(System.out)) { int T = sc.nextInt(); for (int tt = 1; tt <= T; tt++) { int n = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } sort(arr); if (n == 2) { System.out.println(arr[0] + " " + arr[1]); } else { int minDiff = Integer.MAX_VALUE; int minI = Integer.MAX_VALUE; for (int i = 0; i < n - 1; i++) { if (arr[i + 1] - arr[i] < minDiff) { minDiff = arr[i + 1] - arr[i]; minI = i; } } //if(arr[n - 1] - arr[0] == minDiff) if (Arrays.stream(arr, 1, n).noneMatch(i -> i != arr[0])) print(arr); else { for (int i = minI + 1; i < n; i++) System.out.print(arr[i] + " "); for (int i = 0; i < minI + 1; i++) System.out.print(arr[i] + " "); System.out.println(); } } } } } private static int find(int[] arr) { int cnt = 0; for (int i = 0; i < arr.length - 1; i++) { if (arr[i] <= arr[i + 1]) cnt++; } return cnt; } private static void print(int[] ans1clone) { for (int num : ans1clone) out.print(num + " "); out.println(); } private static void swap(int[] arr, int i, int j) { int t = arr[i]; arr[i] = arr[j]; arr[j] = t; } private static void sort(int[] arr, int st, int end) { List<Integer> list = new ArrayList<>(); for (int i = st; i <= end; i++) list.add(arr[i]); Collections.sort(list); int idx = 0; for (int i = st; i <= end; i++) arr[i] = list.get(idx++); } private static void sort(int[] arr) { sort(arr, 0, arr.length - 1); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f), 32768); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
package com.learning.thread.Synchornization; class BookTheaterSeatNoSync { int total_seats = 10; void bookSeat(int seats) { if (total_seats >= seats) { System.out.println(Thread.currentThread().getName() + ", " + seats + " seat/s booked successfully"); total_seats = total_seats - seats; System.out.println("Available seats : " + total_seats); } else { System.out.println(Thread.currentThread().getName() + ", " + "sorry seats cannot be booked !"); System.out.println("Available seats : " + total_seats); } } } // MOVIE BOOKING APP WITHOUT SYNC public class WithoutSyncExample implements Runnable{ static BookTheaterSeatNoSync bookTheaterSeat; int seats; @Override public void run() { bookTheaterSeat.bookSeat(seats); } public static void main(String[] args) { bookTheaterSeat = new BookTheaterSeatNoSync(); WithoutSyncExample deepakBookMovie = new WithoutSyncExample(); deepakBookMovie.seats = 7; Thread deepak = new Thread(deepakBookMovie); deepak.setName("deepak"); deepak.start(); WithoutSyncExample reenaBookMovie = new WithoutSyncExample(); reenaBookMovie.seats = 6; Thread reena = new Thread(reenaBookMovie); reena.setName("reena"); reena.start(); } }
// // DataType.swift // SWHub // // Created by liaoya on 2022/7/21. // import Foundation import HiIOS enum TabBarKey { case trending case event case stars case personal } enum DisplayMode: Int, Codable { case none = 0 case list var stringValue: String { switch self { case .none: return "none" case .list: return "list" } } } enum Sort: String, Codable { case stars case forks case updated case issues = "help-wanted-issues" } enum Order: String, Codable { case asc case desc } enum Platform { case github case umeng case weixin var appId: String { switch self { case .github: return "826519ff4600bcfd06fe" case .umeng: return "6093ae3653b6726499ec3983" case .weixin: return UIApplication.shared.urlScheme(name: "weixin") ?? "" } } var appKey: String { switch self { case .github: return "45dbc33afe8c9df67bbd6392bff03268e60a5855" case .umeng: return "6093ae3653b6726499ec3983" case .weixin: return "f7f6a7c1cbe503c497151e076c0a4b4d" } } // var appSecret: String { // "" // } var appLink: String { switch self { case .weixin: return "https://tospery.com/swhub/" default: return "" } } } enum Since: String, Codable { case daily case weekly case montly static let name = R.string.localizable.since() static let allValues = [daily, weekly, montly] // var paramValue: String { // switch self { // case .daily: return R.string.localizable.daily() // case .weekly: return R.string.localizable.weekly() // case .montly: return R.string.localizable.montly() // } // } } enum CellId: Int { case space = 0, button case setting = 10, about, feedback case company = 20, location, email, blog, nickname, bio case author = 30, weibo, shcemes, score, share case language = 40, issues, pullrequests, branches, readme case cache = 50, theme, local var title: String? { switch self { case .issues: return R.string.localizable.issues() case .pullrequests: return R.string.localizable.pullRequests() case .branches: return R.string.localizable.branches() case .readme: return R.string.localizable.readme().uppercased() case .cache: return R.string.localizable.clearCache() case .theme: return R.string.localizable.colorTheme() case .local: return R.string.localizable.languageEnvironment() default: return nil } } var icon: String? { switch self { // user case .company: return R.image.ic_user_company.name case .location: return R.image.ic_user_location.name case .email: return R.image.ic_user_email.name case .blog: return R.image.ic_user_blog.name // repo case .language: return R.image.ic_repo_language.name case .issues: return R.image.ic_repo_issues.name case .pullrequests: return R.image.ic_repo_pullrequests.name case .branches: return R.image.ic_repo_branches.name case .readme: return R.image.ic_repo_readme.name default: return nil } } } enum IHAlertAction: AlertActionType, Equatable { case destructive case `default` case cancel case input case onlyPublic case withPrivate case exit init?(string: String) { switch string { case IHAlertAction.cancel.title: self = IHAlertAction.cancel case IHAlertAction.exit.title: self = IHAlertAction.exit default: return nil } } var title: String? { switch self { case .destructive: return R.string.localizable.sure() case .default: return R.string.localizable.oK() case .cancel: return R.string.localizable.cancel() case .onlyPublic: return R.string.localizable.loginPrivilegeOnlyPublic() case .withPrivate: return R.string.localizable.loginPrivilegeWithPrivate() case .exit: return R.string.localizable.exit() default: return nil } } var style: UIAlertAction.Style { switch self { case .cancel: return .cancel case .destructive, .exit: return .destructive default: return .default } } static func == (lhs: IHAlertAction, rhs: IHAlertAction) -> Bool { switch (lhs, rhs) { case (.destructive, .destructive), (.default, .default), (.cancel, .cancel), (.input, .input), (.onlyPublic, .onlyPublic), (.withPrivate, .withPrivate), (.exit, .exit): return true default: return false } } } struct Author { static let username = "tospery" static let reponame = "SWHub" } struct Metric { static let listAvatarSize = CGSize.init(40.f) static let detailAvatarSize = CGSize.init(60.f) struct Repo { static let maxLines = 5 } struct Personal { static let parallaxTopHeight = 244.0 static let parallaxAllHeight = 290.0 } }
import React from 'react' import styled from 'styled-components' import { useCartContext } from '../context/cart_context' import { useUserContext } from '../context/user_context' import { formatPrice } from '../utils/helpers' import { Link } from 'react-router-dom' /**comfy-sloth-ecommerce app version 32 - CartTotals * Component - Features: * * --> Fixing Redirect warning by removing it * from the imports. * * Notes: 'loginWithRedirect' will handle 'myUser' * login before the to checkout * * pending to handle a redirect to checkout page after * the 'myUser' login */ const CartTotals = () => { const { total_amount, shipping_fee } = useCartContext(); const { myUser, loginWithRedirect } = useUserContext(); return( <Wrapper> <div> <article> <h5>subtotal: <span>{formatPrice(total_amount)} </span> </h5> <p>shipping fee: <span>{formatPrice(shipping_fee)} </span> </p> <hr /> <h4>order total: <span> {formatPrice(total_amount + shipping_fee) }</span> </h4> </article> { myUser ? ( <Link to='/checkout' className='btn'> proceed to checkout </Link> ) : <button className='btn' onClick={loginWithRedirect}>login</button> } </div> </Wrapper> ) } const Wrapper = styled.section` margin-top: 3rem; display: flex; justify-content: center; article { border: 1px solid var(--clr-grey-8); border-radius: var(--radius); padding: 1.5rem 3rem; } h4, h5, p { display: grid; grid-template-columns: 200px 1fr; } p { text-transform: capitalize; } h4 { margin-top: 2rem; } @media (min-width: 776px) { justify-content: flex-end; } .btn { width: 100%; margin-top: 1rem; text-align: center; font-weight: 700; } ` export default CartTotals
<ion-navbar *navbar class="tab-nav"> <ion-title>New Challenge</ion-title> </ion-navbar> <ion-content class="createchallenge"> <!-- Body --> <div class="container top-padding"> <form [ngFormModel]="challengeform" (ngSubmit)="onSubmit(challengeform.value)"> <!-- GENERAL CHALLENGE INFO --> <div class="color-white general-padding">GENERAL</div> <ion-list> <ion-item> <ion-label stacked>Competition Name</ion-label> <ion-input [ngFormControl]="challengeform.controls['name']" type="text" placeholder="Name the challenge"> </ion-input> </ion-item> <p class="color-red container" [hidden]="challengeform.controls.name.pristine || challengeform.controls.name.valid">Please provide a competition name</p> <ion-item> <ion-label stacked>Purpose</ion-label> <ion-select [ngFormControl]="challengeform.controls['purpose']"> <ion-option value="health" checked="true">Health and Fitness</ion-option> </ion-select> </ion-item> <ion-item> <ion-label stacked>Time Frame</ion-label> <ion-select [ngFormControl]="challengeform.controls['timeframe']"> <ion-option value="1day" checked="true">1 Day</ion-option> <ion-option value="2days">2 Days</ion-option> <ion-option value="3days">3 Days</ion-option> <ion-option value="1week">1 Week</ion-option> <ion-option value="2weeks">2 Weeks</ion-option> <ion-option value="1month">1 Month</ion-option> </ion-select> </ion-item> <ion-item> <ion-label stacked>Start Date</ion-label> <ion-input [ngFormControl]="challengeform.controls['startdate']" type="date" placeholder="Start date"> </ion-input> </ion-item> </ion-list> <div class="color-white general-padding">SPORTS & METRICS</div> <ion-list> <ion-item> <ion-label stacked>Type of Challenge</ion-label> <ion-select [ngFormControl]="challengeform.controls['challengetype']"> <ion-option value="1v1" checked="true">One on One</ion-option> <ion-option value="myself">Challenge Myself</ion-option> <ion-option value="other">Challenge Other</ion-option> </ion-select> </ion-item> <ion-item> <ion-label stacked>Category</ion-label> <ion-select [ngFormControl]="challengeform.controls['category']"> <ion-option value="running" checked="true">Running</ion-option> <ion-option value="cycling">Cycling</ion-option> <ion-option value="swimming">Swimming</ion-option> <ion-option value="lifting">Lifting</ion-option> </ion-select> </ion-item> <ion-item> <ion-label stacked>Challenge Course</ion-label> <ion-select [ngFormControl]="challengeform.controls['challengecourse']"> <ion-option value="distance" checked="true">Distance</ion-option> <ion-option value="time">Time</ion-option> <ion-option value="reps">Reps</ion-option> </ion-select> </ion-item> <ion-item> <ion-label stacked>Describe the Challenge</ion-label> <ion-input [ngFormControl]="challengeform.controls['description']" type="text" placeholder="Describe the challenge"> </ion-input> </ion-item> <p class="color-red container" [hidden]="challengeform.controls.description.pristine || challengeform.controls.description.valid">Please provide a description of the challenge</p> <ion-item> <ion-label stacked>Proof of Completion</ion-label> <ion-select [ngFormControl]="challengeform.controls['proof']"> <ion-option value="uploadpic" checked="true">Upload a Picture</ion-option> <ion-option value="enterURL">Enter a URL</ion-option> <ion-option value="enterresults">Enter the Results</ion-option> <ion-option value="location">Location Check-in</ion-option> </ion-select> </ion-item> <ion-item> <ion-label stacked>Describe How To Prove Completion (Optional)</ion-label> <ion-input [ngFormControl]="challengeform.controls['proofdescription']" type="text" placeholder="Take a picture at the finish line!"> </ion-input> </ion-item> </ion-list> <!-- SOCIAL AND REWARDS --> <div class="color-white general-padding">SOCIAL & REWARDS</div> <ion-list> <ion-item> <ion-label stacked>Challenge Privacy</ion-label> <ion-select [ngFormControl]="challengeform.controls['privacy']"> <ion-option value="private" checked="true">Private</ion-option> <ion-option value="public">Public</ion-option> </ion-select> </ion-item> <ion-item> <ion-label stacked>Reward</ion-label> <ion-select [ngFormControl]="challengeform.controls['reward']"> <ion-option value="100P" checked="true">100P</ion-option> <ion-option value="250P">250P</ion-option> <ion-option value="500P">500P</ion-option> <ion-option value="1000P">1000P</ion-option> <ion-option value="all">All my Podiims</ion-option> </ion-select> </ion-item> <!-- COMPETITORS --> <div class="color-white general-padding">COMPETITORS</div> <div *ngFor="#result of everyperson; #i = index"> <choosechallenger [feedinfo]="result"></choosechallenger> </div> <ion-item> <ion-label stacked>Socialize (Optional)</ion-label> <ion-select [ngFormControl]="challengeform.controls['socialize']" multiple="true"> <ion-option value="none" checked="true">None</ion-option> <ion-option value="twitter">Twitter</ion-option> <ion-option value="facebook">Facebook</ion-option> </ion-select> </ion-item> <ion-row center> <ion-col width-20> <ion-checkbox [ngFormControl]="challengeform.controls['readterms']" class="checkbox-padding"></ion-checkbox> </ion-col> <ion-col> <span class="usertitle">I agree with the</span> <span class="linktext" (click)="openSafetyTerms()">Terms of Safety</span> </ion-col> </ion-row> </ion-list> <div class="buttonwrap text-center"> <button outline round type="submit" class="btn-full">Submit</button> </div> <div class="buttonwrap text-center"> <button (click)="openActiveChallengePage()" outline round type="button" class="btn-full">Active Challenge</button> </div> </form> </div> </ion-content>
<!DOCTYPE html> <html> <head> <!--Import Google Icon Font--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!--Import materialize.css--> <link type="text/css" rel="stylesheet" href="css/materialize.min.css" media="screen,projection"/> <link rel="stylesheet" type="text/css" href="css/style.css"> <!--Let browser know website is optimized for mobile--> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <title>Company Profile - PT.Pengen Makmur</title> </head> <body> <!-- Navbar --> <div class="navbar-fixed"> <nav class="teal darken-4"> <div class="container"> <div class="nav-wrapper"> <a href="#!" class="brand-logo">EA</a> <a href="#" data-target="mobile-nav" class="sidenav-trigger"><i class="material-icons">menu</i></a> <ul class="right hide-on-med-and-down"> <li><a href="#about">About Us</a></li> <li><a href="#clients">Clients</a></li> <li><a href="#services">Services</a></li> <li><a href="#portfolio">Portfolio</a></li> <li><a href="#contact">Contact Us</a></li> </ul> </div> </div> </nav> </div> <!-- sidenav --> <ul class="sidenav" id="mobile-nav"> <li><a href="#about">About Us</a></li> <li><a href="#clients">Clients</a></li> <li><a href="#services">Services</a></li> <li><a href="#portfolio">Portfolio</a></li> <li><a href="#contact">Contact Us</a></li> </ul> <!-- slider --> <div class="slider"> <ul class="slides"> <li> <img src="img/slider/1.png"> <div class="caption center-align"> <h3>Menjadi kaya itu mudah!</h3> <h5 class="light grey-text text-lighten-3">Here's our small slogan.</h5> </div> </li> <li> <img src="img/slider/2.png"> <div class="caption right-align"> <h3>Kalian percaya itu?</h3> <h5 class="light grey-text text-lighten-3">Here's our small slogan.</h5> </div> </li> <li> <img src="img/slider/4.png"> <div class="caption left-align"> <h3>Mudah saja kalo kita berusaha.</h3> <h5 class="light grey-text text-lighten-3">Here's our small slogan.</h5> </div> </li> </ul> </div> <!-- about us --> <section id="about" class="about scrollspy"> <div class="container"> <div class="row"> <h3 class="center">About Us</h3> <div class="col m6"> <h5>Saya Seorang Professional</h5> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p> </div> <div class="col m6"> <p>Accounting</p> <div class="progress"> <div class="determinate" style="width: 95%"></div> </div> <p>Web Development</p> <div class="progress"> <div class="determinate" style="width: 85%"></div> </div> <p>Design Grafis</p> <div class="progress"> <div class="determinate" style="width: 90%"></div> </div> </div> </div> </section> <!-- clients --> <div id="clients" class="parallax-container scrollspy"> <div class="parallax"><img src="img/slider/3.png"></div> <div class="container clients "> <h3 class="center light white-text">Our Clients</h3> <div class="row"> <div class="col m4 s12 center"> <img src="img/clients/traveloka.png"> </div> <div class="col m4 s12 center"> <img src="img/clients/tokopedia.png"> </div> <div class="col m4 s12 center"> <img src="img/clients/gojek.png"> </div> </div> <div class="row"> <div class="col m4 s12 center "> <img src="img/clients/shopee.png"> </div> <div class="col m4 s12 center mt"> <img src="img/clients/yt.png"> </div> <div class="col m4 s12 center"> <img src="img/clients/tiktok.png"> </div> </div> </div> </div> <!-- service --> <section id="services" class="services grey lighten-3 scrollspy"> <div class="container"> <div class="row"> <h3 class="light center grey-text text-darken-3">Our Services</h3> <div class="col m4 s12"> <div class="card-panel center"> <i class="material-icons medium">assignment</i> <h5>Accounting</h5> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore </p> </div> </div> <div class="col m4 s12"> <div class="card-panel center"> <i class="material-icons medium">desktop_mac</i> <h5>Web Development</h5> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore </p> </div> </div> <div class="col m4 s12"> <div class="card-panel center"> <i class="material-icons medium">format_color_fill</i> <h5>Design Grafis</h5> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore </p> </div> </div> </div> </div> </section> <!-- portfolio --> <section id="portfolio" class="portfolio scrollspy"> <div class="container" > <h3 class="light center grey-text text-darken-3">Portfolio</h3> <div class="row "> <div class="col m3 s12"> <img src="img/portfolio/5.png" class="responsive-img materialboxed"> </div> <div class="col m3 s12"> <img src="img/portfolio/4.png" class="responsive-img materialboxed"> </div> <div class="col m3 s12"> <img src="img/portfolio/3.png" class="responsive-img materialboxed"> </div> <div class="col m3 s12"> <img src="img/portfolio/6.png" class="responsive-img materialboxed"> </div> </div> <div class="row " > <div class="col m3 s12"> <img src="img/portfolio/1.png" class="responsive-img materialboxed"> </div> <div class="col m3 s12"> <img src="img/portfolio/2.png" class="responsive-img materialboxed"> </div> <div class="col m3 s12"> <img src="img/portfolio/4.png" class="responsive-img materialboxed"> </div> <div class="col m3 s12"> <img src="img/portfolio/5.png" class="responsive-img materialboxed"> </div> </div> </div> </section> <!-- contact --> <section id="contact" class="contact grey text-lighten-3 scrollspy"> <div class="container"> <h3 class="light grey-text text-darken-3 center" >Contact Us</h3> <div class="row"> <div class="col m5 s12"> <div class="card-panel teal darken-2 center white-text"> <i class="material-icons">call</i> <h5>Contact</h5> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor </p> </div> <ul class="collection with-header"> <li class="collection-header"><h5>Our Office</h5></li> <li class="collection-item">PT.Pengen Makmur</li> <li class="collection-item">Jl. Masihsetia N0. 21, Gresik</li> <li class="collection-item">Jawa Timur, Indonesia.</li> </ul> </div> <div class="col m7 s12"> <form> <div class="card-panel"> <h5>Tolong isi Form di bawah ini.</h5> <div class="input-field"> <input type="text" name="name" id="name" required class="validate"> <label for="name">Nama</label> </div> <div class="input-field"> <input type="email" name="email" id="email" class="validate"> <label for="email">Email</label> </div> <div class="input-field"> <input type="text" name="phone" id="phone"> <label for="phone">Telepon</label> </div> <textarea name="message" id="message" class="materialize-textarea"></textarea> <label for="message">Pesan</label> <div> <button type="submit" class="btn">Kirim</button> </div> </div> </form> </div> </div> </div> </section> <!-- footer --> <footer class="teal darken-2 white-text center"> <p>PT. Pengen Makmur. Copyright 2022.</p> </footer> <!--JavaScript at end of body for optimized loading--> <script type="text/javascript" src="js/materialize.min.js"></script> <!-- javascript --> <script> const sideNav = document.querySelectorAll('.sidenav'); M.Sidenav.init(sideNav); const slider = document.querySelectorAll('.slider'); M.Slider.init(slider, { interval: 2000 }); const parallax = document.querySelectorAll('.parallax'); M.Parallax.init(parallax); const materialbox = document.querySelectorAll('.materialboxed'); M.Materialbox.init(materialbox); const scroll = document.querySelectorAll('.scrollspy'); M.Scrollspy.init(scroll, { scrolloffset: 10 }); </script> </body> </html>
<?php namespace App\DB\Core; use app\Db\Core\ParentField; use App\Exceptions\ErrorException; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Config; use illuminate\Database\Eloquent\Model; use Illuminate\Database\QueryException; use Illuminate\Support\Facades\Storage; use Illuminate\Database\Eloquent\ModelNotFoundException; class Crud { public function __construct( private Model $model, private ?array $data, private ?int $id, private $editMode, private $deleteMode, private ?string $updateColumnField = 'id', private ?string $imageField = 'image', ) { $this->model = $model; $this->data = $data; $this->id = $id; $this->editMode = $editMode; $this->deleteMode = $deleteMode; self::$tableName = $model->getTable(); } public static string $imageDirectory = ''; public static string $tableName = ''; public static string $diskName = ''; private ?Model $record = null; public function setImageDirectory(string $directoryPath, string $tablename, string $diskName) { self::$imageDirectory = $directoryPath; self::$tableName = $tablename; self::$diskName = $diskName; } public function getData(string $model, string $id) { $modelInstance = new $model; return $modelInstance->findOrFail($id); } public function execute(): mixed { try { if ($this->editMode) { return $this->handleEditMode(); } elseif ($this->deleteMode) { return $this->handleDeleteMode(); } else { return $this->handleStoreMode(); } } catch (QueryException $e) { return response($e->getMessage()); } } protected function iterateData(array $data, ?Model $record = null): Model { $target = $record ?? $this->model; foreach ($data as $column => $value) { $target->{$column} = $this->savableField($column)->setValue($value)->execute(); } return $target; } protected function handleStoreMode(): Model { if ($this->data) { $this->model = $this->iterateData($this->data, null); if ($this->model->save()) { return $this->model; } // else { // return response(status: 500); // } } } protected function handleEditMode(): Model { try{ $this->record = $this->model->where($this->updateColumnField,$this->id)->first(); }catch(ModelNotFoundException){ throw ErrorException::recordNotFoundCode(Config::get('variables.ERROR_MESSAGES.NOT_FOUND_RECORD')); } if ($this->record?->{$this->imageField}) { $this->deleteImage($this->imageField); } // if ($this->model->getTable() === 'products' || $this->model->getTable() === 'profiles' || $this->model->getTable() === 'users' || $this->model->getTable() === 'company') { // $this->deleteImage(); // } if ($this->data) { $record = $this->iterateData($this->data, $this->record); return $record->save() ? $record : response(status: 500); // return $record->save() ? $this->record : response(status: 500); } } protected function handleDeleteMode() { try { $this->record = $this->model->findOrFail($this->id); // dd($this->model->getTable()); if ($this->model->getTable() === 'expenses') { $this->deleteImage('invoice_slip '); } return $this->record->delete() ? true : false; } catch (ModelNotFoundException) { throw ErrorException::recordNotFoundCode(Config::get('variables.ERROR_MESSAGES.NOT_FOUND_RECORD')); } } public function savableField($column): ParentField { return $this->model->saveableFields()[$column]; } public function deleteImage($image = 'image'): bool { $old_image = $this->record->$image; return $old_image ? Storage::disk('spaces')->delete($old_image) : false; } public static function storeImage($value, $imageDirectory, $imageName, $diskName) { return $value->storeAs($imageDirectory, $imageName, $diskName); } }
<# .SYNOPSIS .DESCRIPTION .LINK .NOTES // Module : [FightingEntropy()][2023.8.0] \\ \\ Date : 2023-08-08 14:30:04 // FileName : Get-MDTModule.ps1 Solution : [FightingEntropy()][2023.8.0] Purpose : Retrieves the location of the main MDTToolkit.psd file, and installs (MDT/WinADK/WinPE) if they are not present Author : Michael C. Cook Sr. Contact : @mcc85s Primary : @mcc85s Created : 2023-04-05 Modified : 2023-08-08 Demo : N/A Version : 0.0.0 - () - Finalized functional version 1 TODO : N/A .Example #> Function Get-MdtModule { Enum MdtDependencyType { Mdt WinAdk WinPe } Class MdtDependencyItem { [UInt32] $Index [String] $Name [String] $DisplayName [Version] $Version [String] $Resource [String] $Path [String] $File [String] $Arguments [UInt32] $IsInstalled MdtDependencyItem([String]$Name) { $This.Index = [UInt32][MdtDependencyType]::$Name $This.Name = [MdtDependencyType]::$Name } Load([String[]]$List) { $This.DisplayName = $List[0] $This.Version = $List[1] $This.Resource = $List[2] $This.Path = $List[3] $This.File = $List[4] $This.Arguments = $List[5] } [String] FilePath() { Return "{0}\{1}" -f $This.Path, $This.File } [String] ToString() { Return $This.Name } } Class MdtDependencyController { Hidden [Object] $Registry Hidden [UInt32] $Status [Object] $Output MdtDependencyController() { $This.GetStatus() } [Object] MdtDependencyItem([String]$Name) { Return [MdtDependencyItem]::New($Name) } Clear() { $This.Output = @( ) } Refresh() { $This.Clear() $Arch = $This.Arch() $This.Registry = $This.RegistryString() | Get-ItemProperty ForEach ($Name in [System.Enum]::GetNames([MdtDependencyType])) { $Item = $This.MdtDependencyItem($Name) $X = Switch ($Name) { Mdt { "Microsoft Deployment Toolkit", "6.3.8450.0000", "https://download.microsoft.com/download/3/3/9/339BE62D-B4B8-4956-B58D-73C4685FC492/MicrosoftDeploymentToolkit_x$Arch.msi", "$Env:ProgramData\Tools\Mdt", "MicrosoftDeploymentToolkit_x$Arch.msi", "/quiet /norestart" } WinAdk { "Windows Assessment and Deployment Kit", "10.1.17763.1", "https://go.microsoft.com/fwlink/?linkid=2086042", "$Env:ProgramData\Tools\WinAdk", "winadk1903.exe", "/quiet /norestart /log $Env:temp\winadk.log /features +" } WinPe { "Windows Preinstallation Environment", "10.1.17763.1", "https://go.microsoft.com/fwlink/?linkid=2087112", "$Env:ProgramData\Tools\WinPe", "winpe1903.exe", "/quiet /norestart /log $Env:temp\winpe.log /features +" } } $Item.Load($X) $This.Output += $Item } } [UInt32] Arch() { Return @{x86 = 86; AMD64 = 64 }[$Env:Processor_Architecture] } [String[]] RegistryString() { Return "", "\WOW6432Node" | % { "HKLM:\Software$_\Microsoft\Windows\CurrentVersion\Uninstall\*" } } GetStatus() { $This.Status = 0 If ($This.Output.Count -eq 0) { $This.Refresh() } ForEach ($Item in $This.Output) { $Package = $This.Registry | ? DisplayName -match $Item.DisplayName $Item.IsInstalled = !!$Package } If (0 -notin $This.Output.IsInstalled) { $This.Status = 1 } } Install() { $This.GetStatus() $List = $This.Output | ? IsInstalled -eq 0 If ($List.Count -gt 0) { [Net.ServicePointManager]::SecurityProtocol = 3072 ForEach ($Item in $List) { If (![System.IO.Directory]::Exists($Item.Path)) { [System.IO.Directory]::Create($Item.Path) } If (![System.IO.File]::Exists($Item.FilePath())) { Invoke-RestMethod -URI $Item.Resource -OutFile $Item.FilePath() } $Process = Start-Process -FilePath $Item.FilePath() -ArgumentList $Item.Arguments -PassThru While (!$Process.HasExited) { For ($X = 0; $X -le 100; $X++) { Write-Progress -Activity "[Installing] @: $($Item.Name)" -PercentComplete $X Start-Sleep -Milliseconds 50 } } $Item.IsInstalled ++ } } } [String] InstallPath() { $RegPath = "HKLM:\Software\Microsoft\Deployment 4" If (Test-Path $RegPath) { Return Get-ItemProperty $RegPath | % Install_Dir | % TrimEnd \ } Else { Return $Null } } MdtModXml() { If ($This.Status) { $Module = Get-FEModule -Mode 1 $Install = $This.InstallPath() ForEach ($File in $Module.GetFolder("Control").Item | ? Name -match mod.xml) { [System.IO.File]::Copy($File.Fullname,"$Install\Templates\$($File.Name)") } } } [String] ToolkitPath() { Return $This.InstallPath() | Get-ChildItem -Filter *Toolkit.psd1 -Recurse | % FullName } [String] ToString() { Return "<FEModule.MdtDependency[Controller]>" } } [MdtDependencyController]::New() }
@php use App\Models\User; $notifikasiCount = count( User::with('notifikasi') ->where('id', auth()->user()->id) ->first() ->notifikasi->where('mark', 'false'), ); // $notifikasiCount = 5 @endphp <nav class="navbar navbar-expand-lg navbar-absolute fixed-top navbar-transparent"> <div class="container-fluid"> <div class="navbar-wrapper"> <div class="navbar-toggle"> <button type="button" class="navbar-toggler"> <span class="navbar-toggler-bar bar1"></span> <span class="navbar-toggler-bar bar2"></span> <span class="navbar-toggler-bar bar3"></span> </button> </div> <a class="navbar-brand" href="javascript:;">{{$title}}</a> </div> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navigation" aria-controls="navigation-index" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-bar navbar-kebab"></span> <span class="navbar-toggler-bar navbar-kebab"></span> <span class="navbar-toggler-bar navbar-kebab"></span> </button> <div class="collapse navbar-collapse justify-content-end" id="navigation"> <ul class="navbar-nav"> <li class="nav-item btn-rotate dropdown"> <a class="nav-link dropdown-toggle" id="get-data" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="nc-icon nc-bell-55"></i> <p> <span class="badge bg-primary" id="notif-number" style="color: white;">{{ $notifikasiCount }}</span> </p> </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="get-data"> <div id="data"></div> {{-- <a class="dropdown-item" href="#">Another action</a> <a class="dropdown-item" href="#">Something else here</a> --}} </div> </li> <li class="nav-item"> <form role="form" method="post" action="{{ route('logout') }}" id="logout-form"> @csrf {{-- <a class="nav-link btn-rotate border-0" type="submit"> <i class="fa fa-sign-out" aria-hidden="true"></i> </a> --}} <a class="nav-link btn-rotate" href="javascript:;" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> <i class="fa fa-sign-out" aria-hidden="true"></i> <p> <span href="{{ route('logout') }}" onclick="" class="d-sm-inline d-none"></span> </p> </a> </form> </li> </ul> </div> </div> </nav> @push('js') <script> $(document).ready(function() { // alert('oke') $('#get-data').click(function() { $.ajax({ url: "{{ route('notifi.mark') }}", type: 'GET', dataType: 'json', success: function(data) { // tampilkan data pada halaman // console.log(data) $('#data').empty() $('#data').html(` <li class="dropdown-header"> pesan terakhir <a href="{{ route('notifikasi') }}" class="text-decoration-none"> <span class="badge rounded-pill bg-primary p-2 ms-2" style="color:white;">View all </span> </a> </li> <li> <hr class="dropdown-divider"></hr> </li> `) if (data.length == 0) $('#data').append( `<li class="notification-item"> <h5 class="mx-auto text-center mt-2">pesan kosong</h4></li>` ) else { $.each(data, async function(index, item) { // console.log(index) var row = $('<li>').addClass( 'd-flex justify-content-between align-items-center' ); if (item.status == 'berhasil') { var i = $('<i>').addClass( 'fa fa-check text-success me-2') } else { var i = $('<i>').addClass( 'fa fa-x-circle text-danger') } var div = $('<div>').addClass('ms-2').css('cursor', 'pointer') var h5 = $('<h6>').addClass( 'font-poppins text-uppercase').text( "tabel " + await item .nama_table); var p = $('<span>').addClass( 'font-poppins font-weight-bold' ).css('font-size', '12px') .text( await item.msg); var hr = $('<hr>').addClass('dropdown-divider'); div.append(h5, p) row.append(i, div) $('#data').append(row, hr) }) } $('#notif-number').html('0') }, error: function(data) { // tampilkan pesan error pada halaman // console.log(data) } }); }); }); </script> @endpush
import numpy as np class OptionPricing: def __init__(self, S0, E, T, rf, sigma, iterations): self.S0 = S0 self.E = E self.T = T self.rf = rf self.sigma = sigma self.iterations = iterations def call_option_simulation(self): # 2 columns: the first column will store 0s and the second column will store the payoff # we need the first column of 0s: payoff function is max(0, S-E) for call option option_data = np.zeros([self.iterations, 2]) # dimensions: 1 dimensional array with as many items as the iterations rand = np.random.normal(0, 1, [1, self.iterations]) # equation for the S(t) stock price stock_price = self.S0 * np.exp(self.T * (self.rf - 0.5 * self.sigma ** 2) + self.sigma * np.sqrt(self.T) * rand) # need S-E to calculate the max(S-E, 0) option_data[:, 1] = stock_price - self.E # average for the Monte Carlo simulation # max() returns the max (0, S-E) according to the formula # THIS IS THE AVERAGE VALUE average = np.sum(np.amax(option_data, axis=1)) / float(self.iterations) # have to use the exp(-rT) discount factor return np.exp(-1.0*self.rf*self.T)*average def put_option_simulation(self): # 2 columns: the first column will store 0s and the second column will store the payoff # need the first column of 0s: payoff function is max(0, E-S) for call option option_data = np.zeros([self.iterations, 2]) # dimensions: 1 dimensional array with as many items as the iterations rand = np.random.normal(0, 1, [1, self.iterations]) # equation for the S(t) stock price stock_price = self.S0 * np.exp(self.T * (self.rf - 0.5 * self.sigma ** 2) + self.sigma * np.sqrt(self.T) * rand) # we need S-E because we have to calculate the max(E-S, 0) option_data[:, 1] = self.E - stock_price # average for the Monte Carlo simulation # max() returns the max (0, E-S) according to the formula # THIS IS THE AVERAGE VALUE average = np.sum(np.amax(option_data, axis=1)) / float(self.iterations) # use the exp(-rT) discount factor return np.exp(-1.0 * self.rf * self.T) * average if __name__ == '__main__': model = OptionPricing(100, 100, 1, 0.05, 0.2, 10000) print('Value of the call option is $%.2f' % model.call_option_simulation()) print('Value of the put option is $%.2f' % model.put_option_simulation())
// // CategoryViewController.swift // RealmDB // // Created by deniss.lobacs on 15/04/2022. // import UIKit //import RealmSwift class CategoryViewController: UIViewController { private var tableView = UITableView() private var viewModel: CategoryViewModel? override func viewDidLoad() { super.viewDidLoad() configTable() configNavigationItems() viewModel?.load() } } //MARK: - CategoryViewController Settings extension CategoryViewController { func configTable() { view.addSubview(tableView) tableView.frame = view.bounds tableView.delegate = self tableView.dataSource = self tableView.register(UINib(nibName: "CategoryCell", bundle: nil), forCellReuseIdentifier: "categoryCell") } func configure(viewModel: CategoryViewModel) { self.viewModel = viewModel } func configNavigationItems() { navigationItem.title = "Todoey" navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addButtonPressed)) } //MARK: - Add new category @objc func addButtonPressed() { presentSearchAlertController(withTitle: "Add New Category", message: "", style: .alert) { [weak self] item in guard let self = self else { return } let newCategory = Category() newCategory.name = item self.viewModel?.save(category: newCategory) self.tableView.reloadData() } } } //MARK: - TableView DataSource extension CategoryViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel?.getCategoriesCount() ?? 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "categoryCell", for: indexPath) as? CategoryCell, let category = viewModel?.getCategories(index: indexPath.row) else { return .init() } // cell.categoryName.text = viewModel?.getCategories(index: indexPath.row)?.name ?? "No categories added" cell.configCell(category) return cell } } //MARK: - TableView Delegate extension CategoryViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 70 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let category = viewModel?.getCategories(index: indexPath.row) else { return } viewModel?.shouldGoToToDoListViewController(with: category) } func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { return .delete } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { guard let category = viewModel?.getCategories(index: indexPath.row) else { return } viewModel?.delete(category: category) tableView.deleteRows(at: [indexPath], with: .fade) tableView.reloadData() } } }
import React from 'react' import ReactDOM from 'react-dom' import { useDispatch } from 'react-redux' import { fetchDeletedProject } from '../../store/projectsSlice' import Transition from '../project/SideBarTransition' function DeleteProjectModal({ show, onClose, projectId }) { const dispatch = useDispatch() const deleteOrg = () => { dispatch(fetchDeletedProject(projectId)) onClose() } return show ? ReactDOM.createPortal( <div className="justify-center items-center flex flex-col overflow-x-hidden overflow-y-auto fixed inset-0 z-50 outline-none focus:outline-none -top-60"> <Transition appear={true} show={show} enter="transition-opacity duration-300" enterFrom="opacity-0" enterTo="opacity-75" leave="transition-opacity duration-300" leaveFrom="opacity-75" leaveTo="opacity-0" > <div className="fixed inset-0 bg-black opacity-0" /> </Transition> <div className="relative w-100 h-40 my-6 mx-auto "> <div className="rounded-lg shadow-lg relative flex flex-col w-full bg-white dark:bg-gray-900 outline-none focus:outline-none"> <button type="button" className=" flex justify-end mr-3 focus:outline-none" data-dismiss="modal" aria-label="Close" onClick={onClose} > <span className=" flex justify-end outline-none m-2" aria-hidden="true" > &times; </span> </button> <div className="flex-col items-start p-5 rounded-lg"> <h6 className="text-md tracking-wide mb-2 text-center"> Are you sure you want to delete this project? <br /> You cannot undo this action. </h6> <div className="flex items-center justify-center py-3"> <button className="bg-red-500 dark:bg-gray-600 text-white hover:bg-red-700 dark:text-gray-300 rounded-lg dark:hover:bg-red-500 mx-2 px-3 py-1 text-base shadow-sm" type="button" onClick={deleteOrg} > Delete </button> <button className="bg-skyblue dark:bg-gray-600 text-white hover:bg-navyblue dark:text-gray-300 rounded-lg dark:hover:bg-skyblue mx-2 px-3 py-1 text-base shadow-sm" type="button" onClick={onClose} > Cancel </button> </div> </div> </div> </div> </div>, document.getElementById('projectDeleteModal') ) : null } export default DeleteProjectModal
@extends('layout/cms_base') @section('title', $course->name) @section('page-title', $course->name) @if(session('success')) @section('alert-success-content') {{ session('success')['message'] }} @endsection @endif @if(session('error')) @section('alert-error-content') {{ session('error')['message'] }} @endsection @endif @section('back') <a href="{{ route('course.index') }}" class="hover:bg-slate-100 rounded-md"> <svg class="fill-current w-7 h-7 " viewBox="0 0 48 48"> <path d="M26.95 34.9L17.05 25C16.8833 24.8333 16.7666 24.6667 16.7 24.5C16.6333 24.3333 16.6 24.15 16.6 23.95C16.6 23.75 16.6333 23.5667 16.7 23.4C16.7666 23.2333 16.8833 23.0667 17.05 22.9L27 12.95C27.3 12.65 27.6583 12.5 28.075 12.5C28.4916 12.5 28.85 12.65 29.15 12.95C29.45 13.25 29.5916 13.6167 29.575 14.05C29.5583 14.4833 29.4 14.85 29.1 15.15L20.3 23.95L29.15 32.8C29.45 33.1 29.6 33.45 29.6 33.85C29.6 34.25 29.45 34.6 29.15 34.9C28.85 35.2 28.4833 35.35 28.05 35.35C27.6166 35.35 27.25 35.2 26.95 34.9Z"></path> </svg> </a> @endsection @section('content') <main class="w-full flex flex-col space-y-6 px-8 py-4"> <div class="w-full flex flex-col space-y-6"> <div class="flex flex-row items-center space-x-4"> <p class="w-40">Course Name</p> <p>:</p> <p class="w-96 font-medium">{{ $course->name }}</p> </div> <div class="flex flex-row items-center space-x-4"> <p class="w-40">Course Lecturer</p> <p>:</p> <p class="w-96 font-medium">{{ $course->lecturer->name }} (<a class="text-blue-700 cursor-pointer" href="mailto:{{ $course->lecturer->email }}">Mail</a>)</p> </div> <div class="flex flex-row items-center space-x-4"> <p class="w-40">Mode</p> <p>:</p> <p class="font-medium w-fit px-2 rounded-md {{ $course->mode == 'edit' ? 'text-blue-700 bg-blue-100' : 'text-green-700 bg-green-100' }}">{{ $course->mode == 'edit' ? 'Draft' : 'Published' }}</p> </div> <div class="flex flex-row items-center space-x-4"> <p class="w-40">Course Schedule</p> <p>:</p> <p class="w-96 font-medium">{{ $course->start_date->format('d F Y') }} -> {{ $course->end_date->format('d F Y') }}</p> </div> <div class="flex flex-row space-x-4"> <p class="w-40">Course Description</p> <p>:</p> <p class="w-96">{{ $course->description }}</p> </div> </div> <div class="w-full flex flex-col space-y-8"> <div class="w-full flex items-center"> <h3 class="text-2xl font-medium">Content</h3> @if($course->mode == 'edit') <a href="{{ route('course.create_content_view', [ 'id' => $course->id ]) }}" class="text-center px-3 py-2 rounded-md bg-slate-700 hover:bg-slate-800 active:bg-slate-900 text-white ml-auto">Create Content</a> @endif </div> <table class="border-collapse"> <thead> <tr> <th class="border px-2 py-2.5">#</th> <th class="border px-2 py-2.5">Title</th> <th class="border px-2 py-2.5">Description</th> <th class="border px-2 py-2.5">Document</th> <th class="border px-2 py-2.5">Handle</th> </tr> </thead> <tbody> @if (count($course->contents) == 0) <tr> <td colspan="6" class="border px-2 py-2.5 align-middle text-center text-slate-500">Data doesn't exist!</td> </tr> @endif @foreach($course->contents as $i => $content) <tr> <td class="border px-2 py-2.5">{{ ($i + 1) }}</td> <td class="border px-2 py-2.5">{{ $content->name }}</td> <td class="border px-2 py-2.5">{{ $content->description }}</td> <td class="border px-2 py-2.5 align-middle text-center"> @if($content->filename) <a target="_blank" class="text-blue-700" href="{{ route('file.show_pdf', ['filename' => $content->filename ]) }}">Open Content</a> @endif </td> <td class="border px-2 py-2.5"> <div class="flex justify-center space-x-2 text-black"> @if($course->mode == 'edit') <a href="{{ route('course.update_content_view', [ 'id' => $course->id, 'content_id' => $content->id ]) }}" class="block px-3 py-2 rounded-md border border-slate-400 w-fit hover:cursor-pointer hover:bg-slate-100">Edit</a> <button data-modal-target="popup-delete-course-content-{{ $content->id }}" data-modal-toggle="popup-delete-course-content-{{ $content->id }}" class="block px-3 py-2 rounded-md border border-red-400 w-fit hover:cursor-pointer hover:bg-red-100">Delete</button> @endif </div> </td> <div id="popup-delete-course-content-{{ $content->id }}" tabindex="-1" class="fixed top-0 left-0 right-0 z-50 hidden p-4 overflow-x-hidden overflow-y-auto md:inset-0 h-[calc(100%-1rem)] max-h-full"> <div class="relative w-full max-w-md max-h-full"> <div class="relative bg-white rounded-lg shadow dark:bg-slate-700"> <button type="button" class="absolute top-3 right-2.5 text-slate-400 bg-transparent hover:bg-slate-200 hover:text-slate-900 rounded-lg text-sm w-8 h-8 ml-auto inline-flex justify-center items-center dark:hover:bg-slate-600 dark:hover:text-white" data-modal-hide="popup-delete-course-content-{{ $content->id }}"> <svg class="w-3 h-3" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 14 14"> <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6" /> </svg> <span class="sr-only">Close modal</span> </button> <div class="p-6 text-center"> <svg class="mx-auto mb-4 text-red-600 w-12 h-12" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 20 20"> <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 11V6m0 8h.01M19 10a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" /> </svg> <h3 class="mb-8 font-normal">Apakah kamu yakin untuk menghapus content dengan judul <span class="font-semibold">{{ $content->name }}</span>?</h3> <form method="POST" action="{{ route('course.delete_content', ['id' => $course->id]) }}"> @csrf <input type="hidden" value="{{ $content->id }}" name="id"> <button data-modal-hide="popup-delete-course-content-{{ $content->id }}" type="submit" class="text-white bg-red-600 hover:bg-red-700 focus:ring-4 focus:outline-none focus:ring-red-300 dark:focus:ring-red-800 rounded-lg text-sm inline-flex items-center px-5 py-2.5 text-center mr-2"> Yes </button> </form> <button data-modal-hide="popup-delete-course-content-{{ $content->id }}" type="button" class="text-center px-3 py-2 rounded-md border border-slate-400 w-fit hover:cursor-pointer hover:bg-slate-100 text-sm">No, Cancel</button> </div> </div> </div> </div> </tr> @endforeach </tbody> </table> </div> </main> @endsection
import { useContext } from 'react'; import { useNavigate } from 'react-router-dom'; import {ShopContext} from '../components/ShopContext'; import { Products } from '../components/Products'; import { CartItem } from '../components/CartItem'; import style from "./style.css"; // Kundvagn med alla produkter som lagts till export const Cart = () => { const {cart, getTotalCartAmount, checkout, emptyAllProductsFromCart} = useContext(ShopContext); const cartCount = getTotalCartAmount(); const navigate = useNavigate(); // nedan kod kollar om 1. om det finns produkter (som har id) i kundvagnen och mappad ut dem isåfall. Om cartcount är mer än 0 dvs har produkter i sig så visas kundvagnen annars att kundvagnen är tom. return( <div className="cart"> <div className='items-in-Cart'> {Products.map((product) => { if (cart[product.id] !== 0) { return <CartItem data={product} />; } })} </div> {cartCount > 0 ? ( <div className="checkout"> <div> <h1>Your Cart Items</h1> </div> <p> Subtotal: ${cartCount} </p> <button onClick={() => navigate("/")}> Continue Shopping </button> <button onClick={() => { checkout(); navigate("/"); }} > {" "} Checkout{" "} </button> <button onClick={()=> { emptyAllProductsFromCart(); navigate("/") }}> Clear Cart </button> </div> ) : ( <h1> Your Shopping Cart is Empty</h1> )} </div>) }
package com.github.kackan1.springboot.controller; import com.github.kackan1.springboot.model.Task; import com.github.kackan1.springboot.model.TaskRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationEventPublisher; import org.springframework.data.domain.Pageable; import org.springframework.http.ResponseEntity; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.net.URI; import java.util.List; @RestController @RequestMapping(value = "/tasks") class TaskController { private static final Logger logger = LoggerFactory.getLogger(TaskController.class); private final ApplicationEventPublisher eventPublisher; private final TaskRepository repository; TaskController(final TaskRepository repository, final ApplicationEventPublisher eventPublisher) { this.eventPublisher = eventPublisher; this.repository = repository; } @PostMapping ResponseEntity<Task> createTask(@RequestBody @Valid Task toCreate) { Task result = repository.save(toCreate); return ResponseEntity.created(URI.create("/" + result.getId())).body(result); } @GetMapping(params = { "!sort", "!page", "!size" }) ResponseEntity<List<Task>> readAllTasks() { logger.warn("Exposing all the tasks"); return ResponseEntity.ok(repository.findAll()); } @GetMapping ResponseEntity<List<Task>> readAllTasks(Pageable page) { logger.info("Custom pageable"); return ResponseEntity.ok(repository.findAll(page).getContent()); } @GetMapping("/{id}") ResponseEntity<Task> readTask(@PathVariable int id) { return repository.findById(id) .map(task -> ResponseEntity.ok(task)) .orElse(ResponseEntity.notFound().build()); } @GetMapping(value = "/search/done") ResponseEntity<List<Task>> readDoneTasks(@RequestParam(defaultValue = "true") boolean state) { return ResponseEntity.ok(repository.findByDone(state)); } @PutMapping("/{id}") ResponseEntity<?> updateTask(@PathVariable int id, @RequestBody @Valid Task toUpdate) { if (!repository.existsById(id)) { return ResponseEntity.notFound().build(); } repository.findById(id) .ifPresent(task -> { task.updateFrom(toUpdate); repository.save(task); }); return ResponseEntity.noContent().build(); } @Transactional @PatchMapping("/{id}") public ResponseEntity<?> toggleTask(@PathVariable int id) { if (!repository.existsById(id)) { return ResponseEntity.notFound().build(); } repository.findById(id) .map(Task::toggle) .ifPresent(eventPublisher::publishEvent); return ResponseEntity.noContent().build(); } }
package api import ( "errors" "net/http" db "simplebank/db/sqlc" "simplebank/token" "strings" "github.com/gin-gonic/gin" "github.com/jackc/pgx/v5" ) type createAccountRequest struct { Currency string `json:"currency" binding:"required"` } func (server *Server) createAccount(ctx *gin.Context) { var req createAccountRequest if err := ctx.ShouldBindJSON(&req); err != nil { ctx.JSON(http.StatusBadRequest, errorResponse(err)) return } authPayload := ctx.MustGet(authPayloadKey).(*token.Payload) arg := db.CreateAccountParams{ Owner: authPayload.Name, Balance: 0, Currency: req.Currency, } // Use the store to create the account account, err := server.store.CreateAccount(ctx, arg) if err != nil { if strings.Contains(err.Error(), "violates foreign key constraint") { ctx.JSON(http.StatusForbidden, errorResponse(err)) return } ctx.JSON(http.StatusInternalServerError, errorResponse(err)) return } ctx.JSON(http.StatusOK, account) } type getAccountRequest struct { // This parameter comes from the uri ID int64 `uri:"id" binding:"required,min=1"` } func (server *Server) getAccount(ctx *gin.Context) { var req getAccountRequest if err := ctx.ShouldBindUri(&req); err != nil { ctx.JSON(http.StatusBadRequest, errorResponse(err)) return } account, err := server.store.GetAccount(ctx, req.ID) if err != nil { if errors.Is(err, pgx.ErrNoRows) { ctx.JSON(http.StatusNotFound, errorResponse(err)) return } ctx.JSON(http.StatusInternalServerError, errorResponse(err)) return } // If the account donesn't belong to the user, return the error authPayload := ctx.MustGet(authPayloadKey).(*token.Payload) if authPayload.Name != account.Owner { err := errors.New("account doesn't belong to the authenticated user") ctx.JSON(http.StatusUnauthorized, errorResponse(err)) return } ctx.JSON(http.StatusOK, account) } type listAccountRequest struct { PageID int32 `form:"page_id" binding:"required,min=1"` PageSize int32 `form:"page_size" binding:"required,min=5,max=50"` } func (server *Server) listAccounts(ctx *gin.Context) { var req listAccountRequest if err := ctx.ShouldBindQuery(&req); err != nil { ctx.JSON(http.StatusBadRequest, errorResponse(err)) return } authPayload := ctx.MustGet(authPayloadKey).(*token.Payload) arg := db.ListAccountParams{ Owner: authPayload.Name, Limit: req.PageSize, Offset: (req.PageID - 1) * req.PageSize, } accounts, err := server.store.ListAccount(ctx, arg) if err != nil { ctx.JSON(http.StatusInternalServerError, errorResponse(err)) return } ctx.JSON(http.StatusOK, accounts) }
import Shimmer from "./Shimmer"; import { useParams } from "react-router-dom"; import RestaurantCategory from "./RestaurantCategory"; import { useState } from "react"; import useResMenu from "../utils/useResMenu"; import RestaurantCategory from "./RestaurantCategory"; import { useState } from "react"; const RestaurantMenu = () => { const { resId } = useParams(); const [showIndex, setShowIndex] = useState(0); const menu = useResMenu(resId); const { name, cuisines, costForTwo } = menu?.cards[0]?.card?.card?.info ?? {}; const categories = menu?.cards[2]?.groupedCard?.cardGroupMap?.REGULAR?.cards.filter( (c) => c.card?.card?.["@type"] === "type.googleapis.com/swiggy.presentation.food.v2.ItemCategory" ); // console.log(categories); if (menu === null) return <Shimmer />; return ( <div className="m-8 text-center"> <h1 className="text-xl font-bold ">{name}</h1> <p className="text-sm my-2"> {cuisines.join(", ")} - ₹ {costForTwo / 100} </p> {/* Categories accordian */} {categories.map((category, index) => ( <RestaurantCategory data={category?.card?.card} key={index} showItems={index === showIndex} setShowIndex={setShowIndex} index={index} /> ))} </div> ); }; export default RestaurantMenu;
/******************************************************************************* * Copyright (c) MOBAC developers * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package mobac.program.atlascreators; import com.sleepycat.je.DatabaseException; import mobac.exceptions.AtlasTestException; import mobac.exceptions.MapCreationException; import mobac.program.annotations.AtlasCreatorName; import mobac.program.atlascreators.tileprovider.TileProvider; import mobac.program.interfaces.AtlasInterface; import mobac.program.interfaces.MapInterface; import mobac.program.interfaces.MapSource; import mobac.program.model.Settings; import mobac.program.tilestore.berkeleydb.ExportTileDatabase; import mobac.program.tilestore.berkeleydb.TileDbEntry; import mobac.utilities.Utilities; import javax.imageio.ImageIO; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; @AtlasCreatorName(value = "Tile store export", type = "TILE_EXPORT") public class TileStoreExport extends AtlasCreator { protected static final int MAX_BATCH_SIZE = 1000; protected File baseDir = null; protected String currentMapStoreName = null; protected ExportTileDatabase db = null; protected Map<String, ExportTileDatabase> dbs = new HashMap<>(); @Override public void startAtlasCreation(AtlasInterface atlas, File customAtlasDir) throws IOException, AtlasTestException, InterruptedException { if (customAtlasDir == null) customAtlasDir = Settings.getInstance().getAtlasOutputDirectory(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HHmmss"); String atlasDirName = atlas.getName() + "_" + sdf.format(new Date()); super.startAtlasCreation(atlas, customAtlasDir); baseDir = new File(atlasDir, atlasDirName); Utilities.mkDirs(baseDir); } private void closeAll() { for (ExportTileDatabase db : dbs.values()) { if (db != null) { db.close(); db = null; } } dbs.clear(); } @Override public void initializeMap(MapInterface map, TileProvider mapTileProvider) { super.initializeMap(map, mapTileProvider); currentMapStoreName = map.getMapSource().getName(); if (currentMapStoreName.indexOf("street") >= 0) currentMapStoreName = "street"; else if (currentMapStoreName.indexOf("satellite") >= 0) currentMapStoreName = "map"; } @Override public void abortAtlasCreation() throws IOException { closeAll(); super.abortAtlasCreation(); } @Override public void finishAtlasCreation() throws IOException, InterruptedException { closeAll(); super.finishAtlasCreation(); } @Override public boolean testMapSource(MapSource mapSource) { return true; } @Override public void createMap() throws MapCreationException, InterruptedException { try { db = dbs.get(currentMapStoreName); if (db == null) { db = new ExportTileDatabase(currentMapStoreName, new File(baseDir, "db-" + currentMapStoreName)); dbs.put(currentMapStoreName, db); } createTiles(); } catch (IOException | DatabaseException e) { throw new MapCreationException("Error create database: " + e.getMessage(), map, e); } } protected void createTiles() throws InterruptedException, MapCreationException { atlasProgress.initMapCreation((xMax - xMin + 1) * (yMax - yMin + 1)); ImageIO.setUseCache(false); int batchTileCount = 0; for (int x = xMin; x <= xMax; x++) { for (int y = yMin; y <= yMax; y++) { checkUserAbort(); atlasProgress.incMapCreationProgress(); try { byte[] sourceTileData = getTileData(x, y); if (sourceTileData != null) { TileDbEntry entry = new TileDbEntry(x, y, zoom, sourceTileData); db.put(entry); batchTileCount++; if (batchTileCount >= MAX_BATCH_SIZE) { System.gc(); batchTileCount = 0; } } } catch (Exception e) { throw new MapCreationException("Error writing tile image: " + e.getMessage(), map, e); } } } } protected byte[] getTileData(int x, int y) throws Exception{ return mapDlTileProvider.getTileData(x, y); } }
/* eslint-disable react/jsx-no-useless-fragment */ import React from 'react'; import { ComponentStory, ComponentMeta } from '@storybook/react'; import { titles } from '@/constants'; import Modal from './Modal'; import ModalHeader from '@/components/Modal/components/ModalHeader'; import ModalBody from '@/components/Modal/components/ModalBody'; import ModalFooter from '@/components/Modal/components/ModalFooter'; import Button from '@/components/Button/Button'; export default { title: `${titles.layouts}Modal`, component: Modal, } as ComponentMeta<typeof Modal>; const Template: ComponentStory<typeof Modal> = (args) => <Modal {...args} />; export const Standard = Template.bind({}); Standard.args = { open: false, onClose: () => {}, children: ( <> <ModalHeader onClose={() => {}} title="Header" /> <ModalBody> <section className="flex items-center justify-center h-full"> <p>Modal body example</p> </section> </ModalBody> <ModalFooter> <section className="grid gap-4"> <section className="grid gap-3 lg:flex lg:w-[337px] lg:justify-self-end"> <Button type="outlined" width="w-full lg:w-[30%]" onClick={() => {}} > <p className="text-base font-semibold leading-base">Cancel</p> </Button> <Button width="w-full lg:w-[70%]" onClick={() => {}}> <p className="text-base font-semibold leading-base">Apply</p> </Button> </section> </section> </ModalFooter> </> ), }; export const Empty = Template.bind({}); Empty.args = { open: true, onClose: () => {}, children: ( <section className="flex items-center justify-center h-full"> <p>Empty modal without header and footer</p> </section> ), };
import { useState } from 'react'; import Box from '@mui/material/Box'; import Avatar from '@mui/material/Avatar'; import Divider from '@mui/material/Divider'; import Popover from '@mui/material/Popover'; import { alpha } from '@mui/material/styles'; import MenuItem from '@mui/material/MenuItem'; import Typography from '@mui/material/Typography'; import IconButton from '@mui/material/IconButton'; import { account } from '../../../_mock/account'; import { signOut } from 'next-auth/react'; import { SafeUser } from '@/app/types'; // ---------------------------------------------------------------------- const MENU_OPTIONS = [ { label: 'Home', icon: 'eva:home-fill', }, { label: 'Profile', icon: 'eva:person-fill', }, { label: 'Settings', icon: 'eva:settings-2-fill', }, ]; // ---------------------------------------------------------------------- interface AccountProps { currentUser?: SafeUser | null; } const AccountPopover: React.FC<AccountProps> = ({ currentUser }) => { const [open, setOpen] = useState(null); const handleOpen = (event:any) => { setOpen(event.currentTarget); }; const handleClose = () => { setOpen(null); }; return ( <> <IconButton onClick={handleOpen} sx={{ width: 40, height: 40, background: (theme) => alpha(theme.palette.grey[500], 0.08), }} > <Avatar src={currentUser?.image ? currentUser?.image : ''} alt={currentUser?.name ? currentUser?.name : ''} sx={{ width: 36, height: 36, border: (theme) => `solid 2px ${theme.palette.background.default}`, }} > {currentUser?.name ? currentUser?.name.charAt(0).toUpperCase() : ''} </Avatar> </IconButton> <Popover open={!!open} anchorEl={open} onClose={handleClose} anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }} transformOrigin={{ vertical: 'top', horizontal: 'right' }} PaperProps={{ sx: { p: 0, mt: 1, ml: 0.75, width: 200, }, }} > <Box sx={{ my: 1.5, px: 2 }}> <Typography variant="subtitle2" noWrap> {currentUser?.name ? currentUser?.name : ''} </Typography> <Typography variant="body2" sx={{ color: 'text.secondary' }} noWrap> {currentUser?.email ? currentUser?.email : ''} </Typography> </Box> <Divider sx={{ borderStyle: 'dashed' }} /> {MENU_OPTIONS.map((option) => ( <MenuItem key={option.label} onClick={handleClose}> {option.label} </MenuItem> ))} <Divider sx={{ borderStyle: 'dashed', m: 0 }} /> <MenuItem disableRipple disableTouchRipple onClick={()=>{signOut()}} sx={{ typography: 'body2', color: 'error.main', py: 1.5 }} > Logout </MenuItem> </Popover> </> ); } export default AccountPopover;
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <pthread.h> #include <asm-generic/socket.h> #include <fcntl.h> #define PORT 8080 #define MAX_CLIENTS 5 pthread_mutex_t book_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t user_mutex = PTHREAD_MUTEX_INITIALIZER; // Admin credentials (for demonstration purposes) #define ADMIN_USERNAME "admin" #define ADMIN_PASSWORD "adminpass" // User credentials (for demonstration purposes) #define USER_USERNAME "user" #define USER_PASSWORD "userpass" FILE * file; FILE * file1; int num_entries=0; char name[100]; char pwd[100]; struct Entry{ char name[100]; char password[100]; }entries[100]; struct Book{ char name[100]; char author[100]; char quant[100]; }books[100]; typedef struct { char name[100]; int status; // 0 for returned, 1 for borrowed } User; int read_lock(int fd) { struct flock lock; lock.l_type = F_RDLCK; // Set read lock lock.l_whence = SEEK_SET; lock.l_start = 0; // Lock the whole file lock.l_len = 0; // 0 means until EOF if (fcntl(fd, F_SETLKW, &lock) == -1) { perror("fcntl - read lock"); return -1; } return 0; } // Function to acquire a write lock int write_lock(int fd) { struct flock lock; lock.l_type = F_WRLCK; // Set write lock lock.l_whence = SEEK_SET; lock.l_start = 0; // Lock the whole file lock.l_len = 0; // 0 means until EOF if (fcntl(fd, F_SETLKW, &lock) == -1) { perror("fcntl - write lock"); return -1; } return 0; } // Function to unlock int unlock(int fd) { struct flock lock; lock.l_type = F_UNLCK; // Release lock lock.l_whence = SEEK_SET; lock.l_start = 0; // Unlock the whole file lock.l_len = 0; // 0 means until EOF if (fcntl(fd, F_SETLK, &lock) == -1) { perror("fcntl - unlock"); return -1; } return 0; } User users[5]; int num_users = 0; void load_users(){ int fd = open("users.txt", O_RDWR, 0666); FILE *file = fdopen(fd,"r"); //read_lock(fd); if (file == NULL) { perror("fopen"); return; } num_users = 0; while (fscanf(file, "%s %d", users[num_users].name, &users[num_users].status) == 2) { num_users++; if (num_users >= 5) { break; // Prevent overflow } } // unlock(fd); fclose(file); } void save_users() { int fd = open("users.txt", O_RDWR, 0666); FILE *file = fdopen(fd, "w"); //write_lock(fd); if (file == NULL) { perror("fopen"); return; } for (int i = 0; i < num_users; i++) { fprintf(file, "%s %d\n", users[i].name, users[i].status); } // unlock(fd); fflush(file); fclose(file); } void update_user_status(const char *username, int status) { for (int i = 0; i < num_users; i++) { if (strcmp(users[i].name, username) == 0) { users[i].status = status; save_users(); return; } } } // Function to handle admin login int read_books_data() { int num = 0; int fd = open("books.txt", O_RDWR, 0666); FILE *file = fdopen(fd, "r"); read_lock(fd); if (file != NULL) { while (fscanf(file, "%s %s %s", books[num].name, books[num].author, books[num].quant) == 3) { num++; if (num >= 200) { break; // Prevent overflow of books array } } unlock(fd); fclose(file); } return num; } void write_books_data(int num_books) { int fd = open("books.txt", O_RDWR, 0666); write_lock(fd); FILE *file = fdopen(fd, "w"); if (file != NULL) { for (int i = 0; i < num_books; i++) { fprintf(file, "%s %s %s\n", books[i].name, books[i].author, books[i].quant); } unlock(fd); fclose(file); } } int book_exists(char *book_name , int num_books) { for (int i = 0; i < num_books; i++) { if (strcmp(books[i].name,book_name)==0 ) { return 1+i; // Book found } } return 0; // Book not found } void delete_book(const char *book_name,int num_books) { // Find the index of the book to be deleted int index = -1; for (int i = 0; i < num_books; i++) { if (strcmp(books[i].name, book_name) == 0) { index = i; break; } } // If the book is found if (index != -1) { // Shift subsequent books one position back in the array for (int i = index; i < num_books - 1; i++) { strcpy(books[i].name, books[i + 1].name); strcpy(books[i].author, books[i + 1].author); strcpy(books[i].quant, books[i + 1].quant); } num_books--; // Decrement the total number of books } else { printf("Book not found.\n"); } } void delete_book_by_name(const char *book_name) { pthread_mutex_lock(&book_mutex); // Open the file for reading FILE *file = fopen("books.txt", "r"); if (file == NULL) { perror("fopen"); pthread_mutex_unlock(&book_mutex); return; } // Read all books into an array // Assuming a maximum of 1000 books int book_count = 0; char line[512]; while (fgets(line, sizeof(line), file)) { if (sscanf(line, "%s %s %s]", books[book_count].name, books[book_count].author, books[book_count].quant) == 3) { book_count++; } } fclose(file); // Search for the book to be deleted int index_to_delete = -1; for (int i = 0; i < book_count; i++) { if (strcmp(books[i].name, book_name) == 0) { index_to_delete = i; break; } } // If the book is found, remove it from the array if (index_to_delete != -1) { for (int i = index_to_delete; i < book_count - 1; i++) { books[i] = books[i + 1]; } book_count--; // Write the modified array back to the file file = fopen("books.txt", "w"); if (file == NULL) { perror("fopen"); pthread_mutex_unlock(&book_mutex); return; } for (int i = 0; i < book_count; i++) { fprintf(file, "%s %s %s\n", books[i].name, books[i].author, books[i].quant); } fclose(file); printf("Book deleted successfully\n"); } else { printf("Book not found\n%s",book_name); } pthread_mutex_unlock(&book_mutex); } void modify_book_quantity(const char *book_name, const char *new_quantity,int num_books) { // Find the index of the book int index = -1; for (int i = 0; i < num_books; i++) { if (strcmp(books[i].name, book_name) == 0) { index = i; break; } } // If the book is found if (index != -1) { // Update the quantity strcpy(books[index].quant, new_quantity); } else { printf("Book not found.\n"); } } void separate_name_and_quantity(char *combined_str, char *name, char *quantity) { char *token = strtok(combined_str, ":"); if (token != NULL) { strcpy(name, token); } token = strtok(NULL, ":"); if (token != NULL) { strcpy(quantity, token); } } void log_transaction(char *username, char *book_name, char *transaction_type) { FILE *file = fopen("transactions.txt", "a"); if (file == NULL) { perror("fopen"); return; } // Get the current date and time time_t now = time(NULL); struct tm *t = localtime(&now); char timestamp[64]; strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", t); // Write the transaction details to the file fprintf(file, "%s - User: %s, Book: %s, Transaction: %s\n", timestamp, username, book_name, transaction_type); fflush(file); fclose(file); } void view_transactions(int client_socket) { pthread_mutex_lock(&book_mutex); FILE *file = fopen("transactions.txt", "r"); if (file == NULL) { perror("fopen"); pthread_mutex_unlock(&book_mutex); return; } char line[256]; while (fgets(line, sizeof(line), file)) { send(client_socket, line, strlen(line), 0); } fclose(file); pthread_mutex_unlock(&book_mutex); } void handle_admin_login(int client_socket) { char buffer[1024] = {0}; char buffer1[1024] = {0}; char name[1024] = {0}; char author[1024] = {0}; char quant[1024] = {0}; char data[1024] = {0}; //char *welcome_message = "Welcome, Admin!\n"; char *login_prompt = "Please enter your username and password (e.g., username:password): "; // Send welcome message to admin //send(client_socket, welcome_message, strlen(welcome_message), 0); memset(buffer,0,sizeof(buffer)); // Receive login credentials from admin int valread = read(client_socket, buffer, 1024); if (valread <= 0) { close(client_socket); pthread_exit(NULL); } // Verify admin login credentials if (strcmp(buffer, ADMIN_USERNAME ":" ADMIN_PASSWORD) == 0) { // Authentication successful char *success_message = "Authentication successful. You are now logged in as admin.\n"; send(client_socket, success_message, strlen(success_message), 0); while (1) { // Receive message from admin // char *menu = "1.Add Book\n 2.Delete Book\n 3.Modify Books\n 4.See transactions\n 5.View Member details\n 6.Exit\n"; // send(client_socket,menu,strlen(menu),0); int valread2 = read(client_socket, buffer1, 1024); if (valread2 <= 0) { break; // Exit loop if no data received or connection closed } if(strcmp(buffer1,"Add Books")==0){ pthread_mutex_lock(&book_mutex); int num_books=read_books_data(); memset(data,0,sizeof(data)); int valread5 = read(client_socket, data, 1024); char *token = strtok(data, ":"); if (token != NULL) { strncpy(name, token, sizeof(name) - 1); name[sizeof(name) - 1] = '\0'; } token = strtok(NULL, ":"); if (token != NULL) { strncpy(author, token, sizeof(author) - 1); author[sizeof(author) - 1] = '\0'; } token = strtok(NULL, ":"); if (token != NULL) { strncpy(quant, token, sizeof(quant) - 1); quant[sizeof(quant) - 1] = '\0'; } if(book_exists(name,num_books)!=0 && num_books!=0){ char * error = "Book already exists"; send(client_socket,error,strlen(error),0); }else{ strcpy(books[num_books].name,name); strcpy(books[num_books].author,author); strcpy(books[num_books].quant,quant); num_books+=1; write_books_data(num_books); char * no_error = "Book added to database"; send(client_socket,no_error,strlen(no_error),0); memset(buffer1,0,sizeof(buffer1)); memset(name,0,sizeof(name)); memset(author,0,sizeof(author)); memset(author,0,sizeof(author)); } pthread_mutex_unlock(&book_mutex); }else if(strcmp(buffer1,"Delete Book\n")==0){ memset(data,0,sizeof(data)); int valread4=read(client_socket,data,1024); int num_books=read_books_data(); if(book_exists(data,num_books)==0){ char * error = "Book Doesnt Exist in database\n"; send(client_socket,error,1024,0); }else{ //pthread_mutex_lock(&book_mutex); int num_books=read_books_data(); // delete_book(data,num_books); // write_books_data(num_books-1); delete_book_by_name(data); char * no_error = "Book deleted from database\n"; send(client_socket,no_error,1024,0); //pthread_mutex_unlock(&book_mutex); } }else if(strcmp(buffer1,"Modify Book\n")==0){ memset(data,0,sizeof(data)); int valread4=read(client_socket,data,1024); int num_books=read_books_data(); separate_name_and_quantity(data,name,quant); if(book_exists(name,num_books)==0){ char * error = "Book Doesnt Exist in database\n"; send(client_socket,error,1024,0); }else{ pthread_mutex_lock(&book_mutex); modify_book_quantity(name,quant,num_books); write_books_data(num_books); char * no_error = "Book Data Modified\n"; send(client_socket,no_error,1024,0); pthread_mutex_unlock(&book_mutex); } }else if(strcmp(buffer1,"Search For a book\n")==0){ char bname[1024]={0}; int valr=read(client_socket,bname,1024); int num_books=read_books_data(); if(book_exists(bname,num_books)==0){ char * error = "Book not in database\n"; send(client_socket,error,strlen(error),0); }else{ pthread_mutex_lock(&book_mutex); FILE *file = fopen("books.txt", "r"); if (file == NULL) { perror("fopen"); pthread_mutex_unlock(&book_mutex); return; } char line[1024]; int found = 0; while (fgets(line, sizeof(line), file)) { char name[256], author[256], quantity[256]; sscanf(line, "%s %s %s", name, author, quantity); if (strcmp(name,bname)==0) { char comb[1024]; snprintf(comb,sizeof(comb),"BookName:%s Author:%s Quantity:%s",name,author,quantity); send(client_socket,comb, strlen(comb), 0); found = 1; break; } } pthread_mutex_unlock(&book_mutex); } } memset(buffer1, 0, sizeof(buffer1)); } } else { // Authentication failed char *failure_message = "Authentication failed. Invalid username or password.\n"; send(client_socket, failure_message, strlen(failure_message), 0); close(client_socket); pthread_exit(NULL); } } char name_pwd_separate(char input[]){ char *token = strtok(input, ":"); if (token != NULL) { strncpy(name, token, sizeof(name) - 1); name[sizeof(name) - 1] = '\0'; } token = strtok(NULL, ":"); if (token != NULL) { strncpy(pwd, token, sizeof(pwd) - 1); pwd[sizeof(pwd) - 1] = '\0'; } }int get_user_status(char *username) { for (int i = 0; i < num_users; i++) { if (strcmp(users[i].name, username) == 0) { return users[i].status; } } // User not found return -1; // Indicates user not found } // Function to handle user login void handle_user_login(int client_socket) { char buffer[1024] = {0}; char buffer1[1024] = {0}; char *welcome_message = "Welcome, User!\n"; char *login_prompt = "Please enter your username and password (e.g., username:password): "; char username[100]; // Send welcome message to user //send(client_socket, welcome_message, strlen(welcome_message), 0); // Receive login credentials from user int valread = read(client_socket, buffer, 1024); if (valread <= 0) { close(client_socket); pthread_exit(NULL); } int authenticated = 0; for (int i = 0; i < num_entries; i++) { name_pwd_separate(buffer); if (strcmp(name,entries[i].name) == 0 && strcmp(pwd,entries[i].password)==0 ){ strcpy(username,entries[i].name); authenticated = 1; break; } } // Verify user login credentials if (authenticated==1) { // Authentication successful char *success_message = "Authentication successful. You are now logged in as user.\n"; send(client_socket, success_message, strlen(success_message), 0); // Implement user functionality here // For demonstration, let's just echo back user's messages // Handle client communication while (1) { load_users(); // Receive message from user char data[100]; int mode; int valread2 = read(client_socket, &mode, sizeof(mode)); printf("%d",mode); if (valread2 <= 0) { break; // Exit loop if no data received or connection closed } if(mode==1){ pthread_mutex_lock(&book_mutex); int valread3 = read(client_socket,data,sizeof(data)); int num_books=read_books_data(); int index = book_exists(data,num_books)-1; char quant[100]; strcpy(quant,books[index].quant); int quantity = atoi(quant); if(get_user_status(username)==0){ char * error = "Already borrowed a book , return the previous book the borrow a new one\n"; send(client_socket,error,strlen(error),0); } else if(book_exists(data,num_books)==0 || quantity==0){ char * error = "Book not available\n"; send(client_socket,error,strlen(error),0); }else{ char new_quant[100]; int num_chars_written = sprintf(new_quant, "%d", quantity-1); modify_book_quantity(data,new_quant,num_books); write_books_data(num_books); char * no_error = "Book borrowed\n"; send(client_socket,no_error,strlen(no_error),0); log_transaction(username,data,"Borrowed"); update_user_status(username, 0); } pthread_mutex_unlock(&book_mutex); }else if(mode==2){ int valread3 = read(client_socket,data,sizeof(data)); int num_books=read_books_data(); int index = book_exists(data,num_books)-1; char quant[100]; strcpy(quant,books[index].quant); int quantity = atoi(quant); if(get_user_status(username)==1){ char * error = "Nothing to return for this particular user\n"; send(client_socket,error,strlen(error),0); } else if(book_exists(data,num_books)==0 || quantity==0){ char * error = "Book not in database\n"; send(client_socket,error,strlen(error),0); }else{ pthread_mutex_lock(&book_mutex); char new_quant[100]; int num_chars_written = sprintf(new_quant, "%d", quantity+1); modify_book_quantity(data,new_quant,num_books); write_books_data(num_books); char * no_error = "Book returned\n"; send(client_socket,no_error,strlen(no_error),0); log_transaction(username,data,"Returned"); update_user_status(username, 1); pthread_mutex_unlock(&book_mutex); } } memset(buffer1, 0, sizeof(buffer1)); } } else { // Authentication failed char *failure_message = "Authentication failed. Invalid username or password.\n"; send(client_socket, failure_message, strlen(failure_message), 0); close(client_socket); pthread_exit(NULL); } } // Function to handle client communication void *handle_client(void *arg) { int client_socket = *((int *)arg); char buffer[1024] = {0}; char *mode_prompt = "Please select login mode:\n1) User Mode\n2) Admin Mode\n"; // Send mode prompt to client send(client_socket, mode_prompt, strlen(mode_prompt), 0); // Receive mode selection from client int mode; int valread = read(client_socket, &mode, sizeof(mode)); if (valread <= 0) { printf("hi\n"); close(client_socket); pthread_exit(NULL); } // Handle client based on selected mode switch (mode){ case 1: char *user_message = "User mode selection.\n"; send(client_socket, user_message, strlen(user_message), 0); handle_user_login(client_socket); break; case 2: char *admin_message = "Admin mode selection.\n"; send(client_socket, admin_message, strlen(admin_message), 0); handle_admin_login(client_socket); break; case 3: pthread_mutex_lock(&book_mutex); char comb[100]; memset(comb,0,strlen(comb)); int valread5=read(client_socket,comb,strlen(comb)); char name1[100]; char pwd1[100]; printf("%s",comb); //add_user(name1,pwd1); char messaga[100]; send(client_socket,comb,strlen(comb),0); handle_user_login(client_socket); pthread_mutex_unlock(&book_mutex); break; default: // Invalid mode selection char *invalid_message = "Invalid mode selection.\n"; send(client_socket, invalid_message, strlen(invalid_message), 0); close(client_socket); pthread_exit(NULL); } } int main() { int server_fd, new_socket; struct sockaddr_in address; int opt = 1; int addrlen = sizeof(address); file = fopen("members.txt","r"); if (file == NULL) { perror("Error opening file"); return 1; } while (fscanf(file, "%s %s", entries[num_entries].name, entries[num_entries].password) == 2) { num_entries++; } // Close the file fclose(file); // Create socket file descriptor if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { perror("socket failed"); exit(EXIT_FAILURE); } // Set socket options if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) { perror("setsockopt"); exit(EXIT_FAILURE); } address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(PORT); // Bind socket to address if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) { perror("bind failed"); exit(EXIT_FAILURE); } // Listen for connections if (listen(server_fd, MAX_CLIENTS) < 0) { perror("listen"); exit(EXIT_FAILURE); } printf("Server listening on port %d\n", PORT); // Accept incoming connections and handle them in separate threads while (1) { if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) { perror("accept"); exit(EXIT_FAILURE); } // Create thread to handle client communication pthread_t tid; if (pthread_create(&tid, NULL, handle_client, &new_socket) != 0) { perror("pthread_create"); close(new_socket); } } return 0; }
/** * @copyright * * Project Athena for Data Clustering Metaheuristics focused on images. * * Copyright (C) 2011 Alexander De Sousa ([email protected]), * Federico Ponte ([email protected]) * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * @author Alexander De Sousa ([email protected]), * Federico Ponte ([email protected]) * * @section Description * * Definition of the abstract class BaseHeuristic. All the algorithms inherit * the base methods defined here. */ #include <cstdio> #include <cstdlib> #include "Individual.h" #ifndef _BASE_HEURISTIC_ #define _BASE_HEURISTIC_ using namespace std; class BaseHeuristic { public: BaseHeuristic() { } /** * Destructor. */ virtual ~BaseHeuristic() { } /** * Executes the heuristic. */ virtual void run() = 0; /** * @return Best solution Davies-Bouldin validity index value. */ virtual float finalDB() = 0; /** * @return Best solution Turi validity index value. */ virtual float finalTuri() = 0; /** * @return Number of evaluations of the objective function. */ virtual int getNumberOfEvaluations() = 0; /** * Best individual found by the algorithm. */ Individual bestIndividual; }; #endif
<div id="document" class="modal fade" tabindex="-1" role="dialog" data-backdrop="static" aria-labelledby="document" aria-hidden="true" > <div class="modal-dialog modal-xl modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title font-weight-bold" id="addDistrictModalTitle"> Add Vehicle Document </h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close" > <span aria-hidden="true">Close &times;</span> </button> </div> <div class="modal-body"> <form class="highlight-required" id="vehicleDetails" #document="ngForm" autocomplete="off" > <input type="hidden" name="id" id="id" [(ngModel)]="this.fields.id" /> <div class="col-md-3"> <label for="documentName"> <h6 class="small font-weight-bold">Document Name</h6> </label> <select2 [selectionCounter]="false" [options]="documentNameoptions" [id]="'documentName'" name="documentName" (onChange)="setDocumentName($event)" [selectedData]="fields.documentName" [placeholder]="'Select'" [(ngModel)]="fields.documentName" ngDefaultControl [required]="true" ></select2> </div> <hr /> <div class="row"> <div class="col-md-3" *ngIf="fieldsToShow?.vehicleNo"> <label for="vehicleNo"> <h6 class="small font-weight-bold">Vehicle No.</h6> </label> <select2 [id]="'vehicleNo'" name="vehicleNo" [selectionCounter]="false" [options]="vehcileOptions" [placeholder]="'Select'" [(ngModel)]="fields.vehicleNo" [selectedData]="fields.vehicleNo" (onChange)="setDocumentValues($event, 'vehicleNo')" ngDefaultControl ></select2> </div> <div class="col-md-3" *ngIf="fieldsToShow?.resource"> <label for="resource"> <h6 class="small font-weight-bold">Resource</h6> </label> <select2 [selectionCounter]="false" [options]="resourceOptions" [id]="'resource'" [placeholder]="'Select'" name="resource" (onChange)="setDocumentValues($event, 'resource')" [selectedData]="fields.resource" [(ngModel)]="fields.resource" ngDefaultControl [required]="true" ></select2> </div> <div class="col-md-3" *ngIf="fieldsToShow?.refNo"> <label for="refNo"> <h6 class="small font-weight-bold">Reference No</h6> </label> <select2 [selectionCounter]="false" [options]="refOptions" [id]="'refNo'" name="refNo" (onChange)="setDocumentValues($event, 'refNo')" [selectedData]="fields.refNo" [(ngModel)]="fields.refNo" ngDefaultControl [placeholder]="'Select'" [required]="true" ></select2> </div> <div class="col-md-3" *ngIf="fieldsToShow?.insuranceCompany"> <label for="insuranceCompany"> <h6 class="small font-weight-bold">Insurance Company</h6> </label> <select2 [selectionCounter]="false" [options]="insuranceCompanyOptions" [id]="'insuranceCompany'" name="insuranceCompany" (onChange)="setDocumentValues($event, 'insuranceCompany')" [selectedData]="fields.insuranceCompany" [(ngModel)]="fields.insuranceCompany" ngDefaultControl [placeholder]="'Select'" [required]="true" ></select2> </div> <div class="col-md-3" *ngIf="fieldsToShow?.validFrom"> <label for="validFrom"> <h6 class="small font-weight-bold">Valid From</h6> </label> <input type="text" id="validFrom" [(ngModel)]="fields.validFrom" required placeholder="Select a Date" class="form-control" onFocus="(this.type = 'date')" name="validFrom" /> </div> <div class="col-md-3" *ngIf="fieldsToShow?.validTo"> <label for="validTo"> <h6 class="small font-weight-bold">Valid To</h6> </label> <input type="text" id="validTo" [(ngModel)]="fields.validTo" required placeholder="Select a Date" class="form-control" onFocus="(this.type = 'date')" name="validTo" /> </div> <div class="col-md-3" *ngIf="fieldsToShow?.authority"> <label for="authority"> <h6 class="small font-weight-bold">Authority</h6> </label> <select2 [selectionCounter]="false" [options]="authorityOptions" [id]="'authority'" name="authority" (onChange)="setDocumentValues($event, 'authority')" [selectedData]="fields.authority" [(ngModel)]="fields.authority" ngDefaultControl [placeholder]="'Select'" [required]="true" ></select2> </div> <div class="col-md-3" *ngIf="fieldsToShow?.ncb"> <label for="ncb"> <h6 class="small font-weight-bold">NCB</h6> </label> <select2 [selectionCounter]="false" [options]="ncbOptions" [id]="'ncb'" name="ncb" (onChange)="setDocumentValues($event, 'ncb')" [selectedData]="fields.ncb" [(ngModel)]="fields.ncb" ngDefaultControl [placeholder]="'Select'" [required]="true" ></select2> </div> <div class="col-md-3" *ngIf="fieldsToShow?.idv"> <label for="idv"> <h6 class="small font-weight-bold">IDV</h6> </label> <select2 [selectionCounter]="false" [options]="idvOptions" [id]="'idv'" name="idv" (onChange)="setDocumentValues($event, 'idv')" [selectedData]="fields.idv" [(ngModel)]="fields.idv" [placeholder]="'Select'" ngDefaultControl [required]="true" ></select2> </div> <div class="col-md-3" *ngIf="fieldsToShow?.govt"> <label for="govt"> <h6 class="small font-weight-bold">Govt. Name</h6> </label> <select2 [selectionCounter]="false" [options]="govtOptions" [id]="'govt'" name="govt" (onChange)="setDocumentValues($event, 'govt')" [selectedData]="fields.govt" [(ngModel)]="fields.govt" ngDefaultControl [placeholder]="'Select'" [required]="true" ></select2> </div> <div class="col-md-3" *ngIf="fieldsToShow?.tax"> <label for="tax"> <h6 class="small font-weight-bold">Tax Name</h6> </label> <select2 [selectionCounter]="false" [options]="taxOptions" [id]="'tax'" name="tax" (onChange)="setDocumentValues($event, 'tax')" [selectedData]="fields.tax" [(ngModel)]="fields.tax" ngDefaultControl [required]="true" [placeholder]="'Select'" ></select2> </div> <div class="col-md-3" *ngIf="fieldsToShow?.amount"> <label for="amt"> <h6 class="small font-weight-bold">Amount</h6> </label> <input type="number" id="amt" [(ngModel)]="fields.amount" required class="form-control" name="amt" placeholder="Amount" /> </div> <div class="col-md-3" *ngIf="fieldsToShow?.transactionId"> <label for="transactionId"> <h6 class="small font-weight-bold">Transaction ID</h6> </label> <input type="date" id="transactionId" placeholder="Transaction ID" [(ngModel)]="fields.transactionId" required class="form-control" name="transactionId" /> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" id="submitDistrictInformation" class="btn btn-theme" [disabled]="document.invalid" (click)="submitDetails(document)" > Save Details </button> </div> </div> </div> </div>
package com.climbingzone5.service; import com.climbingzone5.service.dto.CardDTO; import java.util.List; import java.util.Optional; /** * Service Interface for managing {@link com.climbingzone5.domain.Card}. */ public interface CardService { /** * Save a card. * * @param cardDTO the entity to save. * @return the persisted entity. */ CardDTO save(CardDTO cardDTO); /** * Get all the cards. * * @return the list of entities. */ List<CardDTO> findAll(); /** * Get the "id" card. * * @param id the id of the entity. * @return the entity. */ Optional<CardDTO> findOne(Long id); /** * Delete the "id" card. * * @param id the id of the entity. */ void delete(Long id); }
<?php declare(strict_types=1); namespace Mothership; use Exception; use Psr\Log\InvalidArgumentException; use Mothership\Payload\Level; use Mothership\Handlers\FatalHandler; use Mothership\Handlers\ErrorHandler; use Mothership\Handlers\ExceptionHandler; use Stringable; use Throwable; class Mothership { /** * The instance of the logger. This is null if Mothership has not been initialized or {@see Mothership::destroy()} has * been called. * * @var MothershipLogger|null */ private static ?MothershipLogger $logger = null; /** * The fatal error handler instance or null if it was disabled or Mothership has not been initialized. * * @var FatalHandler|null */ private static ?FatalHandler $fatalHandler = null; /** * The error handler instance or null if it was disabled or Mothership has not been initialized. * * @var ErrorHandler|null */ private static ?ErrorHandler $errorHandler = null; /** * The exception handler instance or null if it was disabled or Mothership has not been initialized. * * @var ExceptionHandler|null */ private static ?ExceptionHandler $exceptionHandler = null; /** * Sets up Mothership monitoring and logging. * * This method may be called more than once to update or extend the configs. To do this pass an array as the * $configOrLogger argument. Any config values in the array will update or replace existing configs. * * Note: this and the following two parameters are only used the first time the logger is created. This prevents * multiple error monitors from reporting the same error more than once. To change these values you must call * {@see Mothership::destroy()} first. * * Example: * * // Turn off the fatal error handler * $configs = Mothership::logger()->getConfig(); * Mothership::destroy(); * Mothership::init($configs, handleFatal: false); * * @param MothershipLogger|array $configOrLogger This can be either an array of config options or an already * configured {@see MothershipLogger} instance. * @param bool $handleException If set to false Mothership will not monitor exceptions. * @param bool $handleError If set to false Mothership will not monitor errors. * @param bool $handleFatal If set to false Mothership will not monitor fatal errors. * * @return void * @throws Exception If the $configOrLogger argument is an array that has invalid configs. * * @link https://docs.mothership.app */ public static function init( MothershipLogger|array $configOrLogger, bool $handleException = true, bool $handleError = true, bool $handleFatal = true ): void { $setupHandlers = is_null(self::$logger); self::setLogger($configOrLogger); if ($setupHandlers) { if ($handleException) { self::setupExceptionHandling(); } if ($handleError) { self::setupErrorHandling(); } if ($handleFatal) { self::setupFatalHandling(); } self::setupBatchHandling(); } } /** * Creates or configures the MothershipLogger instance. * * @param MothershipLogger|array $configOrLogger The configs array or a new {@see MothershipLogger} to use or replace the * current one with, if one already exists. If a logger already exists * and this is an array the current logger's configs will be extended * configs from the array. * * @return void * @throws Exception If the $configOrLogger argument is an array that has invalid configs. */ private static function setLogger(MothershipLogger|array $configOrLogger): void { if ($configOrLogger instanceof MothershipLogger) { self::$logger = $configOrLogger; return; } // Replacing the logger rather than configuring the existing logger breaks BC if (self::$logger !== null) { self::$logger->configure($configOrLogger); return; } self::$logger = new MothershipLogger($configOrLogger); } /** * Enables logging of errors to Mothership. * * @return void */ public static function enable(): void { self::logger()->enable(); } /** * Disables logging of errors to Mothership. * * @return void */ public static function disable(): void { self::logger()->disable(); } /** * Returns true if the Mothership logger is enabled. * * @return bool */ public static function enabled(): bool { return self::logger()->enabled(); } /** * Returns true if the Mothership logger is disabled. * * @return bool */ public static function disabled(): bool { return self::logger()->disabled(); } /** * Returns the current logger instance, or null if it has not been initialized or has been destroyed. * * @return MothershipLogger|null */ public static function logger(): ?MothershipLogger { return self::$logger; } /** * Creates and returns a new {@see MothershipLogger} instance. * * @param array $config The configs extend the configs of the current logger instance, if it exists. * * @return MothershipLogger * @throws Exception If the $config argument is an array that has invalid configs. */ public static function scope(array $config): MothershipLogger { if (is_null(self::$logger)) { return new MothershipLogger($config); } return self::$logger->scope($config); } /** * Logs a message to the Mothership service with the specified level. * * @param Level|string $level The severity level of the message. * Must be one of the levels as defined in * the {@see Level} constants. * @param string|Stringable $message The log message. * @param array $context Arbitrary data. * * @return void * * @throws InvalidArgumentException If $level is not a valid level. * @throws Throwable Rethrown $message if it is {@see Throwable} and {@see Config::raiseOnError} is true. */ public static function log($level, string|Stringable $message, array $context = array()): void { if (is_null(self::$logger)) { return; } self::$logger->log($level, $message, $context); } /** * Creates the {@see Response} object and reports the message to the Mothership * service. * * @param string|Level $level The severity level to send to Mothership. * @param string|Stringable $message The log message. * @param array $context Any additional context data. * * @return Response * * @throws InvalidArgumentException If $level is not a valid level. * @throws Throwable Rethrown $message if it is {@see Throwable} and {@see Config::raiseOnError} is true. * * @since 4.0.0 */ public static function report($level, string|Stringable $message, array $context = array()): Response { if (is_null(self::$logger)) { return self::getNotInitializedResponse(); } return self::$logger->report($level, $message, $context); } /** * Attempts to log a {@see Throwable} as an uncaught exception. * * @param string|Level $level The log level severity to use. * @param Throwable $toLog The exception to log. * @param array $context The array of additional data to pass with the stack trace. * * @return Response * @throws Throwable The rethrown $toLog. * * @since 3.0.0 */ public static function logUncaught(string|Level $level, Throwable $toLog, array $context = array()): Response { if (is_null(self::$logger)) { return self::getNotInitializedResponse(); } return self::$logger->report($level, $toLog, $context, isUncaught: true); } /** * Logs a message with the {@see Level::DEBUG} log level. * * @param string|Stringable $message The debug message to log. * @param array $context The additional data to send with the message. * * @return void * @throws Throwable */ public static function debug(string|Stringable $message, array $context = array()): void { self::log(Level::DEBUG, $message, $context); } /** * Logs a message with the {@see Level::INFO} log level. * * @param string|Stringable $message The info message to log. * @param array $context The additional data to send with the message. * * @return void * @throws Throwable */ public static function info(string|Stringable $message, array $context = array()): void { self::log(Level::INFO, $message, $context); } /** * Logs a message with the {@see Level::NOTICE} log level. * * @param string|Stringable $message The notice message to log. * @param array $context The additional data to send with the message. * * @return void * @throws Throwable */ public static function notice(string|Stringable $message, array $context = array()): void { self::log(Level::NOTICE, $message, $context); } /** * Logs a message with the {@see Level::WARNING} log level. * * @param string|Stringable $message The warning message to log. * @param array $context The additional data to send with the message. * * @return void * @throws Throwable */ public static function warning(string|Stringable $message, array $context = array()): void { self::log(Level::WARNING, $message, $context); } /** * Logs a message with the {@see Level::ERROR} log level. * * @param string|Stringable $message The error message to log. * @param array $context The additional data to send with the message. * * @return void * @throws Throwable */ public static function error(string|Stringable $message, array $context = array()): void { self::log(Level::ERROR, $message, $context); } /** * Logs a message with the {@see Level::CRITICAL} log level. * * @param string|Stringable $message The critical message to log. * @param array $context The additional data to send with the message. * * @return void * @throws Throwable */ public static function critical(string|Stringable $message, array $context = array()): void { self::log(Level::CRITICAL, $message, $context); } /** * Logs a message with the {@see Level::ALERT} log level. * * @param string|Stringable $message The alert message to log. * @param array $context The additional data to send with the message. * * @return void * @throws Throwable */ public static function alert(string|Stringable $message, array $context = array()): void { self::log(Level::ALERT, $message, $context); } /** * Logs a message with the {@see Level::EMERGENCY} log level. * * @param string|Stringable $message The emergency message to log. * @param array $context The additional data to send with the message. * * @return void * @throws Throwable */ public static function emergency(string|Stringable $message, array $context = array()): void { self::log(Level::EMERGENCY, $message, $context); } /** * Creates a listener that monitors for exceptions. * * @return void */ public static function setupExceptionHandling(): void { self::$exceptionHandler = new ExceptionHandler(self::$logger); self::$exceptionHandler->register(); } /** * Creates a listener that monitors for errors. * * @return void */ public static function setupErrorHandling(): void { self::$errorHandler = new ErrorHandler(self::$logger); self::$errorHandler->register(); } /** * Creates a listener that monitors for fatal errors that cause the program to shut down. * * @return void */ public static function setupFatalHandling(): void { self::$fatalHandler = new FatalHandler(self::$logger); self::$fatalHandler->register(); } /** * Creates and returns a {@see Response} to use if Mothership is attempted to be used prior to being initialized. * * @return Response */ private static function getNotInitializedResponse(): Response { return new Response(0, "Mothership Not Initialized"); } /** * This method makes sure the queue of logs stored in memory are sent to Mothership prior to shut down. * * @return void */ public static function setupBatchHandling(): void { register_shutdown_function('Mothership\Mothership::flushAndWait'); } /** * Sends all the queued logs to Mothership. * * @return void */ public static function flush(): void { if (is_null(self::$logger)) { return; } self::$logger->flush(); } /** * Sends all the queued logs to Mothership and waits for the response. * * @return void */ public static function flushAndWait(): void { if (is_null(self::$logger)) { return; } self::$logger->flushAndWait(); } /** * Adds a new key / value pair that will be sent with the payload to Mothership. If the key already exists in the * custom data array the existing value will be overwritten. * * @param string $key The key to store this value in the custom array. * @param mixed $data The value that is going to be stored. Must be a primitive or JSON serializable. * * @return void */ public static function addCustom(string $key, mixed $data): void { self::$logger->addCustom($key, $data); } /** * Removes a key from the custom data array that is sent with the payload to Mothership. * * @param string $key The key to remove. * * @return void */ public static function removeCustom(string $key): void { self::$logger->removeCustom($key); } /** * Returns the array of key / value pairs that will be sent with the payload to Mothership. * * @return array|null */ public static function getCustom(): ?array { return self::$logger->getCustom(); } /** * Configures the existing {@see MothershipLogger} instance. * * @param array $config The array of configs. This does not need to be complete as it extends the existing * configuration. Any existing values present in the new configs will be overwritten. * * @return void */ public static function configure(array $config): void { self::$logger->configure($config); } /** * Destroys the currently stored $logger allowing for a fresh configuration. This is especially used in testing * scenarios. * * @return void */ public static function destroy(): void { self::$logger = null; } }
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/foundation.dart'; import 'package:price_cruncher_new/services/auth_services_new.dart'; import '../models/usermodel.dart'; class UserDataProvider with ChangeNotifier { UserModel? _user; UserModel? get user => _user; // Fetch user data from Firestore by document ID Future<void> fetchUser() async { try { final snapshot = await FirebaseFirestore.instance .collection('users') .doc(await AuthServicesNew().getEmail()) .get(); if (snapshot.exists) { final userData = snapshot.data() as Map<String, dynamic>; _user = UserModel.fromMap(userData); notifyListeners(); } else { // Handle the case where the document does not exist } } catch (e) { // Handle any errors that occur during the fetch print('Error fetching user data: $e'); } } }
import React from "react"; import { useState } from "react"; import "./double-btn.scss"; import Hidden from "@material-ui/core/Hidden"; import { useSelector } from "react-redux"; const DoubleBtn = (props) => { const { mainText, onText, offText, width, onAction, offAction, type, disabled, } = props; const scSize = useSelector((state) => state.ScSizeReducer); const isMobile = scSize?.width < 960 ? true : false; return ( <> <div className="db-link" style={{ width: width }}> <Hidden smDown> <button disabled={disabled} type={type} onClick={offAction} onMouseEnter={(e) => { e.currentTarget.innerText = offText; }} onMouseLeave={(e) => { e.currentTarget.innerText = isMobile ? offText : mainText; }} > {isMobile ? onText : mainText} </button> </Hidden> <button disabled={disabled} type={type} onClick={onAction} onMouseEnter={(e) => { e.currentTarget.innerText = onText; }} onMouseLeave={(e) => { e.currentTarget.innerText = isMobile ? onText : mainText; }} > {isMobile ? onText : mainText} </button> </div> </> ); }; export default DoubleBtn;
import React, { memo } from "react"; import { TextInputProps, View } from "react-native"; import { useFormikContext } from "formik"; import AppTextInput from "components/AppTextInput"; import ErrorMessage from "../ErrorMessage"; import { MaterialCommunityIconsType } from "types/data"; import globalStyles from "config/globalStyles"; interface Props extends TextInputProps { error: string | undefined; iconName?: MaterialCommunityIconsType; fieldName: string; placeHolder: string; value: string; visible: boolean | undefined; props?: TextInputProps; } const AppFormField: React.FC<Props> = ({ error = "", iconName, fieldName, placeHolder = "", value = "", visible = false, ...props }) => { const { setFieldTouched, handleChange } = useFormikContext(); return ( <View> <AppTextInput error={error} iconName={iconName} onBlur={() => setFieldTouched(fieldName)} onChangeText={handleChange(fieldName)} placeHolder={placeHolder} value={value} visible={visible} {...props} /> <View style={globalStyles.fieldError}> <ErrorMessage error={error} visible={visible} /> </View> </View> ); }; export default memo(AppFormField);
--- import "../../styles/style.css"; import Footer from '../../components/Footer.astro' import { getCollection } from 'astro:content'; import { ViewTransitions } from 'astro:transitions'; export async function getStaticPaths() { const languageEntries = await getCollection("languages"); return languageEntries.map(i => ({ params: { language: i.slug } })); } const languageCollection = await getCollection("languages"); const { language } = Astro.params; const selectedLanguage = languageCollection.find((lang) => lang.slug === language); --- <html lang={selectedLanguage?.data.iso}> <head> <meta charset="utf-8" /> <link rel="icon" type="image/svg+xml" href="/favicon.svg" /> <meta name="viewport" content="width=device-width" /> <meta name="generator" content={Astro.generator} > <ViewTransitions /> <title>Contact</title> </head> <style> main { height: 80vh; flex-direction: column; align-items: center; justify-content: center; } .contact-persons { display: flex; flex-direction: row; justify-content: space-between; margin-block-start: 5rem; gap: 5rem; } .wife, .husband { display: flex; flex-direction: column; justify-content: center; align-items: center; gap: 2rem; } a{ text-align: center; } </style> <body> <main transition:animate="slide" class="justify-center"> <p>{selectedLanguage?.data.contactInfo}</p> <h1>{selectedLanguage?.data.contactHealine}</h1> <div class="contact-persons"> <div class="wife"> <h2><b>DIANA</b></h2> <a target="_blank" href="https://www.facebook.com/otelea.diana">Facebook</a> <a href="tel:+4591638056">{selectedLanguage?.data.phoneNumber}</a> </div> <div class="husband"> <h2><b>MICK</b></h2> <a target="_blank" href="https://www.facebook.com/mick.pedersen">Facebook</a> <a href="">{selectedLanguage?.data.phoneNumber}</a> </div> </div> </main> <Footer/> </body> </html>
//-------------------------------------------------------------------------------------------------------------------- // Name : switch.h // Purpose : Switch Driver Class // Description : // This class intended for control of generic switch. // // Language : C++ // Platform : Portable // Framework : Portable // Copyright : MIT License 2024, John Greenwell // Requires : External : N/A // Custom : hal.h - Custom implementation-defined Hardware Abstraction Layer //-------------------------------------------------------------------------------------------------------------------- #ifndef _SWITCH_H #define _SWITCH_H #include "hal.h" namespace PeripheralIO { class Switch { public: /** * @brief Constructor for Switch object * @param pin Pin identifier to which switch is attached * @param press_logic Logic level of a pressed switch * @param debounce_ms Time in milliseconds to debounce switch, greater than update_interval_ms * @param release_timeout_ms Optional timeout after which a release is ignored, use 0 for no timeout * @param update_interval_ms Interval in milliseconds between timed calls to switch_state_update() */ Switch(uint8_t pin, bool press_logic=false, uint16_t debounce_ms=20, uint16_t update_interval_ms=5, uint16_t release_timeout_ms=0); /** * @brief Initialize switch; should not be necessary if constructor init of pin is reliable */ void init() const; /** * @brief Check whether switch has been pressed; requires clearState() to reset * @return True if button has been pressed, false otherwise */ bool pressed() const; /** * @brief Check whether switch has been released; requires clearState() to reset * @return True if button has been released at interval shorter than timeout, false otherwise */ bool released() const; /** * @brief Clear state of switch, returning to unpressed/unreleased status */ void clearState(); /** * @brief Get the current raw, non-debounced logical press state of the button * @return True for a logic level matching press_logic, false otherwise */ bool getState() const; /** * @brief Poll the state of the switch at fixed intervals update_interval_ms; facilitates switch * debouncing and press/release detection. */ void poll(); private: HAL::GPIO _pin; bool _press_logic; bool _timeout_enabled; bool _is_held; bool _is_pressed; bool _is_released; uint16_t _debounce_ms; uint16_t _update_interval_ms; uint16_t _release_timeout_ms; uint32_t _counter_min; uint32_t _counter_max; uint32_t _count; }; } #endif // _SWITCH_H // EOF
import {Input} from '../common/Input' import { FormProvider, useForm } from 'react-hook-form' import { email_validation, phone_validation, aadhar_validation, date_validation, reg_date_validation, reg_name_validation, } from '../../utils/inputValidations' import { useState } from 'react' import { GrMail } from 'react-icons/gr' import { BsFillCheckSquareFill } from 'react-icons/bs' import { useNavigate } from 'react-router-dom' export const Register = () => { const methods = useForm() const [success, setSuccess] = useState(false) const navigate = useNavigate(); const onSubmit = methods.handleSubmit(data => { console.log(data) const requestOptions = { method: 'PUT', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data) }; fetch(`http://localhost:3010/customer/${data.name}`, requestOptions) .then(response => response.json()) .then(res => { console.log(res) methods.reset() setSuccess(true) navigate('./dashboard',{state:data.name}) } ); }) return ( <FormProvider {...methods}> <form onSubmit={e => e.preventDefault()} noValidate autoComplete="off" className="container" > <h4>Please enter the details</h4> <div className="grid gap-5 md:grid-cols-2"> <Input {...reg_name_validation} /> <Input {...email_validation} /> <Input {...date_validation} /> <Input {...phone_validation} /> <Input {...aadhar_validation} /> <Input {...reg_date_validation} /> </div> <div className="mt-5"> {success && ( <p className="font-semibold text-green-500 mb-5 flex items-center gap-1"> <BsFillCheckSquareFill /> Form has been submitted successfully </p> )} <button onClick={onSubmit} data-testid="button" className="p-5 rounded-md bg-blue-600 font-semibold text-white flex items-center gap-1 hover:bg-blue-800" > <GrMail /> Submit Form </button> </div> </form> </FormProvider> ) }
package com.kocci.healtikuy.core.di import android.content.Context import androidx.room.Room import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase import com.kocci.healtikuy.core.data.local.db.AvoidFeatureDao import com.kocci.healtikuy.core.data.local.db.HealtikuyDao import com.kocci.healtikuy.core.data.local.db.HealtikuyRoomDatabase import com.kocci.healtikuy.core.data.local.db.NutritionDao import com.kocci.healtikuy.core.data.local.db.SleepDao import com.kocci.healtikuy.core.data.local.db.SunExposureDao import com.kocci.healtikuy.core.data.local.db.WaterIntakeDao import com.kocci.healtikuy.core.data.local.db.exercise.JoggingDao import com.kocci.healtikuy.core.data.local.db.exercise.RunningDao import com.kocci.healtikuy.core.data.local.db.exercise.StaticBikeDao import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) class DatabaseModule { private val MIGRATION_1_2 = object : Migration(1, 2) { override fun migrate(database: SupportSQLiteDatabase) { //? You can get this code in core > schemas > latest version database. database.execSQL("CREATE TABLE IF NOT EXISTS `avoid_feature` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `alcohol` INTEGER NOT NULL, `smoke` INTEGER NOT NULL, `limitSugar` INTEGER NOT NULL, `limitFat` INTEGER NOT NULL, `isTodayAllChecked` INTEGER NOT NULL, `timeStamp` INTEGER NOT NULL)") } } @Provides @Singleton fun provideRoomDatabase(@ApplicationContext context: Context): HealtikuyRoomDatabase { return Room.databaseBuilder( context, HealtikuyRoomDatabase::class.java, "healtikuy.db" ) .addMigrations(MIGRATION_1_2) .build() } @Provides @Singleton fun provideWaterIntakeDao(database: HealtikuyRoomDatabase): WaterIntakeDao { return database.waterDao() } @Provides @Singleton fun provideSleepDao(database: HealtikuyRoomDatabase): SleepDao { return database.sleepDao() } @Provides @Singleton fun provideJoggingDao(database: HealtikuyRoomDatabase): JoggingDao { return database.joggingDao() } @Provides @Singleton fun provideRunningDao(database: HealtikuyRoomDatabase): RunningDao { return database.runningDao() } @Provides @Singleton fun provideStaticBikeDao(database: HealtikuyRoomDatabase): StaticBikeDao { return database.staticBikeDao() } @Provides @Singleton fun provideHealtikuyDao(database: HealtikuyRoomDatabase): HealtikuyDao { return database.dao() } @Provides @Singleton fun provideNutritionDao(database: HealtikuyRoomDatabase): NutritionDao { return database.nutritionDao() } @Provides @Singleton fun provideSunexposureDao(database: HealtikuyRoomDatabase): SunExposureDao { return database.sunExposureDao() } @Provides @Singleton fun provideAvoidFeatureDao(database: HealtikuyRoomDatabase): AvoidFeatureDao { return database.avoidFeatureDao() } }
import { Suspense } from "react"; export default function DataComponent<T>({ source, loading, component: renderer, }: { source: Promise<T>; loading: JSX.Element; component: (data: T) => JSX.Element; }) { return ( <Suspense fallback={loading}> <ComponentRenderer provider={suspend(source)} renderer={renderer} /> </Suspense> ); } function ComponentRenderer<T>({ provider, renderer, }: { provider: () => T; renderer: (data: T) => JSX.Element; }) { return renderer(provider()); } function suspend<T>(promise: Promise<T>): () => T { let status: "pending" | "success" | "error" = "pending"; let result: T; const suspender = new Promise<void>((resolve, reject) => { promise .then((r) => { status = "success"; result = r; resolve(); }) .catch((e) => { status = "error"; result = e; // <Suspend /> promises can never return anything // eslint-disable-next-line prefer-promise-reject-errors reject(); }); }); // @ts-expect-error If the user passes a promise returning undefined then they know what they're getting into return () => { if (status === "pending") { throw suspender; } else if (status === "error") { throw result; } else if (status === "success") { return result; } }; }
#!/usr/bin/env python import numpy class Pattern: def __init__(self, lines): self.height = len(lines) self.width = len(lines[0]) self.map = numpy.zeros((self.height, self.width), dtype=numpy.uint8) for y in range(self.height): for x in range(self.width): if lines[y][x] == '#': self.map[y, x] = 1 def is_horizontal_reflection(self, candidate_row): if candidate_row <= 0 or candidate_row >= self.height: return False for check_offset in range(1, min([candidate_row, self.height - candidate_row]) + 1): for x in range(self.width): if self.map[candidate_row + check_offset - 1, x] != \ self.map[candidate_row - check_offset, x]: return False return True def is_vertical_reflection(self, candidate_col): if candidate_col <= 0 or candidate_col >= self.width: return False for check_offset in range(1, min([candidate_col, self.width - candidate_col]) + 1): for y in range(self.height): if self.map[y, candidate_col + check_offset - 1] != \ self.map[y, candidate_col - check_offset]: return False return True def score_horizontal_reflection(self): for candidate_row in range(1, self.height): if self.is_horizontal_reflection(candidate_row): return 100 * candidate_row return 0 def score_vertical_reflection(self): for candidate_col in range(1, self.width): if self.is_vertical_reflection(candidate_col): return candidate_col return 0 def score(self): return self.score_horizontal_reflection() + \ self.score_vertical_reflection() def __str__(self): return str(self.map) lines = [line.strip() for line in open('13.input').readlines()] patterns = [] buffer = [] for line in lines: if len(line) == 0: patterns.append(Pattern(buffer)) buffer = [] else: buffer.append(line) patterns.append(Pattern(buffer)) print(sum([p.score() for p in patterns]))
<!DOCTYPE html> <html lang="fr"> <head> <meta charset="utf-8"> <title>DataViz with D3.js</title> <script src="../../js/d3/d3.v3.js"></script> <style> path { stroke: #91268E; stroke-width: .5; fill: none; } .axis { shape-rendering: crispEdges; } .axis text{ text-anchor: end; fill: blue; font-size:7px; } text.labelPoints{ text-anchor: middle; font-size:7px; } .axis path { /* marker-end:url(#markerArrow); */ stroke: blue; stroke-width: 1; } .axis .tick line { stroke: blue; } .axis line.grid { opacity: 1; stroke: lightgrey; stroke-width: 1; stroke-dasharray: 2, 4; } #titre { fill:#F8981D; font-size: small; text-anchor: middle; font-weight: bold; } .titre { fill: blue; font-size: small; text-anchor: middle; font-weight: bold; } line.max { stroke: red; stroke-width: .4; } </style> </head> <body> <div id="divGraphique" class="aGraph" style="position:absolute;top:10px;left:10px; float:left;"></div> <script> var grandWidth = 600, grandHeight = 400; var margin = {top: 40, right: 40, bottom: 60, left: 60}, width = grandWidth - margin.left - margin.right, height = grandHeight - margin.top - margin.bottom; var dataset = [3.5, 3.9, 4.3, 4.5, 5.1, 5.4, 6.4, 6.9, 7.2, 8.5, 9, 9, 9.1, 8.8, 8.2, 7.9, 8.2, 9, 10.1, 10.7, 10.1, 10.6, 10.8, 10.3, 10, 8.6, 7.8, 7.9, 8.5, 8.9, 8.9, 8.8, 8, 7.4, 7.4, 9.2, 9.3, 9.9, 10.5]; var pasY = 2.5; var baseYear = 1975; var max, min, maxData, minData, avgData; var Intercept = 6.053205, Slope = 0.113664; function abLine(x) { return Slope * x + Intercept; } function minmax() { max = Number.MIN_VALUE; min = Number.MAX_VALUE; var sumX = 0, sumY = 0, sumX2 = 0, sumXY = 0; var N = dataset.length; for(var i = 0; i < dataset.length; i++) { sumY += dataset[i]; // Recherche minimum et maximum if(dataset[i] > max) max = dataset[i]; if(dataset[i] < min) min = dataset[i]; } avgData = sumY / N; minData = min; maxData = max; max = (Math.round(max / pasY) + 1) * pasY; max = Math.round(max+.5); //max = 100; }; function minimumLocal(i) { if(i > 0 && i < dataset.length-1) { return (yScale(dataset[i]) >= yScale(dataset[i-1]) && yScale(dataset[i]) > yScale(dataset[i+1])); } if(i == 0) { return (yScale(dataset[i]) > yScale(dataset[i+1])); } if(i == dataset.length-1) { return (yScale(dataset[i]) > yScale(dataset[i-1])); } } function maximumLocal(i) { if(i > 0 && i < dataset.length-1) { return (yScale(dataset[i]) <= yScale(dataset[i-1]) && yScale(dataset[i]) < yScale(dataset[i+1])); } if(i == 0) { return (yScale(dataset[i]) < yScale(dataset[i+1])); } if(i == dataset.length-1) { return (yScale(dataset[i]) < yScale(dataset[i-1])); } } function dataUp(i) { return i > 0 ? (yScale(dataset[i]) <= yScale(dataset[i-1])) : (yScale(dataset[i]) > yScale(dataset[i+1])); } function dataDown(i) { return i > 0 ? (yScale(dataset[i]) >= yScale(dataset[i-1])): (yScale(dataset[i]) < yScale(dataset[i+1])); } minmax(); var svg = d3.select('#divGraphique').append('svg') .attr('width', grandWidth) .attr('height', grandHeight) .attr('id', 'svgGraphique'); // Bordure svg.append('rect') .attr('x', 0) .attr('y', 0) .attr('width', grandWidth) .attr('height', grandHeight) .style({'stroke-width': 2, 'stroke': 'SteelBlue', 'fill':'LightSteelBlue', 'opacity': .2}); // svg.append("svg:defs") // .append("svg:marker") // .attr("id", 'markerArrow') // //.attr("viewBox", "0 -5 10 10") // .attr("refX", 2) // .attr("refY", 2) // .attr("markerWidth", 4) // .attr("markerHeight", 4) // .attr("orient", "auto") // .attr('markerUnits', 'strokeWidth') // .append("svg:path") // .attr("d", "M0,0 L0,4 L5,2 L0,0") // .style({'stroke': '#000000', 'stroke-width': .2, 'stroke': 'blue', 'fill':'blue'}); var graph = svg.append('g') .attr('id', 'graphique') .attr('transform', "translate(" + margin.left + "," + margin.top + ")"); graph.append('rect') .attr('x', 0) .attr('y', 0) .attr('width', width) .attr('height', height) .style({'fill': 'LightYellow', 'opacity': 1}); var xScale = d3.scale.linear().domain([0, dataset.length-1]).range([0, width]); var yScale = d3.scale.linear().domain([0, max]).range([height, 0]); var line = d3.svg.line() .x(function(d, i) {return xScale(i);}) .y(function(d) {return yScale(d);}); // .interpolate("basis"); graph.append('path') .attr('d', line(dataset)); // Add the x-axis. var xAxis = d3.svg.axis(); xAxis.scale(xScale) .tickFormat(function(d) { return d + baseYear; }) .orient('bottom'); graph.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + (height) + ")") .call(xAxis) .selectAll("text") .style("text-anchor", "end") // .attr("dx", "-.8em") // .attr("dy", ".15em") .attr("transform", function(d) { return "rotate(-65) translate(-7, -7)" }); //var formatAsPercentage = d3.format("0.01%"); var yAxis = d3.svg.axis().ticks(5); //yAxis.tickFormat(formatAsPercentage); yAxis.scale(yScale) .orient('left'); graph.append("g") .attr("class", "y axis") .call(yAxis) ; var dataPoints = graph.append("g") .attr('id', 'groupDataPoints') .selectAll('circle') .data(dataset) .enter() .append('circle') .attr('r', 2) .attr('cx', function(d, i) {return xScale(i);}) .attr('cy', function(d) {return yScale(d)}) .style({'stroke-width':1}) .attr('stroke', function(d, i) { // if(i>0) { // if(yScale(d) > yScale(dataset[i-1])) return '#00ff00'; // else return '#ff0000'; // } // return '#91268E'; return dataDown(i) ? '#00ff00' : (dataUp(i) ? '#ff0000' :'#91268E'); }) .attr('fill', function(d, i) { // if(i<dataset.length-1) { // if(d3.select(this).attr('stroke') == '#00ff00' && yScale(d) > yScale(dataset[i+1])) { // return '#00ff00'; // } // if(d3.select(this).attr('stroke') == '#ff0000' && yScale(d) < yScale(dataset[i+1])) { // return '#ff0000'; // } // } // return 'white'; if(minimumLocal(i)) { return '#00ff00'; } if(maximumLocal(i)) { return '#ff0000'; } return 'white'; }); var labelPoints = graph.append("g") .attr('id', 'groupLabelPoints') .selectAll('text') .data(dataset) .enter() .append('text') .attr('x', function(d, i) { return xScale(i); }) .attr('y', function(d) { return yScale(d); }) .attr('dx', '1em') .attr('dy',function(d, i) { if(minimumLocal(i)) { return '1.5em'; } if(maximumLocal(i)) { return '-.5em'; } return '0em'; }) .text( function(d, i) { if(minimumLocal(i) || maximumLocal(i)) { return d; } return ''; }) .classed('labelPoints', true) .attr('fill', function(d, i) { if(minimumLocal(i)) { return '#00ff00'; } if(maximumLocal(i)) { return '#ff0000'; } return 'black'; //return d3.select(this).attr('stroke'); // if(d3.select(this).attr('stroke') == '#ff0000' && yScale(d) < yScale(dataset[i+1])) { // return '#ff0000'; // } }); d3.selectAll(".x.axis .tick") .filter(function(d,i) {return i != 0;}) .append('line') .attr('x1', 0) .attr('y1', 0) .attr('x2', 0) .attr('y2', -height) .classed('grid', true); d3.selectAll(".y .tick") .filter(function(d,i) {return (i%2 == 0) && (i != 0);}) .append('line') .attr('x1', 0) .attr('y1', 0) .attr('x2', width) .attr('y2', 0) .classed('grid', true); // Ligne du maximum graph.append('line') .attr('x1', 0) .attr('y1', yScale(maxData)) .attr('x2', width) .attr('y2', yScale(maxData)) .classed('max', true); // Ligne de la moyenne graph.append('line') .attr('x1', 0) .attr('y1', yScale(avgData)) .attr('x2', width) .attr('y2', yScale(avgData)) .classed('max', true); // interpolation linéaire graph.append('line') .attr('x1', 0) .attr('y1', yScale(Intercept)) .attr('x2', width) .attr('y2', yScale(abLine(dataset.length-1))) .classed('max', true); // Titre du graphe graph.append("text") .attr('id', 'titre') .attr("x", (width / 2)) .attr("y", 0) .attr('dy', '-.5em') .text("Évolution du taux de chômage en France"); // Titre de l'axe des X graph.append("text") .attr('class', 'titre') .attr("x", (width / 2)) .attr("y", (height+margin.bottom/2)) .attr('dy', '1em') .text("Années"); // Titre de l'axe des Y graph.append("text") .attr('class', 'titre') .attr("y", (height / 2)) .attr("x", (-margin.left/2)) .attr('transform', 'rotate(-90,' + (-margin.left/2) + ',' + (height/2) + ')') .text("Pourcentage"); </script> </body> </html>
package com.example.demo.controller; import com.example.demo.dto.auth_user_dto.AuthUserGetDto; import com.example.demo.exception.ForbiddenAccessException; import com.example.demo.service.AdminService; import com.example.demo.service.AuthUserService; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import java.util.Map; import java.util.UUID; @RestController @RequiredArgsConstructor @RequestMapping("/api.admin") @PreAuthorize("hasAnyAuthority('SUPER_ADMIN','ADMIN')") public class AdminController { private final AdminService adminService; private final AuthUserService authUserService; @PutMapping("/update-email") public void updateEmail(@RequestParam Map<String, String> param){ String adminEmail = param.get("admin"); String oldEmail = param.get("old"); String newEmail = param.get("new"); adminService.updateEmail(adminEmail,oldEmail,newEmail); } @PutMapping("/add-role") public void addRole(@RequestParam String userId, @RequestParam String role){ if (role.equals("SUPER_ADMIN")) { throw new ForbiddenAccessException(); } adminService.addRole(UUID.fromString(userId),role); } @PreAuthorize("hasAuthority('SUPER_ADMIN')") @PutMapping("/add-role-special") public void addRole2(@RequestParam String userId, @RequestParam String role){ adminService.addRole(UUID.fromString(userId),role); } @PutMapping("/remove-role") public void removeRole(@RequestParam String userId, @RequestParam String role){ if (role.equals("SUPER_ADMIN")) { throw new ForbiddenAccessException(); } adminService.removeRole(UUID.fromString(userId),role); } @GetMapping("/get-all-users-data") @PreAuthorize("hasAuthority('SUPER_ADMIN')") public ResponseEntity<Page<AuthUserGetDto>> getUsers(@RequestParam String page, @RequestParam String size){ Page<AuthUserGetDto> users = authUserService .users(PageRequest.of(Integer.parseInt(page), Integer.parseInt(size))); return ResponseEntity.ok(users); } @PutMapping("/update-activity") public void updateActivity(@RequestParam String userId, @RequestParam Boolean activity){ adminService.updateActivity(UUID.fromString(userId),activity); } }
import * as React from "react"; import { Container } from "@material-ui/core"; import HeaderNavigation from "../components/headerNav"; import Footer from "../components/footer"; import { makeStyles } from "@material-ui/core/styles"; const useStyles = makeStyles({ body: { minHeight: "100%", display: "grid", gridTemplateRows: "1fr auto", fontFamily: "Helvetica Neue", lineHeight: "1.5em", }, }); export default function About() { const classes = useStyles(); return ( <> <HeaderNavigation /> <div className={classes.body}> <Container maxWidth="sm"> <br /> <h2>What is this website?</h2> <p> Welcome to my corner of the internet! This project aims to determine the most critically acclaimed videogames of all time, based on critic lists. </p> <br /> <h2>What lists are qualified to appear?</h2> <p> Game of the Year and Greatest Game of All Time lists of all kinds are included as long as there is some sort of editorial staff involved. Fan lists and individual contributor lists are disqualified and not included. </p> <p> In the future, I plan on adding other lists such as Game of the Decade and Greatest Games for X Platform. </p> <br /> <h2>What is the reasoning behind the numbers in your formulas?</h2> <p> First note -- I am not a data scientist or analyst, so the formulas are base on what I believe are fair. They are subject to change in the future. </p> <p> Formulas can be found&nbsp; <a href={process.env.APP_ENV === "dev" ? "../formulas" : "../formulas.html"}>on the page here</a>. </p> <p>Some general notes and insights into my thinking: </p> <ul> <li>The base score for game on a GOAT list is worth twice as much as that of a GOTY winner</li> <li> The older a list is from the current year, the less points are added. This is because a game from say, 1997 has to compete against a universe of smaller games than a game on a 2017 list. Games from within the last 10 years are weighed more heavily and worth more than games on lists > 10 years ago. This is a large reason for having a points-based system. </li> <li>Additional points are based on a percentage of where the game is ranked.</li> <li> An Unranked GOAT is similar to a ranked GOAT, but the ranking is not taken into account due to its lack of existence. </li> <li> An Unranked GOTY list will have all the games inherit the default GOTY value of 0.9, because there is no hierarchy. Therefore, the games are presumed to be ranked equally. </li> </ul> <br /> <h2>How do you treat remakes or re-releases?</h2> <p> This was one of the most difficult things in making this list. Videogames are often re-released, remade and/or remastered throughout the years. I made a choice early on that a game that is a remaster or re-release will count towards the original game's point total (<i>Shadow of the Colossus</i>,{" "} <i>Halo: Anniversary</i>, <i>Demon's Souls</i> on PS5) as long as it was fundamentally the same core game. If a game was remade into something substantially different (the <i>Final Fantasy VII</i> and{" "} <i>Resident Evil 2</i> remakes), they would be counted as their own games. </p> <p> For specific games such as the <i>Street Fighter II</i> and <i>Tetris</i> series of games, this was more difficult and came down to a judgement call. The former series were counted as one game ( <i>Super Street Fighter II/Hyper Fighting/Turbo</i>) while Tetris games were generally grouped together as simply <i>Tetris</i>, with the exception of certain unique instances that were called out ( <i>Tetris Effect</i>,{" "}<i>Tetris Attack</i>). At the end of the day these were decisions made to consolidate a list to what I believe was the best representation of certain games. </p> <p> Where applicable, a note within the SQLite database has been included to denote what specific version of a game was mentioned within the appropriate list. </p> <br /> <h2>I noticed an issue in your list, have questions, or want to leave a comment. How can I reach out?</h2> <p> Feel free to email me at <a href="mailto:[email protected]">[email protected]</a>, or reach out to me via DM/Tweet on <a href="https://mstdn.social/@alxexperience">Mastodon</a>. Also feel free to leave an issue or request on the{" "} <a href="https://gitlab.com/perepechko.alex/greatestgamesofalltime">Gitlab repo</a>! </p> </Container> </div> <Footer /> </> ); }
import React, { useEffect, useState } from 'react' import { useParams } from 'react-router-dom'; import Loader from '../../components/Loader/Loader'; const MealDetails = () => { const [data, setData] = useState(null); const [error, setError] = useState(null); const [loading, setLoading] = useState(true); const { idMeal } = useParams() useEffect(() => { fetch(`https://www.themealdb.com/api/json/v1/1/lookup.php?i=${idMeal}`) .then((response) => { if (!response.ok) { throw new Error(`This is an HTTP Error: The status is ${response.status}`); } return response.json(); }) .then((actualData) => { const meals = actualData.meals; setData(meals); console.log(meals); }) .catch((error) => { console.log(error); setError(error); setData(null); }) .finally(() => { setLoading(false); }); }, [idMeal]); // Extract ingredients from the item object const extractIngredients = (item) => { const ingredients = []; for (let i = 1; i <= 20; i++) { const ingredientKey = `strIngredient${i}`; const measureKey = `strMeasure${i}`; const ingredient = item[ingredientKey]; const measure = item[measureKey]; if (ingredient && ingredient.trim() !== '') { // If both ingredient and measure exist, add them to the ingredients array const ingredientString = measure ? `${ingredient} - ${measure}` : ingredient; ingredients.push(ingredientString); } } return ingredients; }; return ( <section className='flex justify-center items-center my-0 mx-auto py-20 sx:max-w-[100%] lg:max-w-[70%]'> <div className=""> {loading && <Loader />} {error && <div className='text-white font-medium font-Open'>{`There is a problem fetching your data - ${error.message}`}</div>} <div className="px-4 md:px-8 lg:px-0"> {data && data.map((item) => ( <div className="flex flex-col gap-48"> <div className="flex justify-center gap-8 flex-col md:flex-row md:justify-start"> <div className="md:w-2/5"> <img src={item.strMealThumb} alt="" className="" loading='lazy' /> </div> <div className="flex flex-row justify-between md:flex-col"> <div className="flex flex-col gap-4 md:gap-6"> <h1 className='text-2xl sm:text-4xl font-Cormorant text-primaryColor font-semibold'>{item.strMeal}</h1> <p className='text-sm sm:text-base font-medium font-Open text-secondaryColor'>Category: {item.strCategory}</p> {item.strTags && <div className="flex flex-wrap gap-4"> { item.strTags.split(',').map((tag, index) => ( <button key={index} type="button" className='text-sm sm:text-base px-6 py-1 font-Cormorant font-bold rounded-full border border-primaryColor bg-primaryColor text-bgColor w-fit' >{tag}</button> ))} </div> } {item.strYoutube && <p className='font-medium font-Open text-primaryColor transition ease-linear duration-200 delay-100 hover:opacity-80'> <a href={item.strYoutube}>Watch Tutorial</a> </p> } </div> <button type="submit" className='px-4 py-2 font-Cormorant font-bold border border-primaryColor bg-primaryColor text-bgColor w-fit md:w-full h-fit hover:border hover:border-primaryColor hover:bg-transparent hover:text-primaryColor transition ease-linear duration-200 delay-100' > Save Meal </button> </div> </div> <div className="flex flex-col gap-6 font-Open"> <h1 className="text-2xl sm:text-4xl font-semibold text-white ">INGREDIENTS</h1> <ul className="flex flex-col gap-2 text-base sm:text-lg font-medium text-secondaryColor"> {extractIngredients(item).map((ingredient, index) => ( <li key={index}>{ingredient}</li> ))} </ul> </div> <div className="flex flex-col gap-6 font-Open"> <h1 className="text-2xl sm:text-4xl font-semibold text-white ">INSTRUCTIONS</h1> <ul className="flex flex-col gap-2 text-base sm:text-lg font-medium text-secondaryColor"> {item.strInstructions.split('.').map((ins, index) => { if(item !== "") return <li key={index} className="">{`${ins}`}.</li> })} </ul> </div> </div> )) } </div> </div> </section> ) } export default MealDetails
const express = require('express'); const cors = require('cors'); const { databaseConnection } = require('../config/database'); class Server { constructor() { this.app = express(); this.port = process.env.PORT; this.usersPath = '/api/user'; this.authPath = '/api/auth'; this.conectarDB(); this.middlewares(); this.routes(); }; async conectarDB(){ await databaseConnection(); }; middlewares() { this.app.use( cors() ); this.app.use( express.json() ); this.app.use( express.static('public') ); }; routes(){ this.app.use( this.usersPath, require('../routes/user') ); this.app.use( this.authPath, require('../routes/auth') ); }; listen(){ this.app.listen(this.port, () => { console.log(`localhost/port: ${this.port}`); }); }; }; module.exports = Server;
import { nanoid } from 'nanoid' import { ComponentId, componentPropTypes, ComponentType, rootComponentId, SavedComponentConfigs, } from 'types' import { ComponentTemplate, componentTemplates } from './componentTemplates' const hydrateComponent = ( componentTemplate: ComponentTemplate, parentComponentId: ComponentId, componentConfigs: SavedComponentConfigs, knownComponentId?: ComponentId ): ComponentId => { const componentId = knownComponentId ?? nanoid() componentConfigs[componentId] = { componentType: componentTemplate.componentType, props: {}, parentComponentId, childComponentIds: [], } const { props, children } = componentTemplate if (props) { componentConfigs[componentId].props = { ...props } } if (children) { componentConfigs[componentId].childComponentIds = children.map( (childComponentTemplate) => hydrateComponent(childComponentTemplate, componentId, componentConfigs) ) } return componentId } export const createComponent = ( componentType: ComponentType, selectedComponentIds: Array<ComponentId>, componentConfigs: SavedComponentConfigs ): ComponentId => { // Initialize root component if it does not exist if (componentConfigs[rootComponentId] === undefined) { componentConfigs[rootComponentId] = { childComponentIds: [], parentComponentId: '__null__', } } const newComponentId = nanoid() let parentComponentId: ComponentId if (selectedComponentIds.length === 1) { const selectedId = selectedComponentIds[0] // If there is exactly 1 component selected const firstSelectedComponentConfig = componentConfigs[selectedId] if ( componentPropTypes[ componentConfigs[selectedId].componentType ].hasOwnProperty('children') ) { // If the component allows children, make the new component a child parentComponentId = selectedId firstSelectedComponentConfig.childComponentIds.push(newComponentId) } else { // Otherwise, make the new component the next sibling of the selected component parentComponentId = componentConfigs[selectedId].parentComponentId const siblingIds = componentConfigs[parentComponentId].childComponentIds const selectedIdIndex = siblingIds.indexOf(selectedId) siblingIds.splice(selectedIdIndex + 1, 0, newComponentId) } } else { // If 0 or more than 1 components are selected, add the new component at the top level parentComponentId = rootComponentId componentConfigs[rootComponentId].childComponentIds.push(newComponentId) } const componentTemplate = componentTemplates[componentType] if (componentTemplate) { hydrateComponent( componentTemplate, parentComponentId, componentConfigs, newComponentId ) } else { componentConfigs[newComponentId] = { componentType, props: {}, parentComponentId, childComponentIds: [], } } return newComponentId }
<?php namespace App\Http\Controllers; use App\Models\Order; use App\Models\Products; use Illuminate\Http\Request; class CheckoutHistoryController extends Controller { public function index() { $user = session('customer'); if (!$user) { return redirect('login')->with('success', 'Vui lòng đăng nhập!'); } $data['orderHistory'] = Order::where('customer_id', session('customer')->customer_id)->orderByDesc('status')->orderByDesc('create_at')->with('orderDetail.product')->paginate(10); // dd(session('customer')); 31 // dd($data); return view('client.navigation.checkout.history', $data); } public function updateOrderStatus($id) { $order = Order::find($id); $orderUpdateProduct = Order::with('orderDetail.product')->find($id); if (!$orderUpdateProduct) { return redirect()->route('checkout-history')->with('success', 'Đơn hàng không tồn tại'); } $order->status = 'đã giao'; $order->update(); foreach ($orderUpdateProduct->orderDetail as $index => $od) { $product = Products::find($od->product->product_id); if ($product) { $product->quantity -= $od->quantity; $product->update(); } } return redirect()->route('checkout-history')->with('success', 'Đã xác nhận hoàn thành đơn hàng'); } public function deleteOrder($id) { $order = Order::find($id); $order->status = 'đã hủy'; $order->update(); return redirect()->route('checkout-history')->with('success', 'Đã xác nhận hoàn thành đơn hàng'); } }
--no create database ? --CREATE DATABASE gran_vivero DROP SCHEMA IF EXISTS public CASCADE; CREATE SCHEMA public; CREATE TYPE asoleo_planta AS ENUM ('sol', 'sombra', 'resolana'); CREATE TYPE metodo_pago AS ENUM ('efectivo', 'debito', 'credito', 'transferencia', 'otro'); CREATE TABLE Planta ( NombrePlanta varchar(256), Cuidado text, Genero varchar(128), Precio integer,--decimal en centavos TipoAsoleo asoleo_planta, TipoOrigen varchar(128), FechaGerminacion date ); CREATE TABLE Vivero ( NombreVivero varchar(256), FechaApertura date, Estado varchar(256), CP char(5),--son 5 números fijos, los representamos como cadenas para evitar confusión en operaciones Calle varchar(256), NumeroExterior varchar(16)--Hay números que llevan letra, como en duplexes ); CREATE TABLE ViveroTelefono ( NombreVivero varchar(256), Telefono char(10) ); CREATE TABLE Cliente ( IdCliente integer, FechaNacimiento date, Nombre varchar(128), ApellidoP varchar(128), ApellidoM varchar(128), Estado varchar(256), CP char(5), Calle varchar(256), NumeroExterior varchar(16) ); CREATE TABLE ClienteTelefono ( IdCliente integer, Telefono char(10) ); CREATE TABLE ClienteCorreoElectronico ( IdCliente integer, CorreoElectronico varchar(128) ); CREATE TABLE VentaElectronica ( IdVentaElectronica integer, IdCliente integer, NumeroProductos integer, MetodoPago metodo_pago, NumeroSeguimiento integer, FechaPedido date, Estado varchar(256), CP char(5), Calle varchar(256), NumeroExterior varchar(16) ); CREATE TABLE Empleado ( IdEmpleado integer, NombreVivero varchar(256), FechaNacimiento date, Nombre varchar(128), ApellidoP varchar(128), ApellidoM varchar(128), Estado varchar(256), CP char(5), Calle varchar(256), NumeroExterior varchar(16), Rol varchar(128), --{gerente, cuidador de plantas, encargado de mostrar a cliente, cajero} Salario integer --decimal en centavos ); CREATE TABLE EmpleadoTelefono ( IdEmpleado integer, Telefono char(10) ); CREATE TABLE EmpleadoCorreoElectronico ( IdEmpleado integer, CorreoElectronico varchar(128) ); CREATE TABLE VentaFisica ( IdVentaFisica integer, IdCliente integer, AyudarIdEmpleado integer, CobrarIdEmpleado integer, NumeroProductos integer, MetodoPago metodo_pago ); CREATE TABLE EntregarVentaFisica ( IdVentaFisica integer, NombrePlanta varchar(256) ); CREATE TABLE EntregarVentaElectronica ( IdVentaElectronica integer, NombrePlanta varchar(256) ); --Se llamaba En CREATE TABLE EstarEn ( NombreVivero varchar(256), NombrePlanta varchar(256), NumeroDePlantasVivero integer ); --- Restricciones: --PK ALTER TABLE Planta ADD PRIMARY KEY (NombrePlanta); ALTER TABLE Vivero ADD PRIMARY KEY (NombreVivero); ALTER TABLE ViveroTelefono ADD PRIMARY KEY (NombreVivero, Telefono); ALTER TABLE Cliente ADD PRIMARY KEY (IdCliente); ALTER TABLE ClienteTelefono ADD PRIMARY KEY (IdCliente, Telefono); ALTER TABLE ClienteCorreoElectronico ADD PRIMARY KEY (IdCliente, CorreoElectronico); ALTER TABLE VentaElectronica ADD PRIMARY KEY (IdVentaElectronica); ALTER TABLE Empleado ADD PRIMARY KEY (IdEmpleado); ALTER TABLE EmpleadoTelefono ADD PRIMARY KEY (IdEmpleado, Telefono); ALTER TABLE EmpleadoCorreoElectronico ADD PRIMARY KEY (IdEmpleado, CorreoElectronico); ALTER TABLE VentaFisica ADD PRIMARY KEY (IdVentaFisica); --FK ALTER TABLE Empleado ADD FOREIGN KEY (NombreVivero) REFERENCES Vivero(NombreVivero); ALTER TABLE VentaElectronica ADD FOREIGN KEY (IdCliente) REFERENCES Cliente(IdCliente); ALTER TABLE VentaFisica ADD FOREIGN KEY (IdCliente) REFERENCES Cliente(IdCliente); ALTER TABLE VentaFisica ADD FOREIGN KEY (AyudarIdEmpleado) REFERENCES Empleado(IdEmpleado); ALTER TABLE VentaFisica ADD FOREIGN KEY (CobrarIdEmpleado) REFERENCES Empleado(IdEmpleado); ALTER TABLE EntregarVentaElectronica ADD FOREIGN KEY (IdVentaElectronica) REFERENCES VentaElectronica(IdVentaElectronica); ALTER TABLE EntregarVentaElectronica ADD FOREIGN KEY (NombrePlanta) REFERENCES Planta(NombrePlanta); ALTER TABLE EntregarVentaFisica ADD FOREIGN KEY (IdVentaFisica) REFERENCES VentaFisica(IdVentaFisica); ALTER TABLE EntregarVentaFisica ADD FOREIGN KEY (NombrePlanta) REFERENCES Planta(NombrePlanta); ALTER TABLE EstarEn ADD FOREIGN KEY (NombreVivero) REFERENCES Vivero(NombreVivero); ALTER TABLE EstarEn ADD FOREIGN KEY (NombrePlanta) REFERENCES Planta(NombrePlanta); -- restricciones de dominio ALTER TABLE Planta ALTER COLUMN Genero SET NOT NULL; ALTER TABLE Planta ALTER COLUMN Precio SET NOT NULL; ALTER TABLE Planta ALTER COLUMN TipoAsoleo SET NOT NULL; ALTER TABLE Planta ALTER COLUMN TipoOrigen SET NOT NULL; ALTER TABLE Planta ALTER COLUMN FechaGerminacion SET NOT NULL; ALTER TABLE Planta ADD Constraint dinero CHECK (Precio >= 0); ALTER TABLE Vivero ALTER COLUMN FechaApertura SET NOT NULL; ALTER TABLE Vivero ALTER COLUMN Estado SET NOT NULL; ALTER TABLE Vivero ALTER COLUMN CP SET NOT NULL; ALTER TABLE Vivero ALTER COLUMN Calle SET NOT NULL; ALTER TABLE Vivero ALTER COLUMN NumeroExterior SET NOT NULL; ALTER TABLE Cliente ALTER COLUMN FechaNacimiento SET NOT NULL; ALTER TABLE CLiente ALTER COLUMN Nombre SET NOT NULL; ALTER TABLE Cliente ALTER COLUMN ApellidoP SET NOT NULL; ALTER TABLE Cliente ALTER COLUMN ApellidoM SET NOT NULL; ALTER TABLE Cliente ALTER COLUMN Estado SET NOT NULL; ALTER TABLE Cliente ALTER COLUMN CP SET NOT NULL; ALTER TABLE Cliente ALTER COLUMN Calle SET NOT NULL; ALTER TABLE Cliente ALTER COLUMN NumeroExterior SET NOT NULL; ALTER TABLE VentaElectronica ALTER COLUMN NumeroProductos SET NOT NULL; ALTER TABLE VentaElectronica ALTER COLUMN MetodoPago SET NOT NULL; ALTER TABLE VentaElectronica ALTER COLUMN NumeroSeguimiento SET NOT NULL; ALTER TABLE VentaElectronica ALTER COLUMN FechaPedido SET NOT NULL; ALTER TABLE VentaElectronica ALTER COLUMN Estado SET NOT NULL; ALTER TABLE VentaElectronica ALTER COLUMN CP SET NOT NULL; ALTER TABLE VentaElectronica ALTER COLUMN Calle SET NOT NULL; ALTER TABLE VentaElectronica ALTER COLUMN NumeroExterior SET NOT NULL; ALTER TABLE Empleado ALTER COLUMN FechaNacimiento SET NOT NULL; ALTER TABLE Empleado ALTER COLUMN Nombre SET NOT NULL; ALTER TABLE Empleado ALTER COLUMN ApellidoP SET NOT NULL; ALTER TABLE Empleado ALTER COLUMN ApellidoM SET NOT NULL; ALTER TABLE Empleado ALTER COLUMN Estado SET NOT NULL; ALTER TABLE Empleado ALTER COLUMN CP SET NOT NULL; ALTER TABLE Empleado ALTER COLUMN Calle SET NOT NULL; ALTER TABLE Empleado ALTER COLUMN NumeroExterior SET NOT NULL; ALTER TABLE Empleado ALTER COLUMN Rol SET NOT NULL; ALTER TABLE Empleado ALTER COLUMN Salario SET NOT NULL; ALTER TABLE Empleado ADD Constraint dinero CHECK (Salario >= 0); ALTER TABLE VentaFisica ALTER COLUMN CobrarIdEmpleado SET NOT NULL; ALTER TABLE VentaFisica ALTER COLUMN NumeroProductos SET NOT NULL; ALTER TABLE VentaFisica ALTER COLUMN MetodoPago SET NOT NULL; ALTER TABLE EntregarVentaFisica ALTER COLUMN IdVentaFisica SET NOT NULL; ALTER TABLE EntregarVentaFisica ALTER COLUMN NombrePlanta; ALTER TABLE EntregarVentaElectronica ALTER COLUMN IdVentaFisica SET NOT NULL; ALTER TABLE EntregarVentaElectronica ALTER COLUMN NombrePlanta SET NOT NULL; ALTER TABLE EstarEn ALTER COLUMN NombreVivero SET NOT NULL; ALTER TABLE EstarEn ALTER COLUMN NombrePlanta SET NOT NULL; ALTER TABLE EstarEn ALTER COLUMN NumeroDePlantasVivero SET NOT NULL;
Chapter 14 Hierarchical Clustering Given :math:`n` points in a :math:`d`-dimensional space, the goal of hierarchical clustering is to create a sequence of nested partitions, which can be conveniently visualized via a tree or hierarchy of clusters, also called the cluster *dendrogram*. There are two main algorithmic approaches to mine hierarchical clusters: agglomerative and divisive. Agglomerative strategies work in a bottom-up manner. That is, starting with each of the :math:`n` points in a separate cluster, they repeatedly merge the most similar pair of clusters until all points are members of the same cluster. Divisive strategies do just the opposite, working in a top-down manner. Starting with all the points in the same cluster, they recursively split the clusters until all points are in separate clusters. 14.1 Preliminaries ------------------ Given a dataset :math:`\D` comprising :math:`n` points :math:`\x_i\in\R^D(i=1,2,\cds,n)`, a clustering :math:`\cl{C}=\{C_1,\cds,C_k\}` is a partition of :math:`\D`, that is, each cluster is a set of points :math:`C_i\subseteq\D`, such that the clusters are pairwise disjoint :math:`C_i\cap C_j=\emptyset` (for all :math:`i\neq j`), and :math:`\cup_{i=1}^kC_i=\D`. A clustering :math:`\cl{A}=\{A_1,\cds,A_r\}` is said to be nested in another clustering :math:`\cl{B}=\{B_1,\cds,\B_s\}` if and only if :math:`r>s`, and for each cluster :math:`A_i\in\cl{A}`, there exists a cluster :math:`B_j\in\cl{B}`, such that :math:`A_i\subseteq B_j`. Hierarchical clustering yields a sequence of :math:`n` nested partitions :math:`\cl{C}_1,\cds,\cl{C}_n`. The clustering :math:`\cl{C}_{t-1}` is nested in the clustering :math:`\cl{C}_t`. The cluster dendrogram is a rooted binary tree that captures this nesting structure, with edges between cluster :math:`C_i\in\cl{C}_{i-1}` and cluster :math:`C_j\in\cl{C}_t` if :math:`C_i` is nested in :math:`C_j`, that is, if :math:`C_i\subset C_j`. **Number of Hierarchical Clusterings** The number of different nested or hierarchical clusterings corresponds to the number of different binary rooted trees or dendrograms with :math:`n` leaves with distinct labels. Any tree with :math:`t` nodes has :math:`t−1` edges. Also, any rooted binary tree with :math:`m` leaves has :math:`m−1` internal nodes. Thus, a dendrogram with :math:`m` leaf nodes has a total of :math:`t=m+m−1=2m−1` nodes, and consequently :math:`t−1=2m−2` edges. The total number of different dendrograms with :math:`n` leaves is obtained by the following product: .. math:: \prod_{m=1}^{n-1}(2m-1)=1\times 3\times 5\times 7\times\cds\times(2n-3)=(2n-3)!! 14.2 Agglomerative Hierarchical Clustering ------------------------------------------ .. image:: ../_static/Algo14.1.png 14.2.1 Distance between Clusters ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The between-cluster distances are ultimately based on the distance between two points, which is typically computed using the Euclidean distance or :math:`L_2` -*norm*, defined as .. math:: \lv\x-\y\rv=\bigg(\sum_{i=1}^d(x_i-y_i)^2\bigg)^{1/2} **Single Link** Given two clusters :math:`C_i` and :math:`C_j`, the distance between them, denoted :math:`\delta(C_i,C_j)`, is defined as the minimum distance between a point in :math:`C_i` and a point in :math:`C_j` .. note:: :math:`\delta(C_i,C_j)=\min\{\lv\x-\y\rv|\x\in C_i,\y\in C_j\}` **Complete Link** The distance between two clusters is defined as the maximum distance between a point in :math:`C_i` and a point in :math:`C_j`: .. note:: :math:`\delta(C_i,C_j)=\max\{\lv\x-\y\rv|\x\in C_i,\y\in C_j\}` **Group Average** The distance between two clusters is defined as the average pairwise distance between points in :math:`C_i` and :math:`C_j`: .. note:: :math:`\dp\delta(C_i,C_j)=\frac{\sum_{\x\in C_i}\sum_{\y\in C_j}\lv\x-\y\rv}{n_i\cd n_j}` where :math:`n_i=|C_i|` denotes the number of points in cluster :math:`C_i`. **Mean Distance** The distance between two clusters is defined as the distance between the means or centroids of the two clusters: .. note:: :math:`\delta(C_i,C_j)=\lv\mmu_i-\mmu_j\rv` where :math:`\mmu_i=\frac{1}{n_i}\sum_{\x\in C_i}\x`. **Minimum Variance: Ward's Method** The sum of a squared errors (SSE) for a given cluster :math:`C_i` is given as .. math:: SSE_i&=\sum_{\x\in C_i}\lv\x-\mmu_i\rv^2 &=\sum_{\x\in C_i}\lv\x-\mmu_i\rv^2 &=\sum_{\x\in C_i}\x^T\x-2\sum_{\x\in C_i}\x^T\mmu_i+\sum_{\x\in C_i}\mmu_i^T\mmu_i &=\bigg(\sum_{\x\in C_i}\x^T\x\bigg)-n_i\mmu_i^T\mmu_i The SSE for a clustering :math:`\cl{C}=\{C_1,\cds,C_m\}` is given as .. math:: SSE=\sum_{i=1}^mSSE_i=\sum_{i=1}^m\sum_{\x\in C_i}\lv\x-\mmu_i\rv^2 After simplification, we get .. note:: :math:`\dp\delta(C_i,C_j)=\bigg(\frac{n_in_j}{n_i+n_j}\bigg)\lv\mmu_i-\mmu_j\rv^2` 14.2.2 Updating Distance Matrix ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Whenever two clusters :math:`C_i` and :math:`C_j` are merged into :math:`C_{ij}`, we need to update the distance matrix by recomputing the distances from the newly created cluster :math:`C_{ij}` to all other clusters :math:`C_r` (:math:`r \ne i` and :math:`r \ne j`). The Lance–Williams formula provides a general equation to recompute the distances for all of the cluster proximity measures we considered earlier; it is given as .. note:: :math:`\delta(C_{ij},C_r)=\alpha_i\cd\delta(C_i,C_r)+\alpha_j\cd\delta(C_j,C_r)+\beta\cd\delta(C_i,C_j)+\gamma\cd|\delta(C_i,C_r)-\delta(C_j,C_r)|` The coefficients :math:`\alpha_i,\alpha_j,\beta` and :math:`\gamma` differ from one measure to another. 14.2.3 Computational Complexity ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The computational complexity of hierarchical clustering is :math:`O(n^2\log n)`.
import {PermissionsAndroid, Platform} from 'react-native' import {CameraRoll} from '@react-native-camera-roll/camera-roll' async function hasAndroidPermission() { const getCheckPermissionPromise = () => { if (Number(Platform.Version) >= 33) { return Promise.all([ PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.READ_MEDIA_IMAGES), PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.READ_MEDIA_VIDEO), ]).then( ([hasReadMediaImagesPermission, hasReadMediaVideoPermission]) => hasReadMediaImagesPermission && hasReadMediaVideoPermission ) } else { return PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE) } } const hasPermission = await getCheckPermissionPromise() if (hasPermission) { return true } const getRequestPermissionPromise = () => { if (Number(Platform.Version) >= 33) { return PermissionsAndroid.requestMultiple([ PermissionsAndroid.PERMISSIONS.READ_MEDIA_IMAGES, PermissionsAndroid.PERMISSIONS.READ_MEDIA_VIDEO, ]).then( statuses => statuses[PermissionsAndroid.PERMISSIONS.READ_MEDIA_IMAGES] === PermissionsAndroid.RESULTS.GRANTED && statuses[PermissionsAndroid.PERMISSIONS.READ_MEDIA_VIDEO] === PermissionsAndroid.RESULTS.GRANTED ) } else { return PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE).then( status => status === PermissionsAndroid.RESULTS.GRANTED ) } } return await getRequestPermissionPromise() } type FileType = 'photo' | 'video' | 'auto' export async function savePicture(tag: string, type: FileType) { if (Platform.OS === 'android' && !(await hasAndroidPermission())) { return } CameraRoll.save(tag, {type}) }
/* * Copyright 2023-2023 the original author or authors. * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.codebootup.compare interface Difference data class MissingDirectory(val directory: String) : Difference data class ExtraDirectory(val directory: String) : Difference data class MissingFile(val file: String) : Difference data class ExtraFile(val file: String) : Difference data class ContentDifference( val file: String, val deltas: List<ContentDelta>, ) : Difference data class ContentDelta( val original: ContentChunk, val revised: ContentChunk, val type: ContentDeltaType, ) { enum class ContentDeltaType { CHANGE, INSERT, DELETE } } data class ContentChunk( val position: Int, val lines: List<ContentLine>, ) data class ContentLine(val line: String) class PrettyPrintDifferences { companion object { const val level1 = "\n" const val level2 = "\n\t" const val level3 = "\n\t\t" const val twoBlankLines = "\n\n" } fun print(differences: List<Difference>): String { val contentDifferences = differences.filterIsInstance<ContentDifference>().joinToString(level1) { toString(it) } val missingFiles = differences.filterIsInstance<MissingFile>().sortedBy { it.file }.joinToString(level2) { it.file } val missingDirectories = differences.filterIsInstance<MissingDirectory>().sortedBy { it.directory }.joinToString(level2) { it.directory } val extraFiles = differences.filterIsInstance<ExtraFile>().sortedBy { it.file }.joinToString(level2) { it.file } val extraDirectories = differences.filterIsInstance<ExtraDirectory>().sortedBy { it.directory }.joinToString(level2) { it.directory } val missingDirectoriesString = if (missingDirectories.isNotBlank()) "Missing Directories:$level2$missingDirectories" else "" val missingFilesString = if (missingFiles.isNotBlank()) "Missing Files:$level2$missingFiles" else "" val extraDirectoriesString = if (extraDirectories.isNotBlank()) "Extra Directories:$level2$extraDirectories" else "" val extraFilesString = if (extraFiles.isNotBlank()) "Extra Files:$level2$extraFiles" else "" return missingDirectoriesString + twoBlankLines + missingFilesString + twoBlankLines + extraDirectoriesString + twoBlankLines + extraFilesString + twoBlankLines + contentDifferences } private fun toString(contentDifference: ContentDifference): String { val deltas = contentDifference.deltas.map { val originalLines = it.original.lines.joinToString(separator = level3) { l -> l.line } val revisedLines = it.revised.lines.joinToString(separator = level3) { l -> l.line } when (it.type) { ContentDelta.ContentDeltaType.CHANGE -> "${level2}Changed content at line ${it.original.position + 1}:" + "${level3}from ->" + "${level3}$originalLines" + "${level3}to ->" + "${level3}$revisedLines\n" ContentDelta.ContentDeltaType.DELETE -> "${level2}Missing content at line ${it.original.position + 1}:" + "${level3}$originalLines\n" ContentDelta.ContentDeltaType.INSERT -> "${level2}Inserted content at line ${it.revised.position + 1}:" + "${level3}$revisedLines\n" } } val deltaAsString = deltas.joinToString("") return "${contentDifference.file}:$deltaAsString" } }
const express = require("express"); const path = require("path"); const app = express(); const port = 8000; const bodyparser = require("body-parser"); const mongoose = require('mongoose'); const db='mongodb+srv://mydanceacademy:[email protected]/danceacademy?retryWrites=true&w=majority'; main().catch(err => console.log(err)); async function main() { await mongoose.connect(db); } const contactschema = new mongoose.Schema({ name: String, email: String, phone: String, address: String, desc: String }); const contactus = mongoose.model('contactus', contactschema); // EXPRESS SPECIFIC STUFF app.use(bodyparser.urlencoded({ extended: true })); app.use(bodyparser.json()); app.use('/static', express.static('static')) // For serving static files // app.use(express.urlencoded()) // PUG SPECIFIC STUFF app.set('view engine', 'pug') // Set the template engine as pug app.set('views', path.join(__dirname, 'views')) // Set the views directory // END POINT app.get('/', (req, res) => { const params = {} res.status(200).render('home.pug', params); }) app.get('/contact', (req, res) => { const params = {} res.status(200).render('contact.pug', params); }) app.post('/contact',(req,res)=>{ var mydata= new contactus(req.body); mydata.save().then(()=>{ res.send("This item has been saved to the database"); }).catch(()=>{ res.status(400).send("Item was not saved yet into the database"); }); }) app.listen(port, () => { console.log(`The application started successfully on port ${port}`) })
import React, {useMemo} from 'react'; import AppShell from "./AppShell"; import {Routes} from "../components/route"; import {FetchService, Store, WindowSizeContext} from "../components/utils"; import {BaseState} from "./BaseState"; import {Profile} from "./profile"; import PocketBase from "pocketbase"; interface AppProps<T> { mobileOnly: boolean, stateInitValue: T, onProfileChange: (next: Profile, prev: (Profile | undefined), store: Store<T>) => void, pocketBase: PocketBase, fetchService: FetchService, routes: Routes } type App<T extends BaseState> = (props: AppProps<T>) => JSX.Element; export function createApp<T extends BaseState>(): App<T> { return Application<T>; } function Application<T extends BaseState>(props: AppProps<T>) { let {width, height} = useMemo(() => ({width: window.innerWidth, height: window.innerHeight}), []); const isLargeScreen = width > 490; const {mobileOnly} = props; let scale = 1; if (mobileOnly && isLargeScreen) { width = 390; height = 844; scale = (window.innerHeight - 20) / height; } const windowsSizeContextProviderValue = useMemo(() => ({width, height}), [height, width]); if (mobileOnly && isLargeScreen) { return <div style={{ display: 'flex', height: '100%', overflow: 'hidden', alignItems: 'center', justifyContent: 'center', boxSizing: 'border-box' }}> <WindowSizeContext.Provider value={windowsSizeContextProviderValue}> <div style={{ display: 'flex', flexDirection: 'column', height, width, flexShrink: 0, borderRadius: 30, overflow: 'auto', boxShadow: '0 5px 5px 0 rgba(0,0,0,0.5)', border: '10px solid rgba(0,0,0,1)', transform: `scale(${scale})` }}> <AppShell initValue={props.stateInitValue} onProfileChange={props.onProfileChange} pocketBase={props.pocketBase} routes={props.routes} fetchService={props.fetchService}/> </div> </WindowSizeContext.Provider> </div> } return <div style={{display: 'flex', height: '100%', overflow: 'auto'}}> <WindowSizeContext.Provider value={windowsSizeContextProviderValue}> <div style={{ display: 'flex', flexDirection: 'column', height, width, flexShrink: 0, overflow: 'auto', margin: 0, borderRadius: 0 }}> <AppShell initValue={props.stateInitValue} onProfileChange={props.onProfileChange} pocketBase={props.pocketBase} routes={props.routes} fetchService={props.fetchService}/> </div> </WindowSizeContext.Provider> </div> }
<template> <Wrapper> <div class="container-cart"> <h2>Your Cart</h2> <!-- --> <h3>Total Amount: ₿ {{ cartTotal }}</h3> <ul> <!-- a for each loop for our cart array in our index.js, which we pass into our CartCard as PROPS --> <CartCard v-for="product in cartProducts" :key="product.id" :id="product.id" :type="product.type" :brand="product.brand" :model="product.model" :color="product.color" :capacity="product.capacity" :imgSrc="product.imgSrc" :price="product.price" :qty="product.qty" ></CartCard> </ul> </div> </Wrapper> </template> <script> import CartCard from "../components/CartCard"; import Wrapper from "../components/Wrapper"; export default { name: "MyCard", components: { CartCard, Wrapper }, computed: { // we calculate the total in our cart cartTotal() { return this.$store.getters["totalSum"].toFixed(2); }, // we get the cart array which originally started empty, but now has some products in it cartProducts() { return this.$store.getters["cart"]; }, }, }; </script> <style scoped> .container-cart { display: flex; flex-direction: column; } h2 { color: #292929; text-align: center; border-bottom: 2px solid #ccc; padding-bottom: 1rem; } h3 { text-align: center; } ul { list-style: none; margin: 0; padding: 0; } </style>
from flask_wtf import FlaskForm from flask_login import current_user from flask_wtf.file import FileField, FileAllowed from wtforms import StringField, PasswordField, SubmitField, BooleanField, TextAreaField from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError from flaskapp.models import User class RegistrationForm(FlaskForm): username = StringField('Username', validators=[DataRequired(), Length(min=2, max=20)]) email = StringField('Email', validators=[DataRequired(), Email()]) password = PasswordField('Password', validators=[DataRequired()]) confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')]) submit = SubmitField('Sign Up') def validate_username(self, username): user = User.query.filter_by(username=username.data).first() if user: raise ValidationError('This username is already used by another user. Please choose a different one.') def validate_email(self, email): user = User.query.filter_by(email=email.data).first() if user: raise ValidationError('This email address is already used by another user. Please choose a different one.') class LoginForm(FlaskForm): email = StringField('Email', validators=[DataRequired(), Email()]) password = PasswordField('Password', validators=[DataRequired()]) remember = BooleanField('Remember Me') submit = SubmitField('Login') class UpdateAccountForm(FlaskForm): username = StringField('Username', validators=[DataRequired(), Length(min=2, max=20)]) email = StringField('Email', validators=[DataRequired(), Email()]) picture = FileField('Update Profile Image', validators=[FileAllowed(['jpg', 'png', 'gif'])]) submit = SubmitField('Update') def validate_username(self, username): if not username.data == current_user.username: user = User.query.filter_by(username=username.data).first() if user: raise ValidationError('This username is already used by another user. Please choose a different one.') def validate_email(self, email): if not email.data == current_user.email: user = User.query.filter_by(email=email.data).first() if user: raise ValidationError('This email address is already used by another user. Please choose a different one.') # Form for storing postings class PostForm(FlaskForm): title = StringField('Title', validators=[DataRequired()]) content = TextAreaField('Content', validators=[DataRequired()]) submit = SubmitField('Post') # References # This code was adapted from a post by C. Schafer. # Accessed: 13-1-2023, 14-1-2023 # https://www.youtube.com/watch?v=UIJKdCIEXUQ&list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH&index=3 # https://www.youtube.com/watch?v=CSHx6eCkmv0&list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH&index=6 # https://www.youtube.com/watch?v=803Ei2Sq-Zs&list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH&index=7 # https://www.youtube.com/watch?v=u0oDDZrDz9U&list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH&index=8
// // EGCaptureController.m // ImageProcessing // // Created by Chris Marcellino on 8/26/10. // Copyright 2010 Chris Marcellino. All rights reserved. // #import "EGCaptureController.h" #import <AVFoundation/AVFoundation.h> #import <QuartzCore/QuartzCore.h> #import "ShareKit.h" #import "opencv2/opencv.hpp" #import "EGEdgyView.h" #import "UIImage-OpenCVExtensions.h" #import "Binarization.hpp" // for static inlines #import "ImageOrientationAccelerometer.h" #import "EGSHKActionSheet.h" @interface EGCaptureController () - (void)setDefaultSettings; - (void)startRunning; - (void)stopRunning; - (void)stopRunningAndResetSettings; - (void)updateConfiguration; - (void)orientationDidChange; - (void)thresholdChanged:(id)sender; - (void)cameraToggled:(id)sender; - (void)colorToggled:(id)sender; - (void)torchToggled:(id)sender; - (void)captureImage:(id)sender; @end @implementation EGCaptureController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { sampleProcessingQueue = dispatch_queue_create("sample processing", NULL); // Set up the session and output #if TARGET_OS_EMBEDDED session = [[AVCaptureSession alloc] init]; captureVideoDataOuput = [[AVCaptureVideoDataOutput alloc] init]; [captureVideoDataOuput setSampleBufferDelegate:(id<AVCaptureVideoDataOutputSampleBufferDelegate>)self queue:sampleProcessingQueue]; // Try to use YpCbCr as a first option for performance fallBackToBGRA32Sampling = NO; double osVersion = [[[UIDevice currentDevice] systemVersion] doubleValue]; if (osVersion == 0.0 || osVersion >= 4.2) { // Try to use bi-planar YpCbCr first so that we can quickly extract Y' NSDictionary *settings = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_420YpCbCr8BiPlanarFullRange] forKey:(id)kCVPixelBufferPixelFormatTypeKey]; @try { [captureVideoDataOuput setVideoSettings:settings]; } @catch (...) { fallBackToBGRA32Sampling = YES; } } else { fallBackToBGRA32Sampling = YES; } if (fallBackToBGRA32Sampling) { NSLog(@"Falling back to BGRA32 sampling"); // Fall back to BGRA32 NSDictionary *settings = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey]; [captureVideoDataOuput setVideoSettings:settings]; } [session addOutput:captureVideoDataOuput]; #endif [self setDefaultSettings]; } return self; } - (void)dealloc { #if TARGET_OS_EMBEDDED [session removeOutput:captureVideoDataOuput]; #endif } - (void)setDefaultSettings { // Default to the front camera and a moderate threshold colorEdges = YES; deviceIndex = 1; cannyThreshold = 120; } - (void)loadView { // Create the preview layer and view EGEdgyView *view = [[EGEdgyView alloc] initWithFrame:CGRectZero]; [self setView:view]; [[view torchButton] addTarget:self action:@selector(torchToggled:) forControlEvents:UIControlEventTouchUpInside]; [[view captureButton] addTarget:self action:@selector(captureImage:) forControlEvents:UIControlEventTouchUpInside]; [[view cameraToggle] addTarget:self action:@selector(cameraToggled:) forControlEvents:UIControlEventTouchUpInside]; [[view colorToggle] addTarget:self action:@selector(colorToggled:) forControlEvents:UIControlEventTouchUpInside]; [[view cannyThresholdSlider] addTarget:self action:@selector(thresholdChanged:) forControlEvents:UIControlEventValueChanged]; [[view bannerView] setDelegate:self]; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; // Monitor for orientation updates [[ImageOrientationAccelerometer sharedInstance] beginGeneratingDeviceOrientationNotifications]; NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter]; [defaultCenter addObserver:self selector:@selector(orientationDidChange) name:DeviceOrientationDidChangeNotification object:nil]; // Listen for app relaunch [defaultCenter addObserver:self selector:@selector(stopRunningAndResetSettings) name:UIApplicationDidEnterBackgroundNotification object:nil]; [defaultCenter addObserver:self selector:@selector(startRunning) name:UIApplicationDidBecomeActiveNotification object:nil]; // Listen for device updates [defaultCenter addObserver:self selector:@selector(updateConfiguration) name:AVCaptureDeviceWasConnectedNotification object:nil]; [defaultCenter addObserver:self selector:@selector(updateConfiguration) name:AVCaptureDeviceWasDisconnectedNotification object:nil]; [self startRunning]; [self orientationDidChange]; } - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; [self stopRunning]; [[ImageOrientationAccelerometer sharedInstance] endGeneratingDeviceOrientationNotifications]; NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter]; [defaultCenter removeObserver:self name:DeviceOrientationDidChangeNotification object:nil]; [defaultCenter removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil]; [defaultCenter removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil]; [defaultCenter removeObserver:self name:AVCaptureDeviceWasConnectedNotification object:nil]; [defaultCenter removeObserver:self name:AVCaptureDeviceWasDisconnectedNotification object:nil]; } - (void)startRunning { [self updateConfiguration]; [self performSelector:@selector(updateConfiguration) withObject:nil afterDelay:2.0]; // work around OS torch bugs #if TARGET_OS_EMBEDDED [session startRunning]; #endif } - (void)stopRunning { #if TARGET_OS_EMBEDDED [session stopRunning]; #endif } - (void)stopRunningAndResetSettings { [self setDefaultSettings]; [self stopRunning]; } - (void)updateConfiguration { EGEdgyView *view = (EGEdgyView *)[self view]; #if TARGET_OS_EMBEDDED // Create the session [session beginConfiguration]; // Choose the proper device and hide the device button if there is 0 or 1 devices NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]; [[view cameraToggle] setHidden:[devices count] <= 1]; deviceIndex %= [devices count]; if (!currentDevice || ![[devices objectAtIndex:deviceIndex] isEqual:currentDevice]) { currentDevice = [devices objectAtIndex:deviceIndex]; // Create the input and add it to the session if (input) { [session removeInput:input]; } NSError *error = nil; input = [[AVCaptureDeviceInput alloc] initWithDevice:currentDevice error:&error]; NSAssert1(input, @"no AVCaptureDeviceInput available: %@", error); [session addInput:input]; } // Set the configuration if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad && [session canSetSessionPreset:AVCaptureSessionPreset640x480]) { [session setSessionPreset:AVCaptureSessionPreset640x480]; } else if ([session canSetSessionPreset:AVCaptureSessionPresetMedium]) { [session setSessionPreset:AVCaptureSessionPresetMedium]; } [currentDevice lockForConfiguration:nil]; BOOL hasTorch = [currentDevice hasTorch]; [[view torchButton] setHidden:!hasTorch]; if (hasTorch) { [currentDevice setTorchMode:AVCaptureTorchModeOff]; // work around OS bugs [currentDevice setTorchMode:torchOn ? AVCaptureTorchModeOn : AVCaptureTorchModeOff]; [[view torchButton] setSelected:torchOn]; } // Limit the frame rate [currentDevice setActiveVideoMinFrameDuration:CMTimeMake(1, 10)]; // 10 fps max [currentDevice unlockForConfiguration]; // Ensure the image view is rotated properly BOOL front = [currentDevice position] == AVCaptureDevicePositionFront; CGAffineTransform transform = CGAffineTransformMakeRotation(front ? -M_PI_2 : M_PI_2); if (front) { transform = CGAffineTransformScale(transform, -1.0, 1.0); } [[view imageView] setTransform:transform]; [view setNeedsLayout]; [session commitConfiguration]; #endif // Ensure the slider value matches the settings [[view cannyThresholdSlider] setValue:cannyThreshold]; // Update the image orientation to include the mirroring value as appropriate [self orientationDidChange]; } - (void)orientationDidChange { UIDeviceOrientation orientation = [[ImageOrientationAccelerometer sharedInstance] deviceOrientation]; if (UIDeviceOrientationIsValidInterfaceOrientation(orientation)) { CGFloat buttonRotation; UIInterfaceOrientation interfaceOrientation; // Store the last unambigous orientation if not in capture mode switch (orientation) { default: case UIDeviceOrientationPortrait: buttonRotation = 0.0; imageOrientation = UIImageOrientationRight; interfaceOrientation = UIInterfaceOrientationPortrait; break; case UIDeviceOrientationPortraitUpsideDown: buttonRotation = M_PI; imageOrientation = UIImageOrientationLeft; interfaceOrientation = UIInterfaceOrientationPortraitUpsideDown; break; case UIDeviceOrientationLandscapeLeft: buttonRotation = M_PI_2; imageOrientation = UIImageOrientationUp; interfaceOrientation = UIInterfaceOrientationLandscapeLeft; break; case UIDeviceOrientationLandscapeRight: buttonRotation = -M_PI_2; imageOrientation = UIImageOrientationDown; interfaceOrientation = UIInterfaceOrientationLandscapeRight; break; } // Adjust button orientations [(EGEdgyView *)[self view] setButtonImageTransform:CGAffineTransformMakeRotation(buttonRotation) animated:YES]; // Adjust the (hidden) status bar orientation so that sheets and modal view controllers appear in the proper orientation // and so touch hystereses are more accurate [[UIApplication sharedApplication] setStatusBarOrientation:interfaceOrientation]; } } - (void)torchToggled:(id)sender { torchOn = !torchOn; [self updateConfiguration]; } - (void)captureImage:(id)sender { EGEdgyView *view = (EGEdgyView *)[self view]; // Prevent redundant button pressing and ensure we capture the visible image pauseForCapture = YES; // MUST COME FIRST [view setUserInteractionEnabled:NO]; #if TARGET_IPHONE_SIMULATOR UIImage *image = [UIImage imageNamed:@"Default"]; // test code #else // Get the current image and add rotation metadata, rotating the raw pixels if necessary UIImage *image = [[view imageView] image]; if (!image) { pauseForCapture = NO; [view setUserInteractionEnabled:YES]; return; } #endif image = [UIImage imageWithCGImage:[image CGImage] scale:1.0 orientation:imageOrientation]; IplImage *pixels = [image createIplImageWithNumberOfChannels:3]; #if TARGET_OS_EMBEDDED if ([currentDevice position] == AVCaptureDevicePositionFront) { cvFlip(pixels, NULL, (imageOrientation == UIImageOrientationUp || imageOrientation == UIImageOrientationDown) ? 0 : 1); // flip vertically } #endif image = [[UIImage alloc] initWithIplImage:pixels]; cvReleaseImage(&pixels); // Create the item to share NSString *shareFormatString = NSLocalizedString(@"Photo from Edgy Camera, free on the App Store", nil); NSString *title = [[NSString alloc] initWithFormat:shareFormatString, [[UIDevice currentDevice] model]]; SHKItem *item = [SHKItem image:image title:title]; // Get the ShareKit action sheet and display it. Use our subclass so we can know when it gets dismissed. EGSHKActionSheet *actionSheet = [EGSHKActionSheet actionSheetForItem:item]; [actionSheet setTitle:nil]; [actionSheet setEGDismissHandler:^{ pauseForCapture = NO; [view setUserInteractionEnabled:YES]; [view restartFadeTimer]; }]; [(EGEdgyView *)[self view] clearFadeTimer]; [actionSheet showFromRect:[[view captureButton] frame] inView:view animated:YES]; } - (void)thresholdChanged:(id)sender { cannyThreshold = [(UISlider *)sender value]; } - (void)cameraToggled:(id)sender { deviceIndex++; [self updateConfiguration]; } - (void)colorToggled:(id)sender { colorEdges = !colorEdges; } #if TARGET_OS_EMBEDDED // Called on the capture dispatch queue - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection { if (pauseForCapture) { return; } CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer); // Lock the image buffer and get information about the image's *Y plane* CVPixelBufferLockBaseAddress(imageBuffer, 0); void *baseAddress = fallBackToBGRA32Sampling ? CVPixelBufferGetBaseAddress(imageBuffer) : CVPixelBufferGetBaseAddressOfPlane(imageBuffer, 0); size_t bytesPerRow = fallBackToBGRA32Sampling ? CVPixelBufferGetBytesPerRow(imageBuffer) : CVPixelBufferGetBytesPerRowOfPlane(imageBuffer, 0); size_t width = fallBackToBGRA32Sampling ? CVPixelBufferGetWidth(imageBuffer) : CVPixelBufferGetWidthOfPlane(imageBuffer, 0); size_t height = fallBackToBGRA32Sampling ? CVPixelBufferGetHeight(imageBuffer) : CVPixelBufferGetHeightOfPlane(imageBuffer, 0); CvSize size = cvSize((int)width, (int)height); // Create an image header to hold the data. Vector copy the data since the image buffer has very slow random access performance. IplImage *grayscaleImage = cvCreateImageHeader(size, IPL_DEPTH_8U, fallBackToBGRA32Sampling ? 4 : 1); grayscaleImage->widthStep = (int)bytesPerRow; grayscaleImage->imageSize = (int)(bytesPerRow * height); cvCreateData(grayscaleImage); memcpy(grayscaleImage->imageData, baseAddress, height * bytesPerRow); CVPixelBufferUnlockBaseAddress(imageBuffer, 0); // If we fell back, we need to convert the image to grayscale if (fallBackToBGRA32Sampling) { IplImage *temp = cvCreateImage(size, IPL_DEPTH_8U, 1); cvCvtColor(grayscaleImage, temp, CV_BGRA2GRAY); cvReleaseImage(&grayscaleImage); grayscaleImage = temp; } // Get the Canny edge image IplImage *cannyEdgeImage = cvCreateImage(size, IPL_DEPTH_8U, 1); cvCanny(grayscaleImage, cannyEdgeImage, 40.0, cannyThreshold, 3 | CV_CANNY_L2_GRADIENT); cvReleaseImage(&grayscaleImage); // Find each unique contour CvContour *firstContour = NULL; CvMemStorage *storage = cvCreateMemStorage(); cvFindContours(cannyEdgeImage, storage, (CvSeq **)&firstContour, sizeof(CvContour), CV_RETR_LIST); // modifies images cvReleaseImage(&cannyEdgeImage); // Color each contour IplImage *colorEdgeImage = cvCreateImage(size, IPL_DEPTH_8U, 3); fastSetZero(colorEdgeImage); if (firstContour) { CvTreeNodeIterator iterator; cvInitTreeNodeIterator(&iterator, firstContour, INT_MAX); CvContour *contour; while ((contour = (CvContour*)cvNextTreeNode(&iterator)) != NULL) { CvScalar color = colorEdges ? randomRGBColor() : CV_RGB(255, 255, 255); cvDrawContours(colorEdgeImage, (CvSeq *)contour, color, color, 0); } } cvReleaseMemStorage(&storage); // Send the image data to the main thread for display. Block so we aren't drawing while processing. dispatch_sync(dispatch_get_main_queue(), ^{ if (!pauseForCapture) { UIImageView *imageView = [(EGEdgyView *)[self view] imageView]; UIImage *uiImage = [[UIImage alloc] initWithIplImage:colorEdgeImage]; [imageView setImage:uiImage]; } }); cvReleaseImage(&colorEdgeImage); #if PRINT_PERFORMANCE static CFAbsoluteTime lastUpdateTime = 0.0; CFAbsoluteTime currentTime = CACurrentMediaTime(); if (lastUpdateTime) { NSLog(@"Processing time: %.3f (fps %.1f) size(%u,%u)", currentTime - lastUpdateTime, 1.0 / (currentTime - lastUpdateTime), size.width, size.height); } lastUpdateTime = currentTime; #endif } #endif - (void)bannerViewDidLoadAd:(ADBannerView *)banner { [banner setHidden:NO]; [banner setAlpha:0.0]; [[self view] setNeedsLayout]; [UIView beginAnimations:nil context:NULL]; [banner setAlpha:1.0]; [UIView commitAnimations]; } - (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error { [banner setHidden:YES]; [[self view] setNeedsLayout]; } - (BOOL)bannerViewActionShouldBegin:(ADBannerView *)banner willLeaveApplication:(BOOL)willLeave { pauseForCapture = YES; return YES; } - (void)bannerViewActionDidFinish:(ADBannerView *)banner { pauseForCapture = NO; } @end
import csv import os import heapq import datetime import numpy as np import skopt.utils import torch import torch.nn as nn from torch.nn import Module import torch.optim as optim import torch.nn.functional as F from torch.utils.data import DataLoader, Dataset, TensorDataset import pickle from skopt import gp_minimize from skopt.space import Real, Integer from skopt.utils import use_named_args import matplotlib.pyplot as plt import skopt.plots from opt_NeuMF import to_named_params, load_results, save_results import warnings warnings.filterwarnings('ignore') def get_train_instances(train, num_negatives): """用户打过分的为正样本,没打过分的为负样本。采样存储部分负样本""" np.random.seed(123) user_input, item_input, labels = [], [], [] num_items = train.shape[1] for (u, i) in train.keys(): user_input.append(u) item_input.append(i) labels.append(1) for t in range(num_negatives): j = np.random.randint(num_items) while (u, j) in train: j = np.random.randint(num_items) user_input.append(u) item_input.append(j) labels.append(0) return user_input, item_input, labels class MyGRU(Module): """GRU模块""" def __init__(self, seq_length: int, input_size: int, hidden_size: int): super().__init__() self.seq_length: int = seq_length self.input_size: int = input_size self.hidden_size: int = hidden_size self.rnn = nn.GRUCell(self.input_size, self.hidden_size) def forward(self, X: torch.Tensor, h0=None): batch_size: int = X.shape[1] if h0 is None: prev_h = torch.zeros(batch_size, self.hidden_size, device=X.device) else: prev_h = torch.squeeze(h0, 0) output = torch.zeros(self.seq_length, batch_size, self.hidden_size, device=X.device) # 初始化output张量 for i in range(self.seq_length): prev_h = self.rnn(X[i], prev_h) output[i] = prev_h return output, torch.unsqueeze(prev_h, 0) class NeuralMFWithGRU(nn.Module): """NeuralMF with GRU""" def __init__(self, num_users, num_items, mf_dim, mlp_user_dim, mlp_item_dim, layers, dropout, hidden_size, num_layers=1): super(NeuralMFWithGRU, self).__init__() self.MF_Embedding_User = nn.Embedding(num_embeddings=num_users, embedding_dim=mf_dim) self.MF_Embedding_Item = nn.Embedding(num_embeddings=num_items, embedding_dim=mf_dim) self.MLP_Embedding_User = nn.Embedding(num_embeddings=num_users, embedding_dim=mlp_user_dim) self.MLP_Embedding_Item = nn.Embedding(num_embeddings=num_items, embedding_dim=mlp_item_dim) # # GRU组件: # self.gru = nn.GRU(input_size=mlp_user_dim+mlp_item_dim, hidden_size=hidden_size, num_layers=num_layers, batch_first=True) self.gru = MyGRU(1, mlp_user_dim+mlp_item_dim, hidden_size) # 输入形状需为(seq_length, input_size, hidden_size) self.mlp_layers = nn.ModuleList() for i in range(len(layers) - 1): self.mlp_layers.append(nn.Linear(layers[i], layers[i + 1])) self.mlp_layers.append(nn.ReLU()) self.mlp_layers.append(nn.Dropout(p=dropout)) self.linear2 = nn.Linear(2 * mf_dim, 1) self.sigmoid = nn.Sigmoid() def forward(self, inputs): inputs = inputs.long() MF_Embedding_User = self.MF_Embedding_User(inputs[:, 0]) # (100,8)(user_num,mf_dim) MF_Embedding_Item = self.MF_Embedding_Item(inputs[:, 1]) # (3706,8)(item_num,mf_dim) mf_vec = torch.mul(MF_Embedding_User, MF_Embedding_Item) # (100,8)(user_num,mf_dim) MLP_Embedding_User = self.MLP_Embedding_User(inputs[:, 0]) # (100,32)(user_num,mlp_user_dim) MLP_Embedding_Item = self.MLP_Embedding_Item(inputs[:, 1]) # (3706,32)(item_num,mlp_item_dim) x = torch.cat([MLP_Embedding_User, MLP_Embedding_Item], dim=-1) # (64,16)(batch_size,mlp_user_dim+mlp_item_dim) # print('x0', x.shape) # 升维 x = x.unsqueeze(1) # (batch_size,1,mlp_user_dim+mlp_item_dim) B, S, I = x.size() x = x.view(S, B, I) # print('x', x.shape) # gru_out, _ = self.gru(x) # (batch_size,seq_len,hidden_num) gru_out, _ = self.gru(x) # 输入形状需为(seq_length, batch_size, input_size) # print("gru0", gru_out.shape) # 降维 # gru_out = gru_out[:, -1, :] # (batch_size,hidden_num) gru_out = gru_out[-1, :, :] # (batch_size,hidden_num) # print('gru', gru_out.shape) mlp_vec = F.relu(gru_out) for layer in self.mlp_layers: # print(mlp_vec.shape) mlp_vec = layer(mlp_vec) # last_mlp_vec:(batch_size,layers[-1]:mf_dim) vector = torch.cat([mf_vec, mlp_vec], dim=-1) # vector:(user_num,2*mf_dim) linear = self.linear2(vector) # (100,1)(user_num,1) output = self.sigmoid(linear) # (100,1) return output def getHitRatio(ranklist, gtItem): """HitRation""" for item in ranklist: if item == gtItem: return 1 return 0 def getNDCG(ranklist, gtItem): """NDCG""" for i in range(len(ranklist)): item = ranklist[i] if item == gtItem: return np.log(2) / np.log(i + 2) return 0 def eval_one_rating(idx): """对testRatings中的一个用户样本进预测和评估""" rating = _testRatings[idx] items = _testNegatives[idx] u = rating[0] gtItem = rating[1] items.append(gtItem) map_item_score = {} users = np.full(len(items), u, dtype='int32') test_data = torch.tensor(np.vstack([users, np.array(items)]).T).to(device) predictions = _model(test_data) for i in range(len(items)): item = items[i] map_item_score[item] = predictions[i].data.cpu().numpy()[0] items.pop() ranklist = heapq.nlargest(_K, map_item_score, key=lambda k: map_item_score[k]) hr = getHitRatio(ranklist, gtItem) ndcg = getNDCG(ranklist, gtItem) return hr, ndcg def evaluate_model(model, testRatings, testNegatives, K): """整体上评估模型性能""" global _model global _testRatings global _testNegatives global _K _model = model _testNegatives = testNegatives _testRatings = testRatings _K = K hits, ndcgs = [], [] for idx in range(len(_testRatings)): (hr, ndcg) = eval_one_rating(idx) hits.append(hr) ndcgs.append(ndcg) return np.array(hits).mean(), np.array(ndcgs).mean() # def train_and_eval(epochs, loss_func, optimizer, model, dl_train, topK, testRatings, testNegatives): # """考虑贝叶斯优化所需的返回值:当前参数组合下最佳ndcg""" # total_ndcgs = [] # for epoch in range(epochs): # model.train() # for step, (features, labels) in enumerate(dl_train, 1): # features, labels = features.cuda(), labels.cuda() # optimizer.zero_grad() # predictions = model(features) # predictions = predictions.squeeze(1) # loss = loss_func(predictions, labels) # loss.backward() # optimizer.step() # model.eval() # hits, ndcgs = evaluate_model(model, testRatings, testNegatives, topK) # total_ndcgs.append(ndcgs) # max_ndcg = np.max(total_ndcgs) # return max_ndcg # # # if __name__ == "__main__": # # 基本配置 # batch_size = 128 # np.random.seed(123) # file_path = './result/resultsGRU.pkl' # device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # # 参数定义 # epochs = 12 # num_layers = 1 # num_negatives = 5 # # 数据导入 # train = np.load('ProcessedData/train.npy', allow_pickle=True).tolist() # testRatings = np.load('ProcessedData/testRatings.npy').tolist() # testNegatives = np.load('ProcessedData/testNegatives.npy').tolist() # # 切数据 # # train = train[:500] # # testRatings = testRatings[:500] # # testNegatives = testNegatives[:500] # num_users, num_items = train.shape # # 搜索空间(固定:batch_size=128) # space = [ # Integer(33, 50, name='topK'), # Integer(8, 40, name='mf_dim'), # Integer(1, 45, name='mlp_user_dim'), # Integer(1, 40, name='mlp_item_dim'), # # Integer(1, 5, name='num_negatives'), # Real(1e-4, 1e-1, prior='log-uniform', name='lr'), # # Integer(10, 20, name='epochs'), # Integer(40, 128, name='hidden_size'), # Real(0, 0.4, name='dropout'), # # Integer(1, 3, name='num_layers'), # Integer(4, 30, name='layers_1'), # Integer(4, 50, name='layers_2'), # Integer(4, 55, name='layers_3'), # Integer(220, 320, name='layers_4'), # Integer(4, 200, name='layers_5'), # ] # # 优化配置 # HPO_PARAMS = { # 'n_calls': 18, # 总迭代次数 # 'n_random_starts': 1, # 'base_estimator': 'ET', # 指定用于拟合目标函数的基本估计器 # 'acq_func': 'gp_hedge', # 采集函数,概率选择EI、PI和LCB中的一个 # 'random_state': 15 # } # # 目标函数 # @use_named_args(space) # def objective(topK, mf_dim, mlp_user_dim, mlp_item_dim, lr, hidden_size, dropout, layers_1, layers_2, layers_3, layers_4, layers_5): # """返回负的最大 NDCG 值,因为优化器的目标是最小化指标""" # # DataLoader # user_input, item_input, labels = get_train_instances(train, num_negatives) # train_x = np.vstack([user_input, item_input]).T # labels = np.array(labels) # train_dataset = TensorDataset(torch.tensor(train_x), torch.tensor(labels).float()) # dl_train = DataLoader(train_dataset, batch_size=batch_size, shuffle=True) # # 自定义层结构 # layers = [hidden_size, layers_1, layers_2, layers_3, layers_4, layers_5, mf_dim] # # 显示当前评估的参数组合 # print(f"Evaluating: topK={topK}, mf_dim={mf_dim}, mlp_user_dim={mlp_user_dim}, mlp_item_dim={mlp_item_dim}, num_negatives={num_negatives}, lr={lr}, " # f"epochs={epochs}, hidden_size={hidden_size}, dropout={dropout}, num_layers={num_layers}, layers={layers}") # # 创建模型 # model = NeuralMFWithGRU(num_users, num_items, mf_dim, mlp_user_dim, mlp_item_dim, layers, dropout, hidden_size, num_layers) # model.to(device) # # 模型训练与测试 # loss_func = nn.BCELoss() # optimizer = torch.optim.Adam(params=model.parameters(), lr=lr) # max_ndcg = train_and_eval(epochs, loss_func, optimizer, model, dl_train, topK, testRatings, testNegatives) # return -max_ndcg # # 调参测试 # old_results = load_results(file_path) # if old_results is not None: # print("继续测试") # print("old_results.x_iters: ", old_results.x_iters) # print("old_results.func_vals: ", old_results.func_vals) # results = gp_minimize(objective, space, # x0=old_results.x_iters, # y0=old_results.func_vals, # **HPO_PARAMS) # else: # print("从零开始测试") # results = gp_minimize(objective, space, **HPO_PARAMS) # # 保存结果 # save_results(results, file_path) # print("results.x_iters:", results.x_iters) # print("results.func_vals:", results.func_vals) # # 过程显示 # skopt.plots.plot_objective(results) # plt.show() # # 打印最佳参数组合 # best_params = to_named_params(results, space) # print("Best parameters:", best_params) # 验证实验主函数 def train_and_eval(epochs, loss_func, optimizer, model, dl_train, topK, testRatings, testNegatives): test_csv_path = './result/test_results.csv' test_csv_file = open(test_csv_path, 'w', newline='') test_csv_writer = csv.writer(test_csv_file) test_csv_writer.writerow(['Epoch', 'LOSS', 'NDCG', 'HR']) for epoch in range(epochs): model.train() loss_sum = 0.0 for step, (features, labels) in enumerate(dl_train, 1): features, labels = features.cuda(), labels.cuda() optimizer.zero_grad() predictions = model(features) predictions = predictions.squeeze(1) loss = loss_func(predictions, labels) loss.backward() optimizer.step() loss_sum += loss.item() model.eval() hr, ndcg = evaluate_model(model, testRatings, testNegatives, topK) test_csv_writer.writerow([epoch, loss_sum/step, ndcg, hr]) info = (epoch, loss_sum/step, hr, ndcg) print(("\nEPOCH = %d, loss = %.3f, hr = %.3f, ndcg = %.3f") % info) test_csv_file.close() if __name__ == "__main__": # 基本配置 batch_size = 128 np.random.seed(123) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # 参数设置 topK = 40 mf_dim = 38 mlp_user_dim = 45 mlp_item_dim = 3 num_negatives = 5 lr = 0.00439 epochs = 15 hidden_size = 62 dropout = 0.3782 num_layers = 1 layers = [hidden_size, 11, 33, 55, 228, 177, mf_dim] # 数据导入 train = np.load('ProcessedData/train.npy', allow_pickle=True).tolist() testRatings = np.load('ProcessedData/testRatings.npy').tolist() testNegatives = np.load('ProcessedData/testNegatives.npy').tolist() # 切数据 # train = train[:100] # testRatings = testRatings[:100] # testNegatives = testNegatives[:100] num_users, num_items = train.shape # DataLoader user_input, item_input, labels = get_train_instances(train, num_negatives) train_x = np.vstack([user_input, item_input]).T labels = np.array(labels) train_dataset = TensorDataset(torch.tensor(train_x), torch.tensor(labels).float()) dl_train = DataLoader(train_dataset, batch_size=batch_size, shuffle=True) # 模型实例化 model = NeuralMFWithGRU(num_users, num_items, mf_dim, mlp_user_dim, mlp_item_dim, layers, dropout, hidden_size, num_layers) model.to(device) # print(model) # 模型训练与测试 loss_func = nn.BCELoss() optimizer = torch.optim.Adam(params=model.parameters(), lr=lr) train_and_eval(epochs, loss_func, optimizer, model, dl_train, topK, testRatings, testNegatives)
/** * ****************** * BASIC TYPE RENAMES * ****************** */ /** * This is only used for main levels, not sublevels, and is used for the following: * - Level name offset * - Level entrance offset */ export type MainLevelDataOffset = number; /** * This applies to both main and sublevels, and is used for the following: * - Offset to find level headers * - Offset to find level static objects (note: 10 bytes after headers) * - Offset to find level exits (note: at end of level statics list) */ export type LevelDataOffset = number; export type TilePixelData = number[]; export type ObjectStorageType = "4byte" | "s4byte" | "5byte"; export type LevelObjectType = "static" | "sprite"; export function getObjectTypePretty(st: ObjectStorageType, lot: LevelObjectType): string { if (lot === "sprite") { return "Sprite"; } else { if (st === "s4byte") { return "Extended"; } else if (st === "4byte") { return "Static 4byte"; } else { return "Static 5byte"; } } } /** * A list of 16 colors, bg and fg each have 16 of these */ export type Palette = string[]; /** * ****************** * ENUMS AND ORDERING * ****************** */ /** * How the camera scrolls * This is used when loading a LevelEntrance * @see LevelEntrance */ export enum ScrollType { FREE_SCROLLING = 0, NO_SCROLLING = 3 } /** * Some objects automatically take priority over others. Just add them together * so that the superobjects also order themselves */ export const ORDER_PRIORITY_STATIC = 10000; /** * Sprites always go over any static object, no matter what */ export const ORDER_PRIORITY_SPRITE = 100000; /** * Ones above 0xA are theorized to be Bandit Minigames, but * seem to fail when using pipes to go */ export enum LevelEntryAnimation { FALL = 0x0, ON_SKIS = 0x1, RIGHT_FROM_PIPE = 0x2, LEFT_FROM_PIPE = 0x3, DOWN_FROM_PIPE = 0x4, UP_FROM_PIPE = 0x5, GO_RIGHT = 0x6, GO_LEFT = 0x7, GO_DOWN = 0x8, JUMP_HIGH = 0x9, SHOT_TO_MOON = 0xA, _TRANSFER_TO_MAP = 0xB, _CRASH1 = 0xC, _CRASH2 = 0xD } /** * ********************** * ROM-RELATED INTERFACES * ********************** */ /** * The fundamental object containing all info about a level or sublevel */ export interface Level { /** * LevelDataOffset */ levelId: LevelDataOffset; objects: LevelObject[]; levelTitle: string; /** * Note: This only applies to main levels. Sublevels do not have entrances, * their entrance is controlled by LevelExits */ levelEntrance?: LevelEntrance; availableSpriteTiles: TilePixelData[]; // Access via index headers: LevelHeaders; world: number; exits: LevelExit[]; palettes?: Palette[]; } /** * Represents a single level exit, of which there can be many in levels * How it works: The screenExitValue applies a section of the level as * a Screen Exit "page", in which every passage in the section leads to the * level ID in question. * * Note that this means you can only have 1 entrance in each section * @todo Make check to see if multiple entrances in one screen page section */ export interface LevelExit { /** * Example: 0x75 -> page y = 7, x = 5 * You can't really convert this to coords since one page has * 0xf*0xf possible coordinates in it. Only reverse * @see `getScreenPageFromCoords` method in RomService to calculate */ screenExitValue: number; /** * LevelEntrance ID, NOT LevelName ID */ destinationLevelId: number; /** * X position of where you show up in the next level? */ destinationXpos: number; /** * Y position of where you show up in the next level? */ destinationYpos: number; /** * The animation that plays when entering the second level * * This might also be used for bandit minigames */ entryAnimation: LevelEntryAnimation; /** * Unknown */ unknown1: number; /** * Unknown, seems to affect the camera */ unknown2: number; } export interface LevelObject { objectType: LevelObjectType; objectStorage: ObjectStorageType; objectId: number; dimX?: number; dimY?: number; dimZ?: number; xPos: number; yPos: number; originalOffset16?: string; uuid: string; zIndex: number; } /** * Note: These only apply to main levels. Sub level entries are controlled with * LevelExits */ export interface LevelEntrance { /** * This points to the headers, statics, and exits */ levelEntranceId: LevelDataOffset; startX: number; startY: number; iconToUnlockId: number; unknown5: string; scrollType: ScrollType; } /** * Will contain more and more as things become supported * Hint block text? */ export interface RomData { levels: Level[]; } export const LEVEL_HEADERS_KEY_LENGTH = 15; // Order is VERY IMPORTANT here export interface LevelHeaders { backgroundColor: number; // See if this is a special object and not an index /** * The tileset available for the level. * @see TILESET_NAME for descriptions */ tileset: number; layer1palette: number; layer2image: number; layer2palette: number; layer3type: number; layer3palette: number; spriteSet: number; spritePalette: number; layerOrderingProperty: number; index10: number; index11: number; foregroundPosition: number; music: number; middleRingNumber: number; }
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../../../../core/constant/color.dart'; import '../../../../core/constant/linkapi.dart'; import '../../../../data/model/cartitemmodel.dart'; class ItemsCard extends StatelessWidget { final CartItemModel itemsModel; const ItemsCard({Key? key, required this.itemsModel}) : super(key: key); @override Widget build(BuildContext context) { return Container( height: 135, decoration: BoxDecoration( borderRadius: BorderRadius.circular(15), color: Colors.white, ), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 15.0), child: Row( children: [ Container( width: 150, height: 120, decoration: BoxDecoration( borderRadius: BorderRadius.circular(15), color: ColorApp.primaryColor, image: DecorationImage( image: NetworkImage( '${AppLinks.itemsImage}/${itemsModel.itemImage}'), fit: BoxFit.cover)), ), const SizedBox( width: 20, ), Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( itemsModel.itemName ?? "", style: const TextStyle( color: Colors.black, fontSize: 18, fontWeight: FontWeight.bold, ), ), Text( "${itemsModel.price} JD", style: const TextStyle( color: ColorApp.primaryColor, fontSize: 20, fontWeight: FontWeight.w700, ), ) ], ), SizedBox( width: Get.width / 12, ), ], ), ), ); } }
<template> <collapse class="p-5 w-full border-b" v-model="isCollapseOpen"> <template #title> <h3 id="v-step-2" class="font-semibold text-lg"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="h-5 w-5 inline -ml-1 mr-2 -mt-1 transition-colors" :class="{'text-blue-600':isCollapseOpen, 'text-gray-500':!isCollapseOpen}" > <path stroke-linecap="round" stroke-linejoin="round" d="M2.25 15.75l5.159-5.159a2.25 2.25 0 013.182 0l5.159 5.159m-1.5-1.5l1.409-1.409a2.25 2.25 0 013.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 001.5-1.5V6a1.5 1.5 0 00-1.5-1.5H3.75A1.5 1.5 0 002.25 6v12a1.5 1.5 0 001.5 1.5zm10.5-11.25h.008v.008h-.008V8.25zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0z" /> </svg> Link Settings - SEO <pro-tag /> </h3> </template> <p class="mt-4 text-gray-500 text-sm"> Customize the image and text that appear when you share your form on other sites (Open Graph). </p> <text-input v-model="form.seo_meta.page_title" name="page_title" class="mt-4" label="Page Title" help="Under or approximately 60 characters" /> <text-area-input v-model="form.seo_meta.page_description" name="page_description" class="mt-4" label="Page Description" help="Between 150 and 160 characters" /> <image-input v-model="form.seo_meta.page_thumbnail" name="page_thumbnail" class="mt-4" label="Page Thumbnail Image" help="Also know as og:image - 1200 X 630" /> </collapse> </template> <script> import Collapse from '../../../../common/Collapse.vue' import ProTag from '../../../../common/ProTag.vue' export default { components: { Collapse, ProTag }, props: {}, data () { return { isCollapseOpen: false } }, computed: { form: { get () { return this.$store.state['open/working_form'].content }, /* We add a setter */ set (value) { this.$store.commit('open/working_form/set', value) } } }, watch: {}, mounted () { ['page_title', 'page_description', 'page_thumbnail'].forEach((keyname) => { if (this.form.seo_meta[keyname] === undefined) { this.form.seo_meta[keyname] = null } }) }, methods: {} } </script>
import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators, ValidationErrors } from '@angular/forms'; @Component({ selector: 'app-project', templateUrl: './project.component.html', styleUrls: ['./project.component.css'] }) export class ProjectComponent implements OnInit { projectForm: FormGroup; projectName: FormControl; email: FormControl; projectStatus: FormControl; statusList: string[]; projectList: {projectName: string; email: string; projectStatus: string;}[]; constructor() { } ngOnInit(): void { this.statusList = ['Stable', 'Critical', 'Finished']; this.projectList = []; this.onInitProjectForm(); } onInitProjectForm() { this.projectName = new FormControl(null, Validators.required, this.invalidProjectAsync); this.email = new FormControl(null, [Validators.required, Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$")]); this.projectStatus = new FormControl(null, Validators.required); this.projectForm = new FormGroup({ projectName: this.projectName, email: this.email, projectStatus: this.projectStatus }); } onSubmit() { const project = { projectName: this.projectForm.value.projectName, email: this.projectForm.value.email, projectStatus: this.projectForm.value.projectStatus }; this.projectList.push(project); this.projectForm.reset(); } invalidProject(control: FormControl): ValidationErrors | null { if (control.value === 'Test' || control.value === 'test') { return {invalidProject: true}; } return null; } invalidProjectAsync(control: FormControl): Promise<any> { const promise = new Promise((resolve, reject) => { setTimeout(() => { if (control.value === 'Test' || control.value === 'test') { resolve({invalidProject: true}); } else { resolve(null); } }, 1500); }); return promise; } }
// https://codeforces.com/gym/100962 - Frank Sinatra // Tag: Mo on tree #include<bits/stdc++.h> typedef long long ll; const ll mod = 1e9 + 7; #define ld long double using namespace std; #ifdef DEBUG #include "debug.cpp" #else #define dbg(...) #define destructure(a) #a #endif template <typename T> struct FenwickTree { private: vector<T> bit; // binary indexed tree T n; public: FenwickTree(){} void build(T n) { this->n = n; bit.assign(n, 0); } void build(vector<T> a) { build(a.size()); for (int i = 0; i < (int) a.size(); i++) add(i, a[i]); } FenwickTree(vector<T> a) { build(a); } T sum(T r) { if (r==-1) return 0; T ret = 0; for (; r >= 0; r = (r & (r + 1)) - 1) ret += bit[r]; return ret; } T sum(T l, T r) { assert(0 <= l && l <= r && r < n); return sum(r) - sum(l-1); } void add(T idx, T delta) { assert(0 <= idx && idx < n); for (; idx < n; idx = idx | (idx + 1)) bit[idx] += delta; } void set(T idx, T val) { T diff = val - sum(idx, idx); add(idx, diff); } vector<T> original(){ // Return original value of input vector vector<T> a; for (T i=0;i<this->n;i++) a.push_back(sum(i,i)); return a; } }; template<typename T> vector<T> depth_on_tree(vector<vector<T>> tree) { vector<T> depth((ll) tree.size(), 0); std::function<void(T, T)> dfs = [&](T u, T p){ for (auto v: tree.at(u)) { if (v!= p) { depth.at(v) = depth.at(u) + 1; dfs(v, u); } } }; dfs(0, 0); return depth; } const ll blockSize = 500; // 300, 700 struct Query { ll l, r, index; friend bool operator<(Query a, Query b) { // những cái thuộc cùng 1 block sẽ đứng cạnh nhau, những cái cùng block thì r sẽ xếp từ bé tới lớn if (a.l/blockSize == b.l/blockSize) return a.r < b.r; return a.l/blockSize < b.l/blockSize; } friend std::ostream& operator<<(std::ostream& os, const Query &s) { return os << destructure(s);} }; struct Ans { ll index, val; friend bool operator<(Ans a, Ans b) { return a.index < b.index; } friend std::ostream& operator<<(std::ostream& os, const Ans &s) { return os << destructure(s);} }; struct MoOnTree { private: template<typename LL>class LCA{struct Euler{LL vertex, height, index;};template<typename T>class LCASegmentTree{private:ll n;vector<T>dat;public:T merge(T a,T b){if(a.height>b.height)return b;return a;}LCASegmentTree(vector<T>v){int _n=v.size();n=1;while(n<_n)n*=2;dat.resize(2*n-1);for(int i=0;i<_n;i++)dat[n+i-1]=v[i];for(int i=n-2;i>=0;i--)dat[i]=merge(dat[i*2+1],dat[i*2+2]);} LCASegmentTree(int _n){n=1;while(n<_n)n*=2;dat.resize(2*n-1); } void set_val(int i,T x){i+=n-1;dat[i]=x;while(i>0){i=(i-1)/2;dat[i]=merge(dat[i*2+1],dat[i*2+2]);}}T query(int l,int r){r++;T left=T{INT_MAX,INT_MAX,INT_MAX},right=T{INT_MAX,INT_MAX,INT_MAX};l+=n-1;r+=n-1;while(l<r){if((l&1)==0)left=merge(left,dat[l]);if((r&1)==0)right=merge(dat[r-1],right);l=l/2;r=(r-1)/2;}return merge(left,right);}};public:int n;vector<vector<LL>> graph;vector<bool> visited;vector<Euler> eulertour, first;LCASegmentTree<Euler> *seg;LCA() {}LCA(vector<vector<LL>> graph, LL root = 0){build(graph, root);}void build(vector<vector<LL>> graph, LL root = 0) {this->graph = graph;n = graph.size();visited.resize(n);first.resize(n);makeEuler(root);}void makeEuler(LL root){std::fill(visited.begin(), visited.end(), false);int height =0;std::function<void(int)> explore = [&](int u){visited[u] = true;height++;eulertour.push_back(Euler{u, height, (int) eulertour.size()});for (auto v: this->graph[u]){if (!visited[v]) {explore(v);height--;eulertour.push_back(Euler{u, height, (int) eulertour.size()});}}};explore(root);std::fill(visited.begin(), visited.end(), false);for (auto e: eulertour){if (!visited[e.vertex]){visited[e.vertex] = true;first[e.vertex] = e;}}this->seg = new LCASegmentTree<Euler>(eulertour);}LL lca(LL u, LL v){LL uidx = first[u].index;LL vidx = first[v].index;if (uidx > vidx) swap(uidx, vidx);Euler a = seg->query(uidx, vidx);return a.vertex;}vector<LL> height(){vector<LL> h(this->n, 0);for (auto e: eulertour) h[e.vertex] = e.height;return h;}LL lca(LL r, LL u, LL v){LL ru = lca(r, u);LL rv = lca(r, v);LL uv = lca(u, v);if (ru == rv) return uv;if (ru == uv) return rv;return ru;}}; std::vector<ll> first, second, eulertour; vector<ll> makeEulerTour(vector<vector<ll>> adj) { vector<ll> eulertour; first.resize(n); second.resize(n); // first[v] - thời điểm duyệt v, second[v] - thời điểm ra khỏi v ll clock = 0; std::function<void(ll, ll)> dfs = [&](ll u, ll p){ eulertour.push_back(u); first[u] = clock++; for (auto v: adj[u]) { if (v != p) dfs(v, u); } second[u] = clock++; eulertour.push_back(u); }; dfs(0, 0); return eulertour; } // Chuyển query trên node sang query trên euler tour vector<Query> fromEdgeToEuler(vector<Query> queries) { vector<Query> res; for (auto q: queries) { ll u = q.l, v= q.r, idx = q.index; if (first[u] > first[v]) swap(u, v); if (lca.lca(u, v) == u) { // first(u) -> first(v) (má trái) res.push_back(Query{first[u], first[v], idx}); } else { // second(u) -> first(v) res.push_back({second[u], first[v], idx}); } } return res; } public: ll n; vector<ll> weight; vector<Query> queries; // l, r, index LCA<ll> lca; vector<bool> vis; // đánh dấu số lần đỉnh đó đã đi qua vector<ll> data; // lưu trạng thái hiện tại - lưu tần số của từng số có trong range [left, right] hiện tại vector<Ans> ans; // index, val ll cur_result = 0; // giá trị hiện tại, đối với những bài giá trị tuyến tính khi add, remove thì dùng, ko thì tính trực tiếp từ mảng data ll bound; FenwickTree<ll> fw; MoOnTree(vector<vector<ll>> adj, vector<ll> weight) { this->n = (ll) adj.size(); this->weight = weight; lca.build(adj); eulertour = makeEulerTour(adj); vis.resize(n, false); bound = calBound(); fw.build(bound); data.resize(bound, 0); } ll calBound() { vector<ll> w = this->weight; sort(w.begin(), w.end()); dbg(w); ll bound = 0; for (int i=0;i<w.size();i++) { if (bound == w[i]) continue; bound++; if (bound != w[i]) break; } // Xóa đi các phần tử lớn hơn bound for (int i=0;i<this->weight.size();i++) { if (this->weight[i] > bound) this->weight[i] = -1; } return bound; } void add(ll index) { ll edge = eulertour[index]; ll w = weight[edge]; if (w != -1) { // -1 bỏ qua vì lớn hơn bound data[w]++; fw.set(w, 1); } } void remove(ll index) { ll edge = eulertour[index]; ll w = weight[edge]; if (w != -1) { data[w]--; if (data[w] == 0) fw.set(w, 0); } } void resolve(ll index) { ll edge = eulertour[index]; vis[edge] = !vis[edge]; // vis 1 lần thì nó nằm trên đoạn, 2 lần thì nó nằm ngoài đoạn if (!vis[edge]) remove(index); else add(index); } ll getResult() { ll left=0, right= this->bound-1; while (left != right) { ll mid = (left+right)/2; if (fw.sum(mid) != mid+1) right = mid; else left = mid + 1; } if (fw.sum(left) == left +1) return left+1; return left; } void solve(vector<Query> qrs) { queries = fromEdgeToEuler(qrs); sort(queries.begin(), queries.end()); ll cur_l = 0, cur_r = -1; for (auto query: queries) { while (cur_l > query.l) resolve(--cur_l); while (cur_r < query.r) resolve(++cur_r); while (cur_l < query.l) resolve(cur_l++); while (cur_r > query.r) resolve(cur_r--); // Xét tới lca.lca(u, v) ll p = lca.lca(eulertour[query.l], eulertour[query.r]); if (vis[p]) { remove(first[p]); ans.push_back({query.index, getResult()}); add(first[p]); } else { ans.push_back({query.index, getResult()}); } } sort(ans.begin(), ans.end()); for (auto v: ans) cout << v.val <<'\n'; } }; /* MoOnTree mo(graph, weight_on_node); mo.solve(vector<Query> queries); Các hàm cần thay đổi để fit với từng bài: resolve(), add(), remove() và đoạn xét lca(u, v) */ int main(){ ios::sync_with_stdio(0); cin.tie(0); #ifdef DEBUG freopen("inp.txt", "r", stdin); freopen("out.txt", "w", stdout); #endif ll n, q; cin >> n >> q; vector<vector<ll>> adj(n); vector<vector<pair<ll,ll>>> adj_w(n); for (ll i=0;i<n-1;i++) { ll u, v, w; cin >> u >> v >> w; u--; v--; adj[u].push_back(v); adj[v].push_back(u); adj_w[u].push_back({v, w}); adj_w[v].push_back({u, w}); } // chuyển trọng số từ cạnh xuống node bên dưới vector<ll> depth = depth_on_tree<ll>(adj); vector<ll> weight(n, LLONG_MAX); for (ll i=0;i<n;i++) { for (auto uv: adj_w[i]) { if (depth[i] > depth[uv.first]) { weight[i] = uv.second; } else weight[uv.first] = uv.second; } } /* Dựng Mo's on tree - tìm ra số nhỏ nhất bị rỗng trong đó đối với phần còn lại thì dùng binary search để tìm ra, binary search với fenwicktree */ vector<Query> queries; for (ll i=0;i<q;i++) { ll l, r; cin >> l >> r; queries.push_back({--l, --r, i}); } MoOnTree mo(adj, weight); mo.solve(queries); cerr << "Time : " << (double)clock() / (double)CLOCKS_PER_SEC << "s\n"; } /* Bài toán có 2 yêu cầu: * Tìm số nhỏ nhất không tồn tại trong range * Query trên tree Query trên tree sẽ được giải quyết khi dùng MoOnTree Phần quan tâm lúc này là tìm số nhỏ nhất không xuất hiện trong mảng Giả sử mảng 0, 1, 1, 2, 5, 4 có số nhỏ nhất không xuất hiện là 3 Observation 1: số cần tìm luôn nhỏ hơn hoặc bằng 3 cho dù hiện tại có số nào đi chăng nữa -> có 4,5 hay không có 4,5 đều không ảnh hưởng tới kết quả -> tìm ra bound = 3 -> mọi số lớn hơn 3 biến hết thành -1 và trong quá trình duyệt, mọi số -1 đều không cần quan tâm. Observation 2: độ dài vector lớn nhất là 10^5, giá trị tới 10^9 nhưng bound sẽ luôn <=10^5. Do các phần tử lớn hơn bound đều bị xóa bỏ. Khi này bài toán đưa về dạng: cho dãy a có 10^5 phần tử và giá trị các phần tử từ 0->10^5 Dùng fenwicktree kết hợp với binary search. fenwicktree check xem giá trị x có xuất hiện trong mảng hay không. a = [1, 1, 1, 0, 1, 1] 1 là có, 0 là không, index chính là giá trị. data trong Mo sẽ duy trì tần số xuất hiện của weight đó. Khi data[w] = 0 thì fw.set(w, 0) còn không thì fw.set(w, 1) Dùng binary search sẽ tìm ra được vị trí số 0 đầu tiên xuất hiện đó chính là giá trị cần tìm. Bài này dùng technique giống như HLD, đó là đẩy weight từ cạnh xuống đỉnh bên dưới. Khi đẩy cạnh xuống đỉnh bên dưới xét 2 type query (má trái, má phải). Trong video tự quay mình cũng có đề cập. Má trái sẽ là first->first. Má phải là second ->first. Bình thường má phải cần được xét riêng lca. Nhưng tại đây má trái first->first thì đỉnh lca đã được tính nhưng không nằm trên đoạn nên ở đoạn // Xét tới lca.lca(u, v) đã remove rồi lấy giá trị rồi add lại */
package upgrade_test import ( "context" "fmt" "regexp" "time" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/utils/strings/slices" "github.com/openshift-kni/eco-goinfra/pkg/clusteroperator" "github.com/openshift-kni/eco-goinfra/pkg/clusterversion" "github.com/openshift-kni/eco-goinfra/pkg/configmap" "github.com/openshift-kni/eco-goinfra/pkg/deployment" "github.com/openshift-kni/eco-goinfra/pkg/lca" "github.com/openshift-kni/eco-goinfra/pkg/namespace" "github.com/openshift-kni/eco-goinfra/pkg/nodes" "github.com/openshift-kni/eco-goinfra/pkg/olm" "github.com/openshift-kni/eco-goinfra/pkg/pod" "github.com/openshift-kni/eco-goinfra/pkg/proxy" "github.com/openshift-kni/eco-goinfra/pkg/reportxml" "github.com/openshift-kni/eco-goinfra/pkg/route" "github.com/openshift-kni/eco-goinfra/pkg/service" "github.com/openshift-kni/eco-gotests/tests/internal/cluster" "github.com/openshift-kni/eco-gotests/tests/lca/imagebasedupgrade/internal/nodestate" "github.com/openshift-kni/eco-gotests/tests/lca/imagebasedupgrade/internal/safeapirequest" "github.com/openshift-kni/eco-gotests/tests/lca/imagebasedupgrade/mgmt/internal/brutil" . "github.com/openshift-kni/eco-gotests/tests/lca/imagebasedupgrade/mgmt/internal/mgmtinittools" "github.com/openshift-kni/eco-gotests/tests/lca/imagebasedupgrade/mgmt/internal/mgmtparams" "github.com/openshift-kni/eco-gotests/tests/lca/imagebasedupgrade/mgmt/upgrade/internal/tsparams" "github.com/openshift-kni/eco-gotests/tests/lca/internal/url" lcav1 "github.com/openshift-kni/lifecycle-agent/api/imagebasedupgrade/v1" oplmV1alpha1 "github.com/operator-framework/api/pkg/operators/v1alpha1" k8sScheme "k8s.io/client-go/kubernetes/scheme" ) const ( oadpContentConfigmap = "oadp-cm" extraManifestNamespace = "extranamespace" extraManifestConfigmap = "extra-configmap" extraManifestNamespaceConfigmapName = "extra-manifests-cm0" extraManifesConfigmapConfigmapName = "extra-manifests-cm1" ) var ( ibu *lca.ImageBasedUpgradeBuilder err error ibuWorkloadNamespace *namespace.Builder ibuWorkloadRoute *route.Builder ) var _ = Describe( "Performing image based upgrade", Ordered, Label(tsparams.LabelEndToEndUpgrade), func() { var ( originalTargetProxy *proxy.Builder ) BeforeAll(func() { By("Get target cluster proxy configuration") originalTargetProxy, err = proxy.Pull(APIClient) Expect(err).NotTo(HaveOccurred(), "error pulling target cluster proxy") By("Pull the imagebasedupgrade from the cluster") ibu, err = lca.PullImageBasedUpgrade(APIClient) Expect(err).NotTo(HaveOccurred(), "error pulling ibu resource from cluster") By("Ensure that imagebasedupgrade values are empty") ibu.Definition.Spec.ExtraManifests = []lcav1.ConfigMapRef{} ibu.Definition.Spec.OADPContent = []lcav1.ConfigMapRef{} ibu, err := ibu.Update() Expect(err).NotTo(HaveOccurred(), "error updating ibu resource with empty values") if MGMTConfig.ExtraManifests { By("Include user-defined catalogsources in IBU extraManifests") updateIBUWithCustomCatalogSources(ibu) By("Create namespace for extramanifests") extraNamespace := namespace.NewBuilder(APIClient, extraManifestNamespace) extraNamespace.Definition.Annotations = make(map[string]string) extraNamespace.Definition.Annotations["lca.openshift.io/apply-wave"] = "1" By("Create configmap for extra manifests namespace") extraNamespaceString, err := brutil.NewBackRestoreObject( extraNamespace.Definition, k8sScheme.Scheme, v1.SchemeGroupVersion).String() Expect(err).NotTo(HaveOccurred(), "error creating configmap data for extramanifest namespace") extraManifestsNamespaceConfigmap, err := configmap.NewBuilder( APIClient, extraManifestNamespaceConfigmapName, mgmtparams.LCANamespace).WithData(map[string]string{ "namespace.yaml": extraNamespaceString, }).Create() Expect(err).NotTo(HaveOccurred(), "error creating configmap for extra manifests namespace") By("Create configmap for extramanifests") extraConfigmap := configmap.NewBuilder( APIClient, extraManifestConfigmap, extraManifestNamespace).WithData(map[string]string{ "hello": "world", }) extraConfigmap.Definition.Annotations = make(map[string]string) extraConfigmap.Definition.Annotations["lca.openshift.io/apply-wave"] = "2" By("Create configmap for extramanifests configmap") extraConfigmapString, err := brutil.NewBackRestoreObject( extraConfigmap.Definition, k8sScheme.Scheme, v1.SchemeGroupVersion).String() Expect(err).NotTo(HaveOccurred(), "error creating configmap data for extramanifest configmap") extraManifestsConfigmapConfigmap, err := configmap.NewBuilder( APIClient, extraManifesConfigmapConfigmapName, mgmtparams.LCANamespace).WithData(map[string]string{ "configmap.yaml": extraConfigmapString, }).Create() Expect(err).NotTo(HaveOccurred(), "error creating configmap for extra manifests configmap") By("Update IBU with extra manifests") _, err = ibu.WithExtraManifests( extraManifestsNamespaceConfigmap.Object.Name, extraManifestsNamespaceConfigmap.Object.Namespace). WithExtraManifests( extraManifestsConfigmapConfigmap.Object.Name, extraManifestsConfigmapConfigmap.Object.Namespace).Update() Expect(err).NotTo(HaveOccurred(), "error updating image based upgrade with extra manifests") } By("Start test workload on IBU cluster") startTestWorkload() By("Create configmap for oadp") oadpConfigmap := configmap.NewBuilder(APIClient, oadpContentConfigmap, mgmtparams.LCAOADPNamespace) var oadpConfigmapData = make(map[string]string) By("Add workload app backup oadp configmap") workloadBackup, err := brutil.WorkloadBackup.String() Expect(err).NotTo(HaveOccurred(), "error creating configmap data for workload app backup") oadpConfigmapData["workload_app_backup.yaml"] = workloadBackup By("Add workload app restore to oadp configmap") workloadRestore, err := brutil.WorkloadRestore.String() Expect(err).NotTo(HaveOccurred(), "error creating configmap data for workload app restore") oadpConfigmapData["workload_app_restore.yaml"] = workloadRestore _, err = namespace.Pull(APIClient, mgmtparams.LCAKlusterletNamespace) if err == nil { By("Add klusterlet backup oadp configmap") klusterletBackup, err := brutil.KlusterletBackup.String() Expect(err).NotTo(HaveOccurred(), "error creating configmap data for klusterlet backup content") oadpConfigmapData["klusterlet_backup.yaml"] = klusterletBackup By("Add klusterlet restore oadp configmap") klusterletRestore, err := brutil.KlusterletRestore.String() Expect(err).NotTo(HaveOccurred(), "error creating configmap data for klusterlet restire content") oadpConfigmapData["klusterlet_restore.yaml"] = klusterletRestore } By("Create oadpContent configmap") _, err = oadpConfigmap.WithData(oadpConfigmapData).Create() Expect(err).NotTo(HaveOccurred(), "error creating oadp configmap") }) AfterAll(func() { if !MGMTConfig.IdlePostUpgrade && MGMTConfig.RollbackAfterUpgrade { By("Revert IBU resource back to Idle stage") ibu, err = lca.PullImageBasedUpgrade(APIClient) Expect(err).NotTo(HaveOccurred(), "error pulling imagebasedupgrade resource") if ibu.Object.Spec.Stage == "Upgrade" { By("Set IBU stage to Rollback") _, err = ibu.WithStage("Rollback").Update() Expect(err).NotTo(HaveOccurred(), "error setting ibu to rollback stage") By("Wait for IBU resource to be available") err = nodestate.WaitForIBUToBeAvailable(APIClient, ibu, time.Minute*10) Expect(err).NotTo(HaveOccurred(), "error waiting for ibu resource to become available") By("Wait until Rollback stage has completed") _, err = ibu.WaitUntilStageComplete("Rollback") Expect(err).NotTo(HaveOccurred(), "error waiting for rollback stage to complete") } if slices.Contains([]string{"Prep", "Rollback"}, string(ibu.Object.Spec.Stage)) { By("Set IBU stage to Idle") _, err = ibu.WithStage("Idle").Update() Expect(err).NotTo(HaveOccurred(), "error setting ibu to idle stage") By("Wait until IBU has become Idle") _, err = ibu.WaitUntilStageComplete("Idle") Expect(err).NotTo(HaveOccurred(), "error waiting for idle stage to complete") } Expect(string(ibu.Object.Spec.Stage)).To(Equal("Idle"), "error: ibu resource contains unexpected state") deleteTestWorkload() if MGMTConfig.ExtraManifests { By("Pull namespace extra manifests namespace") extraNamespace, err := namespace.Pull(APIClient, extraManifestNamespace) Expect(err).NotTo(HaveOccurred(), "error pulling namespace created by extra manifests") By("Delete extra manifest namespace") err = extraNamespace.DeleteAndWait(time.Minute * 1) Expect(err).NotTo(HaveOccurred(), "error deleting extra manifest namespace") By("Pull extra manifests namespace configmap") extraManifestsNamespaceConfigmap, err := configmap.Pull( APIClient, extraManifestNamespaceConfigmapName, mgmtparams.LCANamespace) Expect(err).NotTo(HaveOccurred(), "error pulling extra manifest namespace configmap") By("Delete extra manifests namespace configmap") err = extraManifestsNamespaceConfigmap.Delete() Expect(err).NotTo(HaveOccurred(), "error deleting extra manifest namespace configmap") By("Pull extra manifests configmap configmap") extraManifestsConfigmapConfigmap, err := configmap.Pull( APIClient, extraManifesConfigmapConfigmapName, mgmtparams.LCANamespace) Expect(err).NotTo(HaveOccurred(), "error pulling extra manifest configmap configmap") By("Delete extra manifests configmap configmap") err = extraManifestsConfigmapConfigmap.Delete() Expect(err).NotTo(HaveOccurred(), "error deleting extra manifest configmap configmap") } } }) It("upgrades the connected cluster", reportxml.ID("71362"), func() { By("Check if the target cluster is connected") connected, err := cluster.Connected(APIClient) if !connected { Skip("Target cluster is disconnected") } if err != nil { Skip(fmt.Sprintf("Encountered an error while getting cluster connection info: %s", err.Error())) } upgrade() }) It("upgrades the disconnected cluster", reportxml.ID("71736"), func() { By("Check if the target cluster is disconnected") disconnected, err := cluster.Disconnected(APIClient) if !disconnected { Skip("Target cluster is connected") } if err != nil { Skip(fmt.Sprintf("Encountered an error while getting cluster connection info: %s", err.Error())) } upgrade() }) It("successfully creates extramanifests", reportxml.ID("71556"), func() { if !MGMTConfig.ExtraManifests { Skip("Cluster not upgraded with extra manifests") } By("Pull namespace created by extra manifests") extraNamespace, err := namespace.Pull(APIClient, extraManifestNamespace) Expect(err).NotTo(HaveOccurred(), "error pulling namespace created by extra manifests") By("Pull configmap created by extra manifests") extraConfigmap, err := configmap.Pull(APIClient, extraManifestConfigmap, extraNamespace.Object.Name) Expect(err).NotTo(HaveOccurred(), "error pulling configmap created by extra manifests") Expect(len(extraConfigmap.Object.Data)).To(Equal(1), "error: got unexpected data in configmap") Expect(extraConfigmap.Object.Data["hello"]).To(Equal("world"), "error: extra manifest configmap has incorrect content") }) It("contains same proxy configuration as seed after upgrade", reportxml.ID("73103"), func() { if originalTargetProxy.Object.Spec.HTTPProxy == "" && originalTargetProxy.Object.Spec.HTTPSProxy == "" && originalTargetProxy.Object.Spec.NoProxy == "" { Skip("Target was not installed with proxy") } if originalTargetProxy.Object.Spec.HTTPProxy != MGMTConfig.SeedClusterInfo.Proxy.HTTPProxy || originalTargetProxy.Object.Spec.HTTPSProxy != MGMTConfig.SeedClusterInfo.Proxy.HTTPSProxy { Skip("Target was not installed with the same proxy as seed") } targetProxyPostUpgrade, err := proxy.Pull(APIClient) Expect(err).NotTo(HaveOccurred(), "error pulling target proxy") Expect(originalTargetProxy.Object.Spec.HTTPProxy).To(Equal(targetProxyPostUpgrade.Object.Spec.HTTPProxy), "HTTP_PROXY postupgrade config does not match pre upgrade config") Expect(originalTargetProxy.Object.Spec.HTTPSProxy).To(Equal(targetProxyPostUpgrade.Object.Spec.HTTPSProxy), "HTTPS_PROXY postupgrade config does not match pre upgrade config") Expect(originalTargetProxy.Object.Spec.NoProxy).To(Equal(targetProxyPostUpgrade.Object.Spec.NoProxy), "NO_PROXY postupgrade config does not match pre upgrade config") }) It("contains different proxy configuration than seed after upgrade", reportxml.ID("73369"), func() { if originalTargetProxy.Object.Spec.HTTPProxy == "" && originalTargetProxy.Object.Spec.HTTPSProxy == "" && originalTargetProxy.Object.Spec.NoProxy == "" { Skip("Target was not installed with proxy") } if originalTargetProxy.Object.Spec.HTTPProxy == MGMTConfig.SeedClusterInfo.Proxy.HTTPProxy && originalTargetProxy.Object.Spec.HTTPSProxy == MGMTConfig.SeedClusterInfo.Proxy.HTTPSProxy { Skip("Target was installed with the same proxy as seed") } targetProxyPostUpgrade, err := proxy.Pull(APIClient) Expect(err).NotTo(HaveOccurred(), "error pulling target proxy") Expect(originalTargetProxy.Object.Spec.HTTPProxy).To(Equal(targetProxyPostUpgrade.Object.Spec.HTTPProxy), "HTTP_PROXY postupgrade config does not match pre upgrade config") Expect(originalTargetProxy.Object.Spec.HTTPSProxy).To(Equal(targetProxyPostUpgrade.Object.Spec.HTTPSProxy), "HTTPS_PROXY postupgrade config does not match pre upgrade config") Expect(originalTargetProxy.Object.Spec.NoProxy).To(Equal(targetProxyPostUpgrade.Object.Spec.NoProxy), "NO_PROXY postupgrade config does not match pre upgrade config") }) It("fails because from Upgrade it's not possible to move to Prep stage", reportxml.ID("71741"), func() { By("Pull the imagebasedupgrade from the cluster") ibu, err = lca.PullImageBasedUpgrade(APIClient) Expect(err).NotTo(HaveOccurred(), "error pulling imagebasedupgrade resource") if ibu.Object.Spec.Stage != "Upgrade" { Skip("IBU is not in Upgrade stage") } _, err := ibu.WithStage("Prep").Update() Expect(err.Error()).To(ContainSubstring("the stage transition is not permitted"), "error: ibu seedimage updated with wrong next stage") }) }) //nolint:funlen func upgrade() { By("Updating the seed image reference") ibu, err = ibu.WithSeedImage(MGMTConfig.SeedImage). WithSeedImageVersion(MGMTConfig.SeedClusterInfo.SeedClusterOCPVersion).Update() Expect(err).NotTo(HaveOccurred(), "error updating ibu with image and version") By("Updating the oadpContent") ibu, err = ibu.WithOadpContent(oadpContentConfigmap, mgmtparams.LCAOADPNamespace).Update() Expect(err).NotTo(HaveOccurred(), "error updating ibu oadp content") By("Setting the IBU stage to Prep") _, err := ibu.WithStage("Prep").Update() Expect(err).NotTo(HaveOccurred(), "error setting ibu to prep stage") By("Wait until Prep stage has completed") _, err = ibu.WaitUntilStageComplete("Prep") Expect(err).NotTo(HaveOccurred(), "error waiting for prep stage to complete") By("Get list of nodes to be upgraded") ibuNodes, err := nodes.List(APIClient) Expect(err).NotTo(HaveOccurred(), "error listing nodes") By("Set the IBU stage to Upgrade") _, err = ibu.WithStage("Upgrade").Update() Expect(err).NotTo(HaveOccurred(), "error setting ibu to upgrade stage") By("Wait for nodes to become unreachable") for _, node := range ibuNodes { unreachable, err := nodestate.WaitForNodeToBeUnreachable(node.Object.Name, "6443", time.Minute*15) Expect(err).To(BeNil(), "error waiting for %s node to shutdown", node.Object.Name) Expect(unreachable).To(BeTrue(), "error: node %s is still reachable", node.Object.Name) } By("Wait for nodes to become reachable") for _, node := range ibuNodes { reachable, err := nodestate.WaitForNodeToBeReachable(node.Object.Name, "6443", time.Minute*20) Expect(err).To(BeNil(), "error waiting for %s node to become reachable", node.Object.Name) Expect(reachable).To(BeTrue(), "error: node %s is still unreachable", node.Object.Name) } By("Wait until all nodes are reporting as Ready") err = safeapirequest.Do(func() error { _, err := nodes.WaitForAllNodesAreReady(APIClient, time.Minute*10) return err }) Expect(err).To(BeNil(), "error waiting for nodes to become ready") By("Wait for IBU resource to be available") err = nodestate.WaitForIBUToBeAvailable(APIClient, ibu, time.Minute*10) Expect(err).NotTo(HaveOccurred(), "error waiting for ibu resource to become available") By("Wait until Upgrade stage has completed") ibu, err = ibu.WaitUntilStageComplete("Upgrade") Expect(err).NotTo(HaveOccurred(), "error waiting for upgrade stage to complete") By("Check the clusterversion matches seedimage version") clusterVersion, err := clusterversion.Pull(APIClient) Expect(err).NotTo(HaveOccurred(), "error pulling clusterversion") Expect(MGMTConfig.SeedClusterInfo.SeedClusterOCPVersion).To( Equal(clusterVersion.Object.Status.Desired.Version), "error: clusterversion does not match seedimageversion") By("Check that no cluster operators are progressing") cosStoppedProgressing, err := clusteroperator.WaitForAllClusteroperatorsStopProgressing(APIClient, time.Minute*5) Expect(err).NotTo(HaveOccurred(), "error while waiting for cluster operators to stop progressing") Expect(cosStoppedProgressing).To(BeTrue(), "error: some cluster operators are still progressing") By("Check that all cluster operators are available") cosAvailable, err := clusteroperator.WaitForAllClusteroperatorsAvailable(APIClient, time.Minute*5) Expect(err).NotTo(HaveOccurred(), "error while waiting for cluster operators to become available") Expect(cosAvailable).To(BeTrue(), "error: some cluster operators are not available") By("Check that all pods are running in workload namespace") workloadPods, err := pod.List(APIClient, mgmtparams.LCAWorkloadName) Expect(err).NotTo(HaveOccurred(), "error listing pods in workload namespace %s", mgmtparams.LCAWorkloadName) Expect(len(workloadPods) > 0).To(BeTrue(), "error: found no running pods in workload namespace %s", mgmtparams.LCAWorkloadName) for _, workloadPod := range workloadPods { err := workloadPod.WaitUntilReady(time.Minute * 2) Expect(err).To(BeNil(), "error waiting for workload pod to become ready") } verifyIBUWorkloadReachable() _, err = namespace.Pull(APIClient, mgmtparams.LCAKlusterletNamespace) if err == nil { By("Check that all pods are running in klusterlet namespace") klusterletPods, err := pod.List(APIClient, mgmtparams.LCAKlusterletNamespace) Expect(err).NotTo(HaveOccurred(), "error listing pods in kusterlet namespace %s", mgmtparams.LCAKlusterletNamespace) Expect(len(klusterletPods) > 0).To(BeTrue(), "error: found no running pods in klusterlet namespace %s", mgmtparams.LCAKlusterletNamespace) for _, klusterletPod := range klusterletPods { // We check if the pod is terminataing or if it still exists to // mitigate situations where a leftover pod is still found but gets removed. if klusterletPod.Object.Status.Phase != "Terminating" { err := klusterletPod.WaitUntilReady(time.Minute * 2) if klusterletPod.Exists() { Expect(err).To(BeNil(), "error waiting for klusterlet pod to become ready") } } } } if MGMTConfig.IdlePostUpgrade && !MGMTConfig.RollbackAfterUpgrade { By("Set the IBU stage to Idle") _, err = ibu.WithStage("Idle").Update() Expect(err).NotTo(HaveOccurred(), "error setting ibu to idle stage") } } func updateIBUWithCustomCatalogSources(imagebasedupgrade *lca.ImageBasedUpgradeBuilder) { catalogSources, err := olm.ListCatalogSources(APIClient, "openshift-marketplace") Expect(err).NotTo(HaveOccurred(), "error listing catalogsources in openshift-marketplace namespace") omitCatalogRegex := regexp.MustCompile(`(redhat|certified|community)-(operators|marketplace)`) for _, catalogSource := range catalogSources { if !omitCatalogRegex.MatchString(catalogSource.Object.Name) { configmapData, err := brutil.NewBackRestoreObject( catalogSource.Object, APIClient.Scheme(), oplmV1alpha1.SchemeGroupVersion).String() Expect(err).NotTo(HaveOccurred(), "error creating configmap data from catalogsource content") By("Create configmap with catalogsource information") _, err = configmap.NewBuilder(APIClient, fmt.Sprintf("%s-configmap", catalogSource.Object.Name), mgmtparams.LCANamespace).WithData( map[string]string{ fmt.Sprintf("99-%s-catalogsource", catalogSource.Object.Name): configmapData, }).Create() Expect(err).NotTo(HaveOccurred(), "error creating configmap from user-defined catalogsource") By("Updating IBU to include configmap") imagebasedupgrade.WithExtraManifests(fmt.Sprintf("%s-configmap", catalogSource.Object.Name), mgmtparams.LCANamespace) } } } func startTestWorkload() { By("Check if workload app namespace exists") if ibuWorkloadNamespace, err = namespace.Pull(APIClient, mgmtparams.LCAWorkloadName); err == nil { deleteTestWorkload() } By("Create workload app namespace") ibuWorkloadNamespace, err = namespace.NewBuilder(APIClient, mgmtparams.LCAWorkloadName).Create() Expect(err).NotTo(HaveOccurred(), "error creating namespace for ibu workload app") By("Create workload app deployment") _, err = deployment.NewBuilder( APIClient, mgmtparams.LCAWorkloadName, mgmtparams.LCAWorkloadName, map[string]string{ "app": mgmtparams.LCAWorkloadName, }, &v1.Container{ Name: mgmtparams.LCAWorkloadName, Image: MGMTConfig.IBUWorkloadImage, Ports: []v1.ContainerPort{ { Name: "http", ContainerPort: 8080, }, }, }).WithLabel("app", mgmtparams.LCAWorkloadName).CreateAndWaitUntilReady(time.Second * 60) Expect(err).NotTo(HaveOccurred(), "error creating ibu workload deployment") By("Create workload app service") _, err = service.NewBuilder( APIClient, mgmtparams.LCAWorkloadName, mgmtparams.LCAWorkloadName, map[string]string{ "app": mgmtparams.LCAWorkloadName, }, v1.ServicePort{ Protocol: v1.ProtocolTCP, Port: 8080, }).Create() Expect(err).NotTo(HaveOccurred(), "error creating ibu workload service") By("Create workload app route") ibuWorkloadRoute, err = route.NewBuilder( APIClient, mgmtparams.LCAWorkloadName, mgmtparams.LCAWorkloadName, mgmtparams.LCAWorkloadName).Create() Expect(err).NotTo(HaveOccurred(), "error creating ibu workload route") verifyIBUWorkloadReachable() } func deleteTestWorkload() { By("Delete ibu workload namespace") err := ibuWorkloadNamespace.DeleteAndWait(time.Second * 30) Expect(err).NotTo(HaveOccurred(), "error deleting ibu workload namespace") } func verifyIBUWorkloadReachable() { By("Verify IBU workload is reachable") err := wait.PollUntilContextTimeout( context.TODO(), time.Second*2, time.Second*10, true, func(ctx context.Context) (bool, error) { _, rc, _ := url.Fetch(fmt.Sprintf("http://%s", ibuWorkloadRoute.Object.Spec.Host), "get", false) return rc == 200, nil }, ) Expect(err).NotTo(HaveOccurred(), "error reaching ibu workload") }
package com.changhong.smarthome.phone.foundation.activity; import java.util.ArrayList; import java.util.List; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import com.changhong.smarthome.phone.R; import com.changhong.smarthome.phone.foundation.baseapi.MsgWhat; import com.changhong.smarthome.phone.foundation.bean.Community; import com.changhong.smarthome.phone.foundation.logic.AddCommunityLogic; import com.changhong.smarthome.phone.foundation.logic.SelectCommunityLogic; import com.lidroid.xutils.HttpUtils; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.view.annotation.ViewInject; public class CommunitySelectActivity extends BaseActivity { @ViewInject(R.id.etSearch) private EditText etSearch; @ViewInject(R.id.btnSearch) private Button btnSearch; @ViewInject(R.id.listView) private ListView listView; private SelectCommunityLogic selectLogic; private Adapter adapter; private HttpUtils selectHttpUtil; private List<Community> list = new ArrayList<Community>(); private AddCommunityLogic addLogic; private HttpUtils addHttpUtil; @Override public void initData() { selectLogic = SelectCommunityLogic.getInstance(); Community cc = new Community(); cc.setId("111"); cc.setName("社区111"); cc.setAddress("代付款理发店里看能否"); selectLogic.list.add(cc); cc = new Community(); cc.setId("222"); cc.setName("社区222"); cc.setAddress("代付款理发店里看能否"); selectLogic.list.add(cc); cc = new Community(); cc.setId("333"); cc.setName("社区333"); cc.setAddress("代付款理发店里看能否"); selectLogic.list.add(cc); } @Override public void initLayout(Bundle paramBundle) { setContentView(R.layout.community_select_layout); ViewUtils.inject(this); String cityName = getIntent().getStringExtra("cityName"); etSearch.setText("搜索" + cityName + "小区"); initAdater(); requestSelectCommunityData(); } public void requestSelectCommunityData() { selectHttpUtil = new HttpUtils(); selectLogic.setData(mHandler); String cityId = getIntent().getStringExtra("cityId"); //String cityId = "320100"; selectLogic.requestCommunity(cityId, selectHttpUtil); } @Override public void handleMsg(android.os.Message msg) { switch (msg.what) { case MsgWhat.MSGWHAT_SELECT_COMMUNITY_SUCCESS: { for (int i = 0; i < selectLogic.list.size(); i++) { Community cc = new Community(); cc.setId(selectLogic.list.get(i).getId()); cc.setName(selectLogic.list.get(i).getName()); list.add(cc); } initAdater(); break; } case MsgWhat.MSGWHAT_ADD_COMMUNITY_SUCCESS: { finish(); } default: { break; } } }; public void initAdater() { if (null == adapter) { adapter = new Adapter(); listView.setAdapter(adapter); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { int typeSrc = getIntent().getIntExtra("typeSrc", 0); //选择小区来源于 小区管理页面 if (typeSrc == 1) { addLogic = AddCommunityLogic.getInstance(); addHttpUtil = new HttpUtils(); addLogic.setData(mHandler); String userId = "1"; String communityId = selectLogic.list.get(position).getId(); addLogic.requestAddCommunity(userId,communityId,addHttpUtil); String city = getIntent().getStringExtra("cityName"); Intent intent = new Intent(); intent.putExtra("name", city + selectLogic.list.get(position).getName()); intent.putExtra("image", R.drawable.community_default_picture); intent.putExtra("communityId", communityId); //将数据带回小区管理页面 CommunitySelectActivity.this.setResult(RESULT_OK, intent); } //选择小区来源于登录页面 else { Log.i("------------", "login"); } } }); } else { adapter.notifyDataSetChanged(); } } @Override public void clearData() { } class Adapter extends BaseAdapter { @Override public int getCount() { return selectLogic.list.size(); } @Override public Community getItem(int position) { return selectLogic.list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder = null; if (convertView == null) { viewHolder = new ViewHolder(); convertView = LayoutInflater.from(getBaseContext()) .inflate(R.layout.community_item_layout, null); viewHolder.tvName = (TextView) convertView.findViewById(R.id.tvName); viewHolder.tvArear = (TextView) convertView.findViewById(R.id.tvArear); viewHolder.tvAddress = (TextView) convertView.findViewById(R.id.tvAddress); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.tvName.setText(getItem(position).getName()); viewHolder.tvArear.setText(getItem(position).getArea()); viewHolder.tvAddress.setText(getItem(position).getAddress()); return convertView; } class ViewHolder { public TextView tvName; public TextView tvArear; public TextView tvAddress; } } }
import React from "react"; const ToDoItem = ({ text, setTodos, todos, todoItem }) => { const deleteHandler = () => { setTodos(todos.filter((el) => el.id !== todoItem.id)); }; const completedHandler = () => { setTodos( todos.map((el) => { if (el.id === todoItem.id) { return { ...el, completed: !el.completed, }; } return el; }) ); }; return ( <div className="todo"> <li className={`todo-item ${todoItem.completed ? "completed" : ""}`}> {text} </li> <button onClick={completedHandler} className="complete-btn"> <i className="fas fa-check"></i> </button> <button onClick={deleteHandler} className="trash-btn"> <i className="fas fa-trash"></i> </button> </div> ); }; export default ToDoItem;
// Tencent is pleased to support the open source community by making // 蓝鲸智云 - 监控平台 (BlueKing - Monitor) available. // Copyright (C) 2022 THL A29 Limited, a Tencent company. All rights reserved. // Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://opensource.org/licenses/MIT // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on // an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. package scraper import ( "bufio" "bytes" "context" "encoding/base64" "fmt" "io" "net" "net/http" "net/url" "os" "strings" "time" "github.com/elastic/beats/libbeat/common/transport/tlscommon" "github.com/elastic/beats/libbeat/outputs" "github.com/elastic/beats/libbeat/outputs/transport" "github.com/pkg/errors" "gopkg.in/yaml.v2" ) type ModuleConfig struct { Tasks []struct { Module TaskConfig `yaml:"module"` } `yaml:"tasks"` } type TaskConfig struct { Hosts []string `yaml:"hosts"` MetricsPath string `yaml:"metrics_path"` BearerFile string `yaml:"bearer_file"` Query url.Values `yaml:"query"` Ssl *tlscommon.Config `yaml:"ssl"` Username string `yaml:"username"` Password string `yaml:"password"` ProxyURL string `yaml:"proxy_url"` Headers map[string]string `yaml:"headers"` Timeout time.Duration `yaml:"timeout"` } type Scraper struct { client *http.Client config TaskConfig } func (c *Scraper) doRequest(host string) (*http.Response, error) { u := host + c.config.MetricsPath req, err := http.NewRequest(http.MethodGet, u, &bytes.Buffer{}) if err != nil { return nil, err } for k, v := range c.config.Headers { req.Header.Set(k, v) } if len(c.config.Query) > 0 { req.URL.RawQuery = c.config.Query.Encode() } return c.client.Do(req) } func (c *Scraper) StringCh() chan string { ch := make(chan string, 1) go func() { defer close(ch) for _, host := range c.config.Hosts { resp, err := c.doRequest(host) if err != nil { continue } defer resp.Body.Close() if resp.StatusCode >= 400 { b, _ := io.ReadAll(resp.Body) msg := fmt.Sprintf("scrape error => status code: %v, response: %v", resp.StatusCode, string(b)) ch <- msg continue } scanner := bufio.NewScanner(resp.Body) for scanner.Scan() { line := scanner.Text() if strings.HasPrefix(line, "#") || line == "" { continue } ch <- line } } }() return ch } func (c *Scraper) Lines() (int, []error) { var errs []error var total int for _, host := range c.config.Hosts { resp, err := c.doRequest(host) if err != nil { errs = append(errs, err) continue } defer resp.Body.Close() if resp.StatusCode >= 400 { b, _ := io.ReadAll(resp.Body) errs = append(errs, fmt.Errorf("scrape error => status code: %v, response: %v", resp.StatusCode, string(b))) continue } scanner := bufio.NewScanner(resp.Body) for scanner.Scan() { line := scanner.Text() if strings.HasPrefix(line, "#") || line == "" { continue } total++ } } return total, errs } func New(data []byte) (*Scraper, error) { var module ModuleConfig // TODO(optimize): beats tlscommon 对 verification_mode 字段做了特殊处理 所以这里采用了`取巧`方法进行替换 // 避免解析出错 后续有更简洁的方式可进行优化 data = bytes.ReplaceAll(data, []byte(`verification_mode: none`), []byte(`verification_mode: 1`)) if err := yaml.Unmarshal(data, &module); err != nil { return nil, err } if len(module.Tasks) <= 0 { return nil, errors.New("no tasks available") } config := module.Tasks[0].Module if config.Headers == nil { config.Headers = map[string]string{} } config.Headers["Accept"] = "application/openmetrics-text,*/*" config.Headers["X-BK-AGENT"] = "bkmonitor-operator" if config.BearerFile != "" { b, err := os.ReadFile(config.BearerFile) if err != nil { return nil, errors.Wrap(err, "read bearer file failed") } config.Headers["Authorization"] = fmt.Sprintf("Bearer %s", b) } if config.Username != "" || config.Password != "" { auth := config.Username + ":" + config.Password config.Headers["Authorization"] = fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(auth))) } tlsConfig, err := outputs.LoadTLSConfig(config.Ssl) if err != nil { return nil, errors.Wrap(err, "load tls config failed") } if tlsConfig != nil { tlsConfig.Verification = tlscommon.VerifyNone } var dialer, tlsDialer transport.Dialer dialer = transport.NetDialer(config.Timeout) tlsDialer, err = transport.TLSDialer(dialer, tlsConfig, config.Timeout) if err != nil { return nil, errors.Wrap(err, "create tls dialer failed") } trp := &http.Transport{ DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { return dialer.Dial(network, addr) }, DialTLSContext: func(ctx context.Context, network, addr string) (net.Conn, error) { return tlsDialer.Dial(network, addr) }, IdleConnTimeout: time.Minute, } if config.ProxyURL != "" { parsed, err := url.Parse(config.ProxyURL) if err != nil { return nil, errors.Wrap(err, "parse proxy url failed") } trp.Proxy = http.ProxyURL(parsed) } return &Scraper{ client: &http.Client{ Transport: trp, Timeout: config.Timeout, }, config: config, }, nil }
from restapi.user.entities.interfaces.user_email_interface import UserEmailInterface from itsdangerous import URLSafeTimedSerializer from django.core.mail import send_mail, get_connection from django.conf import settings import logging from os import getenv, path, makedirs, getenv logger = logging.getLogger(__name__) class UserEmailAdapter(UserEmailInterface): def __init__(self, database) -> None: self.db = database() def generate_token(self, email): serializer = URLSafeTimedSerializer(getenv('SECRET_KEY')) return serializer.dumps(email, salt=getenv("SECURITY_PASSWORD_SALT")) def confirm_token(self, token, expiration=3600): serializer = URLSafeTimedSerializer(getenv('SECRET_KEY')) try: email = serializer.loads( token, salt=getenv("SECURITY_PASSWORD_SALT"), max_age=expiration ) return email except Exception: return False def email_send_token(self, email, token): send_mail( "Movies App Confirmation Token", "token: {token}".format(token=token), getenv("MAIL_DEFAULT_SENDER"), [email], fail_silently=False )
import pandas as pd from dataset_utils import create_graph_from_sequence, create_graph_with_embeddings from tqdm import tqdm import pickle class DNADataset: def __init__(self, file_path, k_mer=4, stride=1, data_count=None, truncate=None, task='order_name'): # task can be 'order_name', 'genus_name', 'family_name', 'species_name' self.k_mer = k_mer train_csv = pd.read_csv(file_path) self.barcodes = train_csv['nucleotides'].to_list() if data_count is not None: self.barcodes = self.barcodes[:data_count] if truncate is not None: self.barcodes = [seq[:truncate] for seq in self.barcodes] self.labels = train_csv[task].to_list() unique_labels = sorted(list(set(self.labels))) self.number_of_classes = len(unique_labels) self.label2idx = {label: idx for idx, label in enumerate(unique_labels)} with open(f'kmers_embedding/kmer_vectors_{self.k_mer}.pkl', 'rb') as f: self.embeddings = pickle.load(f) self.graphs = [create_graph_from_sequence(seq, k=self.k_mer, label=self.label2idx[self.labels[i]], kmer_embeddings=self.embeddings, stride=stride) for i, seq in tqdm(enumerate(self.barcodes))] # self.graphs = [create_graph_from_sequence(seq, k=self.k_mer, label=self.label2idx[self.labels[i]], # kmer_embeddings=None, stride=stride) for i, seq in # tqdm(enumerate(self.barcodes))] node_count = [] edge_count = [] for graph in self.graphs: node_count.append(graph.num_nodes) edge_count.append(graph.edge_index.size(1)) self.average_node_count = {sum(node_count) / len(node_count)} self.average_edge_count = {sum(edge_count) / len(edge_count)} if __name__ == "__main__": temp = DNADataset('data/supervised_train.csv', k_mer=5, stride=5, task='genus_name') temp2 = DNADataset('data/supervised_test.csv', k_mer=5, stride=5, task='order_name') print(temp.average_node_count) print(temp.average_edge_count) print(temp.number_of_classes)
(ns weeknotes-notes.system (:require [babashka.fs :as fs] [integrant.core :as ig] [org.httpkit.server :as httpkit] [weeknotes-notes.core :as core] [weeknotes-notes.assembly :as assembly] [weeknotes-notes.store :as store])) ;; Our system components are: :weeknotes-notes/store ;; a way to store EDN. :weeknotes-notes/injected-app ;; an function from request to response, with required dependencies injected. :weeknotes-notes/http-server ;; a real, running HTTP-server bound to a port. (defmethod ig/init-key :weeknotes-notes/store [_ {:keys [root]}] (store/->FolderBackedEdnStore root)) (defmethod ig/init-key :weeknotes-notes/injected-app [_ {:keys [store]}] (fn [req] (-> req (assoc :weeknotes-notes/store store) assembly/request-enter assembly/wrapped-app assembly/response-exit))) (defmethod ig/init-key :weeknotes-notes/http-server [_ {:keys [port app]}] (println "Server starting on " (str "http://localhost:" port)) (httpkit/run-server app {:legacy-return-value? false :host "0.0.0.0" :port port})) (defmethod ig/halt-key! :weeknotes-notes/http-server [_ server] (httpkit/server-stop! server)) (comment (def mysys (ig/init (core/default-config))) (ig/halt! mysys) (store/list-uuids (:weeknotes-notes/store mysys)) :rcf)
// // BedtimeWindow.swift // OuraWidgetExtension // // Created by Aliaksandr Drankou on 02.01.2023. // import Foundation struct IdealBedtimeResponse: Codable { let ideal_bedtimes: [IdealBedtime] } struct IdealBedtime: Codable { let date: String let bedtime_window: BedtimeWindowValue let status: BedtimeWindowStatus } struct BedtimeWindowValue: Codable { let start: Int? let end: Int? } enum BedtimeWindowStatus: String, Codable { case UNKNOWN = "UNKNOWN" case MISSING_API_KEY = "MISSING_API_KEY" case NOT_ENOUGH_DATA = "NOT_ENOUGH_DATA" case LOW_SLEEP_SCORES = "LOW_SLEEP_SCORES" case IDEAL_BEDTIME_AVAILABLE = "IDEAL_BEDTIME_AVAILABLE" func formatString() -> String { switch self { case .MISSING_API_KEY: return "Missing API key" case .UNKNOWN: return "Unknown" case .NOT_ENOUGH_DATA: return "Not enough data" case .LOW_SLEEP_SCORES: return "Low sleep scores" case .IDEAL_BEDTIME_AVAILABLE: return "Ideal bedtime available" } } } struct BedtimeWindowRich { struct Time { var hour: Int var minute: Int } var start: Time var end: Time } struct BedtimeWindow: Codable { var start: Int = 0 var end: Int = 0 var status: BedtimeWindowStatus = .UNKNOWN var isAvailable: Bool { status == .IDEAL_BEDTIME_AVAILABLE } var errorMessage: String = "" func formatString() -> String { let dateFormatter = DateFormatter() dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)! dateFormatter.setLocalizedDateFormatFromTemplate("HHmm") let startDate = Date(timeIntervalSince1970: TimeInterval(self.start)) let endDate = Date(timeIntervalSince1970: TimeInterval(self.end)) let startTimeString = dateFormatter.string(from: startDate) let endTimeString = dateFormatter.string(from: endDate) return "\(startTimeString) - \(endTimeString)" } func rich() -> BedtimeWindowRich { var calendar = Calendar.current calendar.timeZone = TimeZone(secondsFromGMT: 0)! let startDate = Date(timeIntervalSince1970: TimeInterval(self.start)) let endDate = Date(timeIntervalSince1970: TimeInterval(self.end)) let startHour = calendar.component(.hour, from: startDate) let startMinute = calendar.component(.minute, from: startDate) let endHour = calendar.component(.hour, from: endDate) let endMinute = calendar.component(.minute, from: endDate) return BedtimeWindowRich( start: BedtimeWindowRich.Time(hour: toTwelveHourFormat(hour: startHour), minute: startMinute), end: BedtimeWindowRich.Time(hour: toTwelveHourFormat(hour: endHour), minute: endMinute) ) } } func toTwelveHourFormat(hour: Int) -> Int { return hour > 12 ? hour - 12 : hour } let BedtimeWindowPlaceholder: BedtimeWindow = BedtimeWindow(start: -9000, end: -6300, status: .IDEAL_BEDTIME_AVAILABLE) //21:30 - 22:15
"use server"; import * as z from "zod"; import { ResourceWorkOrderSchema } from "@/schemas/index"; import { BASE_URL } from "@/config/const"; import { ResourceWorkOdderData, ResponseData, WorkOrderData } from "@/types"; import { Axios } from "@/action/axios"; interface data { status: boolean; message: string; data: string; } export const getAllResourceWorkOrder = async () => { try { const axiosResponse = await Axios.get("/resource/getAllResource"); const data = axiosResponse.data; return data; } catch (error) { const errorResponse: ResponseData = { status: false, message: JSON.stringify(error), data: "", }; return errorResponse; } }; export const getAllResourceWorkOrderByStatus = async (value: string) => { try { const axiosResponse = await Axios.get( `/resource/getResourceByStatus?Resource_status=${value}` ); const data = axiosResponse.data; return data; } catch (error) { const errorResponse: ResponseData = { status: false, message: JSON.stringify(error), data: "", }; return errorResponse; } }; export const createResourceWorkOrder = async ( value: z.infer<typeof ResourceWorkOrderSchema>[] ) => { try { console.log(value); const axiosResponse = await Axios.post("/resource/multiple-create", value); const data = axiosResponse.data; console.log(data); return data; } catch (error) { console.log(error); const errorResponse: ResponseData = { status: false, message: JSON.stringify(error), data: "", }; return errorResponse; } }; export const updateResourceWorkOrder = async (value: any) => { try { const axiosResponse = await Axios.put("/resource/update", value); const data = axiosResponse.data; return data; } catch (error) { // console.log(error); const errorResponse: ResponseData = { status: false, message: JSON.stringify(error), data: "", }; return errorResponse; } }; export const deleteResourceWorkOrder = async (value: any) => { try { const axiosResponse = await Axios.delete( `/resource//delete?id=${value}`, value ); const data = axiosResponse.data; return data; } catch (error) { const errorResponse: ResponseData = { status: false, message: JSON.stringify(error), data: "", }; return errorResponse; } };
--- title: Добавление, настройка, перемещение или удаление полей в форме | Документация Майкрософт ms.custom: '' ms.date: 08/26/2019 ms.reviewer: '' ms.service: powerapps ms.suite: '' ms.tgt_pltfrm: '' ms.topic: get-started-article applies_to: - Dynamics 365 (online) - Dynamics 365 Version 9.x - PowerApps author: Aneesmsft ms.author: matp manager: kvivek tags: - Power Apps maker portal impact search.audienceType: - maker search.app: - PowerApps - D365CE ms.openlocfilehash: d711a46676003786363f3496515dbd387024dadb ms.sourcegitcommit: dd2a8a0362a8e1b64a1dac7b9f98d43da8d0bd87 ms.translationtype: HT ms.contentlocale: ru-RU ms.lasthandoff: 12/02/2019 ms.locfileid: "2860690" --- # <a name="add-configure-move-or-delete-fields-on-a-form"></a>Добавление, настройка, перемещение или удаление полей в форме Добавление, настройка, перемещение или удаление полей с помощью конструктора форм. ## <a name="add-fields-to-a-form"></a>Добавление полей в форму Для добавления полей в форму используйте область **Поля**. Область **Поля** позволяет осуществлять поиск и фильтрацию, чтобы можно было быстро находить нужные поля. Она также включает параметр для отображения только неиспользуемых полей. > [!div class="mx-imgBorder"] > ![](media/FormDesignerFieldsPane.png "Fields pane") ### <a name="add-fields-to-a-form-using-drag-and-drop"></a>Добавление полей в форму с помощью перетаскивания > [!NOTE] > При добавлении или перемещении полей перетаскиванием помните, что предварительный просмотр формы реагирует и может отображать несколько столбцов разделов друг над другом. Чтобы обеспечить, чтобы добавляемое или перемещаемое поле находилось в столбце нужного раздела, перетаскивание привязано к другому полю, которое уже находится в столбце этого раздела. 1. Откройте конструктор форм для создания или редактирования формы. Дополнительные сведения: [Создание формы](create-and-edit-forms.md#create-a-form) или [Редактирование формы](create-and-edit-forms.md#edit-a-form) 2. На панели команд выберите **Добавить поле** или в левой панели выберите **Поля**. Панель **Поля** по умолчанию открывается при открытии конструктора форм. 3. На панели **Поля** с помощью поиска, фильтрации или прокрутки можно найти поле, которое требуется добавить. Если не удается найти поле, оно может уже находиться в форме. Снимите флажок **Показывать только неиспользуемые поля** для просмотра всех полей, включая уже добавленные в форму. 4. В области **Поля** выберите поле и перетащите его на предварительный просмотр формы. При перетаскивании поля на предварительный просмотр формы отображаются цели перетаскивания, куда можно добавить поле. 5. Перетащите поле в требуемое местоположение. Обратите внимание на следующее: - Поля можно перетаскивать в положение до или после любого существующего поля или компонента. - Поля можно также перетащить в пустую область в разделе. В этом случае поле будет добавлено в доступное пространство, чтобы равномерно распределить поля и компоненты по столбцам раздела. - При наведении указателя мыши на заголовок вкладки во время перетаскивания поля изменяется текущая выбранная вкладка, позволяя добавить поле на другую вкладку. 6. Повторите шаги 3–5 выше, если требуется добавить несколько полей. 7. На панели команд выберите **Сохранить** для сохранения формы или выберите **Опубликовать**, если требуется сохранить изменения и сделать их видимыми пользователям. ### <a name="add-fields-to-a-form-using-selection"></a>Добавление полей в форму с помощью выбора 1. Откройте конструктор форм для создания или редактирования формы. Дополнительные сведения: [Создание формы](create-and-edit-forms.md#create-a-form) или [Редактирование формы](create-and-edit-forms.md#edit-a-form) 2. В режиме предварительного просмотра формы выберите другое существующее поле или раздел. Обратите внимание на следующее: - При выборе существующего поля новое поле добавляется после существующего поля. - При выборе раздела новое поле добавляется в доступное пространство, чтобы равномерно распределить поля по столбцам раздела. 3. На панели команд выберите **Добавить поле** или в левой панели выберите **Поля**. Панель **Поля** по умолчанию открывается при открытии конструктора форм. 4. На панели **Поля** с помощью поиска, фильтрации или прокрутки можно найти поле, которое требуется добавить. Если не удается найти поле, оно может уже находиться в форме. Снимите флажок **Показывать только неиспользуемые поля** для просмотра всех полей, включая уже добавленные в форму. 5. В области **Поля** выберите поле для добавления в форму. Можно также выбрать **...** рядом с требуемым полем, затем выберите **Добавить в выбранный раздел**. 6. Повторите шаги 2–5 выше, если требуется добавить несколько полей. 7. На панели команд выберите **Сохранить** для сохранения формы или выберите **Опубликовать**, если требуется сохранить изменения и сделать их видимыми пользователям. ## <a name="configure-fields-on-a-form"></a>Настройка полей в форме Это свойства, доступные для настройки поля при создании или редактировании формы с помощью конструктора форм. ## <a name="field-properties"></a>Свойства поля |Диаграмма с областями |Имя |Описание | |---------|---------|---------| |**Параметры отображения** | **Подпись поля** | По умолчанию подпись совпадает с отображаемым именем поля. Это имя формы можно переопределять, введя здесь другую подпись. <br /><br />Это обязательное свойство. | |**Параметры отображения** | **Имя поля** | Имя поля. Это поступает из свойств поля в сущности и доступно только для чтения. | |**Параметры отображения** | **Скрыть подпись** | Если установлен, подпись поля скрыта. | |**Параметры отображения** | **Поле только для чтения** | Если выбрано, значение поля не является изменяемым. | |**Параметры отображения** | **Блокировать поле** | Заблокируйте это поле, чтобы его нельзя было удалить. | |**Параметры отображения** | **Скрыть поле** | Если выбрано, поле по умолчанию скрыто и может быть показано с помощью кода. | |**Параметры отображения** | **Скрыть на телефоне** | Поле может быть скрыто для отображения сжатой версии формы на экранах телефонов. | |**Форматирование** | **Ширина поля** | Если раздел, содержащий поля, содержит несколько столбцов, можно указать, чтобы поле занимало число столбцов, доступных в разделе. | ## <a name="move-fields-on-a-form"></a>Перемещение полей в форме Можно переместить поле в форме переместив или вырезав и вставив действия. ### <a name="move-fields-on-a-form-using-drag-and-drop"></a>Перемещение полей в форме с помощью перетаскивания 1. Откройте конструктор форм для создания или редактирования формы. Дополнительные сведения: [Создание формы](create-and-edit-forms.md#create-a-form) или [Редактирование формы](create-and-edit-forms.md#edit-a-form) 2. В режиме предварительного просмотра формы выберите поле, который требуется переместить, и перетащите его. При перетаскивании поля на предварительный просмотр формы отображаются цели перетаскивания, куда можно переместить поле. Обратите внимание на следующее: - Поля можно перетаскивать в положение до или после любого существующего поля или компонента. - Поля можно также перетащить в пустую область в разделе. В этом случае поле будет добавлено в доступное пространство, чтобы равномерно распределить поля и компоненты по столбцам раздела. - При наведении указателя мыши на заголовок вкладки во время перетаскивания поля изменяется текущая выбранная вкладка, позволяя добавить поле на другую вкладку. 3. Повторите шаг 2 выше, если требуется переместить несколько полей. 4. На панели команд выберите **Сохранить** для сохранения формы или выберите **Опубликовать**, если требуется сохранить изменения и сделать их видимыми пользователям. ### <a name="move-fields-on-a-form-using-cut-and-paste"></a>Перемещение полей в форме с помощью вырезания и вставки 1. Откройте конструктор форм для создания или редактирования формы. Дополнительные сведения: [Создание формы](create-and-edit-forms.md#create-a-form) или [Редактирование формы](create-and-edit-forms.md#edit-a-form) 2. В режиме предварительного просмотра формы выберите поле, которые требуется переместить. 3. В панели команд выберите **Вырезать**. 4. В режиме предварительного просмотра формы выберите другое существующее поле, компонент или раздел. Если требуется, можно также переключиться на другую вкладку. 5. В панели команд выберите **Вставить** или выберите шеврон, затем выберите **Вставить перед**. Обратите внимание на следующее: - Если вы выбираете **Вставить**, перемещаемое поле вставляется после существующего поля или компонента. - Если вы выбираете **Вставить перед**, перемещаемое поле вставляется перед существующим полем или компонентом. - При выборе раздела перемещаемое поле добавляется в доступное пространство, чтобы равномерно распределить поля и компоненты по столбцам раздела. Действие **Вставить перед** не применимо и поэтому не доступно в этом случае. 6. Повторите шаги 2–5 выше, если требуется переместить несколько полей. 7. На панели команд выберите **Сохранить** для сохранения формы или выберите **Опубликовать**, если требуется сохранить изменения и сделать их видимыми пользователям. ## <a name="delete-fields-on-a-form"></a>Удаление полей из формы 1. Откройте конструктор форм для создания или редактирования формы. Дополнительные сведения: [Создание формы](create-and-edit-forms.md#create-a-form) или [Редактирование формы](create-and-edit-forms.md#edit-a-form) 2. В режиме предварительного просмотра формы выберите поле, которое нужно удалить из формы. 3. В панели команд выберите **Удалить**. 4. Повторите шаги 2–3, если требуется удалить несколько полей. 5. На панели команд выберите **Сохранить** для сохранения формы или выберите **Опубликовать**, если требуется сохранить изменения и сделать их видимыми пользователям. > [!NOTE] > - Если поле удалено по ошибке, в панели команд выберите **Отменить** для возврата формы в предыдущее состояние. > - Невозможно удалить поле, которое заблокировано или является обязательным и не присутствует нигде в форме. ## <a name="create-a-new-field-on-the-entity-when-editing-a-form"></a>Создать новое поле для сущности при редактировании формы 1. Откройте конструктор форм для создания или редактирования формы. Дополнительные сведения: [Создание формы](create-and-edit-forms.md#create-a-form) или [Редактирование формы](create-and-edit-forms.md#edit-a-form) 2. В панели команд выберите **Добавить поле** или в левой панели выберите **Поля**. Панель **Поля** по умолчанию открывается при открытии конструктора форм. 3. На панели **Поля** выберите **+ новое поле**. 4. В диалоговом окне **Новое поле** введите **Отображаемое имя** и **Имя** для поля. 5. В диалоговом окне **Новое поле** выберите **Тип данных** и настройте любые другие необходимые свойства поля. > [!NOTE] > - Некоторые типы полей не отображаются при создании поля из конструктора формы. Если требуемый тип поля недоступен, вы можете выполнить действия, описанные в [Создание и редактирование полей для Common Data Service с использованием портала Power Apps](../common-data-service/create-edit-field-portal.md) 6. Выберите **Готово** для создания новых полей для сущности. Поле появляется на панели **Поля**. 7. Если требуется добавление вновь созданное поля к форме, выполните действия, описанные в разделе [**Добавление поля в форму**](add-move-or-delete-fields-on-form.md#add-fields-to-a-form). > [!NOTE] > Если поле для сущности создается, они не ограничено в этой форме и будет доступно для использования в других местах. ### <a name="see-also"></a>См. также [Обзор конструктора управляемых моделью форм](form-designer-overview.md) [Создание, изменение или настройка форм с помощью конструктора форм](create-and-edit-forms.md) [Добавление, настройка, перемещение или удаление компонентов в форме](add-move-configure-or-delete-components-on-form.md) [Добавление, настройка, перемещение или удаление разделов в форме](add-move-or-delete-sections-on-form.md) [Добавление, настройка, перемещение или удаление вкладок в форме](add-move-or-delete-tabs-on-form.md) [Настройка свойств верхнего колонтитула в конструкторе форм](form-designer-header-properties.md) [Добавление или настройка компонента вложенной сетки в форме](form-designer-add-configure-subgrid.md) [Добавление или настройка компонента экспресс-формы в форме](form-designer-add-configure-quickview.md) [Настройка компонента поиска в форме](form-designer-add-configure-lookup.md) [Использование представления дерева в конструкторе форм](using-tree-view-on-form.md) [Создание и изменение полей](../common-data-service/create-edit-field-portal.md)
package com.jiujia.operator.service; import java.util.List; import com.jiujia.operator.domain.ModelRelated; /** * 模板关系e_model_relatedService接口 * * @author ruoyi * @date 2022-10-12 */ public interface IModelRelatedService { /** * 查询模板关系e_model_related * * @param id 模板关系e_model_related主键 * @return 模板关系e_model_related */ public ModelRelated selectModelRelatedById(Long id); /** * 查询模板关系e_model_related列表 * * @param modelRelated 模板关系e_model_related * @return 模板关系e_model_related集合 */ public List<ModelRelated> selectModelRelatedList(ModelRelated modelRelated); /** * 新增模板关系e_model_related * * @param modelRelated 模板关系e_model_related * @return 结果 */ public int insertModelRelated(ModelRelated modelRelated); /** * 修改模板关系e_model_related * * @param modelRelated 模板关系e_model_related * @return 结果 */ public int updateModelRelated(ModelRelated modelRelated); /** * 批量删除模板关系e_model_related * * @param ids 需要删除的模板关系e_model_related主键集合 * @return 结果 */ public int deleteModelRelatedByIds(String ids); /** * 删除模板关系e_model_related信息 * * @param id 模板关系e_model_related主键 * @return 结果 */ public int deleteModelRelatedById(Long id); }
class sepaBASE { constructor(name, iban, bic) { if ( sepaBASE.validateName(name) ) { this._initName = name; } else { throw 'invalid name'; } if ( sepaBASE.validateIBAN(iban) ) { this._initIBAN = iban; } else { throw 'invalid iban'; } if ( sepaBASE.validateBIC(bic) ) { this._initBIC = bic; } else { throw 'invalid bic'; } let d = new Date(); this._execDate = d.toISOString().split('T')[0]; this._createdDateTime = d.toISOString(); this._msgId = d.toISOString(); this._batchBooking = true; this.supportedMsgTypes = []; this._tx = []; } /** * Internal helper function to calculate modulo 97 * * @param {string} i - String to calculate modulo 97 * @returns {int} - checksum as integer */ static modulo97(i) { let mappingTable = { 'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15, 'G': 16, 'H': 17, 'I': 18, 'J': 19, 'K': 20, 'L': 21, 'M': 22, 'N': 23, 'O': 24, 'P': 25, 'Q': 26, 'R': 27, 'S': 28, 'T': 29, 'U': 30, 'V': 31, 'W': 32, 'X': 33, 'Y': 34, 'Z': 35 } // swap characters to number equivalent let j = ''; i.toUpperCase().split('').forEach(value => { j += ( mappingTable.hasOwnProperty(value) ) ? mappingTable[value] : value; }) // calculate modulo 97 let pz = ''; j.match(/.{1,9}/g).forEach( value => { pz = (pz + value) % 97; }) return 98 - parseInt(pz); } /** * static function: checks if iban is valid * * @param {string} iban - IBAN to validate * @return {boolean} - true if valid, false if invalid * */ static validateIBAN(iban) { // iban may not be empty if ( iban == '' ) { return false; } iban = iban.toUpperCase(); // matches to regex for country specific patterns if (! iban.match(/^AL\d{2}\d{8}[a-zA-Z\d]{16}$|^AD\d{2}\d{8}[a-zA-Z\d]{12}$|^AT\d{2}\d{16}$|^AZ\d{2}[a-zA-Z\d]{4}\d{20}$|^BH\d{2}[A-Z]{4}[a-zA-Z\d]{14}$|^BE\d{2}\d{12}$|^BA\d{2}\d{16}$|^BR\d{2}\d{23}[A-Z]{1}[a-zA-Z\d]{1}$|^BG\d{2}[A-Z]{4}\d{6}[a-zA-Z\d]{8}$|^CR\d{2}\d{17}$|^HR\d{2}\d{17}$|^CY\d{2}\d{8}[a-zA-Z\d]{16}$|^CZ\d{2}\d{20}$|^DK\d{2}\d{14}$|^DO\d{2}[A-Z]{4}\d{20}$|^TL\d{2}\d{19}$|^EE\d{2}\d{16}$|^FO\d{2}\d{14}$|^FI\d{2}\d{14}$|^FR\d{2}\d{10}[a-zA-Z\d]{11}\d{2}$|^GE\d{2}[a-zA-Z\d]{2}\d{16}$|^DE\d{2}\d{18}$|^GI\d{2}[A-Z]{4}[a-zA-Z\d]{15}$|^GR\d{2}\d{7}[a-zA-Z\d]{16}$|^GL\d{2}\d{14}$|^GT\d{2}[a-zA-Z\d]{4}[a-zA-Z\d]{20}$|^HU\d{2}\d{24}$|^IS\d{2}\d{22}$|^IE\d{2}[a-zA-Z\d]{4}\d{14}$|^IL\d{2}\d{19}$|^IT\d{2}[A-Z]{1}\d{10}[a-zA-Z\d]{12}$|^JO\d{2}[A-Z]{4}\d{22}$|^KZ\d{2}\d{3}[a-zA-Z\d]{13}$|^XK\d{2}\d{4}\d{10}\d{2}$|^KW\d{2}[A-Z]{4}[a-zA-Z\d]{22}$|^LV\d{2}[A-Z]{4}[a-zA-Z\d]{13}$|^LB\d{2}\d{4}[a-zA-Z\d]{20}$|^LI\d{2}\d{5}[a-zA-Z\d]{12}$|^LT\d{2}\d{16}$|^LU\d{2}\d{3}[a-zA-Z\d]{13}$|^MK\d{2}\d{3}[a-zA-Z\d]{10}\d{2}$|^MT\d{2}[A-Z]{4}\d{5}[a-zA-Z\d]{18}$|^MR\d{2}\d{23}$|^MU\d{2}[A-Z]{4}\d{19}[A-Z]{3}$|^MC\d{2}\d{10}[a-zA-Z\d]{11}\d{2}$|^MD\d{2}[a-zA-Z\d]{2}[a-zA-Z\d]{18}$|^ME\d{2}\d{18}$|^NL\d{2}[A-Z]{4}\d{10}$|^NO\d{2}\d{11}$|^PK\d{2}[a-zA-Z\d]{4}\d{16}$|^PS\d{2}[a-zA-Z\d]{4}\d{21}$|^PL\d{2}\d{24}$|^PT\d{2}\d{21}$|^QA\d{2}[A-Z]{4}[a-zA-Z\d]{21}$|^RO\d{2}[A-Z]{4}[a-zA-Z\d]{16}$|^SM\d{2}[A-Z]{1}\d{10}[a-zA-Z\d]{12}$|^SA\d{2}\d{2}[a-zA-Z\d]{18}$|^RS\d{2}\d{18}$|^SK\d{2}\d{20}$|^SI\d{2}\d{15}$|^ES\d{2}\d{20}$|^SE\d{2}\d{20}$|^CH\d{2}\d{5}[a-zA-Z\d]{12}$|^TN\d{2}\d{20}$|^TR\d{2}\d{5}[a-zA-Z\d]{17}$|^AE\d{2}\d{3}\d{16}$|^GB\d{2}[A-Z]{4}\d{14}$|^VG\d{2}[a-zA-Z\d]{4}\d{16}$|^AO[\d]{2}[A-Za-z\d]{21}$|^BF[\d]{2}[A-Za-z\d]{23}$|^BI[\d]{2}[A-Za-z\d]{12}$|^BJ[\d]{2}[A-Za-z\d]{24}$|^CF[\d]{2}[A-Za-z\d]{23}$|^CG[\d]{2}[A-Za-z\d]{23}$|^CI[\d]{2}[A-Za-z\d]{24}$|^CM[\d]{2}[A-Za-z\d]{23}$|^CV[\d]{2}[A-Za-z\d]{21}$|^DZ[\d]{2}[A-Za-z\d]{20}$|^EG[\d]{2}[A-Za-z\d]{23}$|^GA[\d]{2}[A-Za-z\d]{23}$|^IR[\d]{2}[A-Za-z\d]{22}$|^MG[\d]{2}[A-Za-z\d]{23}$|^ML[\d]{2}[A-Za-z\d]{24}$|^MZ[\d]{2}[A-Za-z\d]{21}$|^SN[\d]{2}[A-Za-z\d]{24}$|^ST[\d]{2}[A-Za-z\d]{21}$/ ) ) { return false; } // especially for german IBANS: check length if ( iban.substr(0, 2) == 'DE' & iban.length != 22) { return false; } // checksum let i = iban.substr(4, iban.length - 4) + iban.substr(0, 2) + '00'; if (sepaBASE.modulo97(i) != parseInt(iban.substr(2,2))) { return false; } return true; } /** * static function: checks if iban is valid * * @param {string} bic - BIC to validate * @return {boolean} - true if valid, false if invalid * */ static validateBIC(bic) { // may not be empty if (bic == '') { return false; } // check length if ( ! ( bic.length == 8 | bic.length == 11) ) { return false; } // pattern matching bic = bic.toUpperCase(); if ( ! bic.match(/[A-Z]{6,6}[A-Z2-9][A-NP-Z0-9]([A-Z0-9]{3,3}){0,1}/) ) { return false; } return true; } /** * static function: checks if creditor id is valid * * @param {string} ci - creditor id to validate * @return {boolean} - true if valid, false if invalid * */ static validateCI(ci) { // ci may not be empty if ( ci == '' ) { return false; } // not longer than 35 chars if ( ci.length > 35) { return false; } ci = ci.toUpperCase(); // matches to regex patterns if (! ci.match(/[a-zA-Z]{2,2}[0-9]{2,2}([A-Za-z0-9]|[\+|\?|/|\|:|\(|\)|\.|,|']){3,3}([A-Za-z0-9]|[\+|\?|/|\|:|\(|\)|\.|,|']){1,28}/ ) ) { //console.log('pattern does not match'); return false; } // especially for german CI: check length if ( ci.substr(0, 2) == 'DE' && ci.length != 18) { //console.log('DE ci not 18 chars') return false; } // checksum let i = ci.substr(7, ci.length - 7) + ci.substr(0, 2) + '00'; if ( sepaBASE.modulo97(i) != parseInt(ci.substr(2,2))) { // console.log('checksum wrong'); // console.log(sepaBASE.modulo97(i)); // console.log(ci); return false; } return true; } /** * static function: checks if name string is valid and length max. 70 chars * @param {string} name - name to validate * @return {boolean} - true if valid, false if invalid */ static validateName(name) { // may not be empty if (name === '') { return false; } // check length if ( name.length > 70) { return false; } // pattern matching if ( ! name.match(/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789/?:().,'+-]+$/) ) { return false; } return true; } /** * static function: checks if id string is valid and length max. 35 chars * @param {string} id - id to validate * @return {boolean} - true if valid, false if invalid */ static validateE2EId(id) { // may not be empty if (id === '') { return false; } // check length if ( id.length > 35) { return false; } // pattern matching if ( ! id.match(/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789/?:().,'+-]+$/) ) { return false; } return true; } /** * static function: checks if purpose string is valid and length max. 140 chars * @param {string} purpose - string to validate * @return {boolean} - true if valid, false if invalid */ static validatePurpose(purpose) { // may not be empty if (purpose == '') { return false; } // check length if ( purpose.length > 140) { return false; } // pattern matching if ( ! purpose.match(/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789/?:().,'+-]+$/) ) { return false; } return true; } /** * Check if a given number is a valid amount for sepa payments * @param {number} amount - number to check * @returns {boolean} - true if valid, false if not */ static validateAmount(amount) { // not 0 if (amount === 0) { return false; } let s = amount.toString(); if ( ! s.match(/^\d+(\.\d{1,2})?$/) ) { return false; } return true; } /** * Temporary service function for generic format checking * * @param {string} name * @param {string} value * @param {number} minLength * @param {number} maxLength * @returns value */ static checkValue(name, value, minLength, maxLength) { if (value.length < minLength) { throw 'value for ' + name + ' is to short: ' + value; } if (value.length > maxLength) { throw 'value for ' + name + ' is to long: ' + value; } return value; } /** * Set message type * * @param {string} messagetype - requested message type * */ set messagetype(messagetype) { if (messagetype == '') { throw 'messagetype may not be empty'; } if (this.supportedMsgTypes.indexOf(messagetype) == -1) { throw 'unsupported messagetype: ' + messagetype; } this._messagetype = messagetype; } /** * Set batch booking attribute * * @param {boolean} batchbooking - if true: batch booking, if false: single bookings */ set batchBooking(batchbooking) { if (typeof batchbooking == 'boolean') { this._batchBooking = batchbooking; } else if (typeof batchbooking == 'number') { batchbooking == 0 ? this._batchBooking = true : this._batchBooking = false; } else if (typeof batchbooking == 'string') { batchbooking.toUpperCase == 'TRUE' ? this._batchBooking = true : this._batchBooking = false; } else { throw 'batchBooking attribute not valid'; } } /** * Set initiator's name * * @param {string} name - A string containing the initiator's name */ set initName(name) { if (! sepaBASE.validateName(name)) { throw 'initname not valid'; } else { this._initName = name; } } /** * Set initiator's IBAN * * @param {string} iban - A string containing the initiator's IBAN */ set initIBAN(iban) { if (! sepaBASE.validateIBAN(iban) ) { throw 'initiban not valid'; } else { this._initIBAN = iban; } } /** * Set initiator's BIC * * @param {string} bic - A string containing the initiator's BIC */ set initBIC(bic) { if (! sepaBASE.validateBIC(bic)) { throw 'initbic not valid'; } else { this._initBIC = bic; } } /** * Set requested execution date / due date * * @param {string} execdate - Execution date as string formatted YYYY-MM-DD */ set execDate(execdate) { try { let d = new Date(execdate); this._execDate = d.toISOString().split('T')[0]; } catch (err) { throw 'invalid execDate: ' + execdate; } } /** * Set created date/time * * @param {string} cdt - Created date/time */ set createdDateTime(cdt) { try { let d = new Date(cdt); this._createdDateTime = d.toISOString(); } catch (err) { throw 'invalid execDate: ' + cdt; } } /** * Set message id * * @param {string} msgid - message id */ set messageId(msgid) { this._msgId = msgid; } /** * Get number of transactions * * @returns {number} - total number of transactions */ get getNumberOfTx() { return this._tx.length; } /** * Get total sum of transactions * @returns {number} - total sum of transactions */ get getTotalSumOfTx() { let u = 0; if (this._tx.length == 0) return 0; this._tx.forEach(tx => { u += tx.amount; }); return u; } /** * Get md5 hash of last gernerated xml string * @returns {string} - md5 hash value in lower case */ get getMsgHash() { // return String(this._payload_md5.toLowerCase()); const crypto = require('crypto'); return crypto.createHash('md5').update(this.getMsgAsXmlString()).digest('hex').toLowerCase(); } } module.exports = sepaBASE;
import express from 'express' import bcrypt from "bcryptjs" import prisma from "../utils/prisma.js" import { filter } from "../utils/common.js" import { Prisma } from "@prisma/client" import { validateUser } from "../validators/users.js" const router = express.Router() router.get('/', async(req, res) => { const allUsers = await prisma.user.findMany() res.json(allUsers) }) router.post('/', async (req, res) => { const data = req.body const validationErrors = validateUser(data) if(Object.keys(validationErrors).length != 0) return res.status(400).send({ error: validationErrors }) data.password = bcrypt.hashSync(data.password, 8); prisma.user.create({ data }).then(user => { return res.json(filter(user, 'id', 'name', 'email')) }).catch(err => { // we have unique index on user's email field in our schema, Postgres throws an error when we try to create 2 users with the same email. Here's how w catch the error and gracefully return a friendly message to the user. if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2002') { const formattedError = {} formattedError[`${err.meta.target[0]}`] = 'already taken' return res.status(500).send({ error: formattedError }); // friendly error handling } throw err // if this happens, our backend application will crash and not respond to the client. because we don't recognize this error yet, we don't know how to handle it in a friendly manner. we intentionally throw an error so that the error monitoring service we'll use in production will notice this error and notify us and we can then add error handling to take care of previously unforeseen errors. }) }) export default router
import React from "react"; import Product from "../Data/Productlist.json"; import { motion } from "framer-motion"; const ProductCard = ({ limit1, limit2 }) => { return ( <div className=" grid grid-cols-4 grid-flow-row gap-5 max-lg:grid-cols-3 max-vmd:grid-cols-2 "> {Product.slice(limit1, limit2).map((Product) => ( <motion.div key={Product.id} initial="hidden" whileInView="visible" viewport={{ once: true }} transition={{ duration: 1, ease: "easeInOut" }} variants={{ hidden: { opacity: 0, y: 40 }, visible: { opacity: 1, y: 0, }, }} className="flex flex-col gap-5 col-span-1" > <div className=" bg-transparent box-border object-contain object-center block hover:scale-105 duration-500 ease-in-out cursor-pointer"> <img src={Product.image} alt={Product.name} className=" w-full h-full rounded-3xl " /> </div> <div> <div className="flex justify-between"> <h2> <span className=" font-Inter font-semibold text-[18px] text-secondary"> {Product.name} </span> </h2> <p> <span className=" font-Inter font-semibold text-[16px] text-tertiary"> {Product.price} </span> </p> </div> <span className=" font-Inter font-semibold text-[12px] text-greyishblue"> {Product.tag} </span> </div> </motion.div> ))} </div> ); }; export default ProductCard;
import { createSlice } from '@reduxjs/toolkit'; import sum from 'lodash/sum'; import uniqBy from 'lodash/uniqBy'; import Cookies from 'universal-cookie'; import { dispatch } from '../store'; import { get_product_list_service } from '../../../services/ecom_product.service'; import { setAuth } from 'services/identity.service'; // ---------------------------------------------------------------------- const initialState = { isLoading: false, error: null, product_list: [], }; const slice = createSlice({ name: 'ecom_product', initialState, reducers: { // START LOADING startLoading(state) { state.isLoading = true; }, // HAS ERROR hasError(state, action) { state.isLoading = false; state.error = action.payload; }, // for Listing Product Data setListData(state, action) { state.isLoading = false; state.product_list = action.payload; }, }, }); // Reducer export default slice.reducer; // Actions export const { setListData } = slice.actions; // // ---------------------------------------------------------------------- export function get_product_list_slice(size, page, search) { return async () => { dispatch(slice.actions.startLoading()); try { const response = await get_product_list_service(size, page, search); console.log(response.data.data.data, 'response.data.data'); dispatch(slice.actions.setListData(response.data.data.data)); return response.data.data; } catch (error) { dispatch(slice.actions.hasError(error)); } }; }
/* eslint-disable @typescript-eslint/no-explicit-any */ import { Memoize } from 'typescript-memoize'; import type { Metadata } from '../metadata'; import { DateField } from '../metadata-fields/field-types/date'; import { StringField } from '../metadata-fields/field-types/string'; /** * A model that describes an item hit from a Metadata Search via the PPS endpoint. * * The fields in here are cast to their respective field types. See `metadata-fields/field-type`. * * Add additional fields as needed. * * @export * @class FavoritedSearchHit */ export class FavoritedSearchHit { /** * This is the raw hit response; useful for inspecting the raw data * returned from the server. */ rawMetadata?: Record<string, any>; constructor(json: Record<string, any>) { this.rawMetadata = json; } /** * The item identifier. * * _Note_: This is a plain string instead of a `MetadataField` since it's * the primary key of the item. */ get identifier(): typeof Metadata.prototype.identifier { return this.rawMetadata?.fields.query; } /** Optional. */ @Memoize() get title(): StringField | undefined { return this.rawMetadata?.fields?.title ? new StringField(this.rawMetadata.fields.title) : undefined; } /** Optional. */ @Memoize() get query(): typeof Metadata.prototype.query { return this.rawMetadata?.fields?.query ? new StringField(this.rawMetadata.fields.query) : undefined; } /** * Optional. */ @Memoize() get date_favorited(): typeof Metadata.prototype.date_favorited { return this.rawMetadata?.fields?.date_favorited ? new DateField(this.rawMetadata.fields.date_favorited) : undefined; } /** * Optional. */ @Memoize() get __href__(): typeof Metadata.prototype.__href__ { return this.rawMetadata?.fields?.__href__ ? new StringField(this.rawMetadata.fields.__href__) : undefined; } }
import { useQuery } from "@tanstack/react-query"; import useAxiosIns from "../../hooks/useAxiosIns"; import { Classwork, IResponseData } from "../../types"; import useAuthStore from "../../stores/auth"; import { Tabs, Tab, Spinner } from "@nextui-org/react"; import DoneTab from "./DoneTab"; import AssignTab from "./AssignTab"; import { useSearchParams } from "react-router-dom"; import { useState, useEffect } from "react"; import useClassroomStore from "../../stores/classroom"; export default function TodoPage() { const axios = useAxiosIns(); const { user } = useAuthStore(); const getTodoClasswork = useQuery({ queryKey: ["fetch/classwork/todo", user?.id], queryFn: () => axios.get<IResponseData<Classwork[]>>(`/api/v1/classwork/todo`), refetchOnWindowFocus: false, }); const getDoneClasswork = useQuery({ queryKey: ["fetch/classwork/done", user?.id], queryFn: () => axios.get<IResponseData<Classwork[]>>(`/api/v1/classwork/done`), refetchOnWindowFocus: false, }); const { registeredClassrooms } = useClassroomStore(); const [searchParams, setSearchParams] = useSearchParams(); const [tab, setTab] = useState("assign"); useEffect(() => { const tab = searchParams.get("tab") ?? "assign"; setTab(tab); }, [searchParams]); const todoClassworks = getTodoClasswork.data?.data?.data || []; const doneClassworks = getDoneClasswork.data?.data?.data || []; return ( <div> {getTodoClasswork.isLoading ? ( <div className="w-full h-24 flex items-center justify-center"> <Spinner /> </div> ) : ( <> <Tabs selectedKey={tab} onSelectionChange={(key) => { if (key == "assign") { searchParams.delete("tab"); } else { searchParams.set("tab", key.toString()); } setSearchParams(searchParams); }} color="primary" variant="underlined" className="w-full" classNames={{ tabList: "w-full relative rounded-none p-0 border-b border-divider h-12", tab: "w-auto px-8 h-full font-semibold text-sm", }} > <Tab key="assign" title={ <div className="flex items-center space-x-2"> <span>Assigned</span> </div> } > <AssignTab registeredClassrooms={registeredClassrooms} classworks={todoClassworks} /> </Tab> <Tab key="done" title={ <div className="flex items-center space-x-2"> <span>Done</span> </div> } > <DoneTab registeredClassrooms={registeredClassrooms} classworks={doneClassworks} /> </Tab> </Tabs> </> )} </div> ); }
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'calculateDate' }) export class CalculateDatePipe implements PipeTransform { transform(value: Date): string { const dateParam = new Date(value); const today = new Date(); const emptyDate = new Date('0001-01-01').setHours(0,0,0); if(new Date(value).getTime() < new Date(1/1/2020).getTime()){ return "Unplanned!"; } else if (dateParam < today) { const difference = Math.abs(today.getTime() - dateParam.getTime()); const days = Math.floor(difference / (1000 * 3600 * 24)); return `${days} days passed.`; } else if (dateParam > today) { const difference = Math.abs(dateParam.getTime() - today.getTime()); const days = Math.floor(difference / (1000 * 3600 * 24)); return `${days} days remaining.`; } else { return "Today!"; } } }
import config from flask import (request, render_template, session, Blueprint, jsonify, g) from models import User from util import * # The authentication API controls login, logout, and accessing of the session # state from the client. authenticate_api = Blueprint('authenticate_api', __name__) @authenticate_api.route('/login', methods=['POST']) def login(): # Get the specified email and password, if they were sent. if 'email' not in request.json or 'password' not in request.json: return bad_request email = request.json['email'] password = request.json['password'] # Find out if there is a user with the requested email. user = User.query.filter_by(email=email).first() if not user: return not_authorized # There is, so compare credentials. hashed_password = password_hash(password, user.salt, config.hash_key) if user.password != hashed_password: return not_authorized else: session['user_id'] = user.id return jsonify({ 'name' : user.name, 'email' : user.email, 'id' : user.id }) @authenticate_api.route('/logout', methods=['POST']) def logout(): # Remove the current user from the session. if 'user_id' in session: session.pop('user_id', None) return empty_response else: return not_authorized @authenticate_api.route('/user') def user(): # Get information about the current user. if 'user_id' in session: user_id = session['user_id'] user = User.query.filter_by(id=user_id).first() return jsonify({ 'name' : user.name, 'email' : user.email, 'id' : user.id }) else: return not_authorized
# Bayesian Flow Networks This repo is a simple replication of the discrete and discretised implementations of Bayesian flow networks (BFNs). ## CIFAR 10 Sampling Data Expectation Distribution (Output distribution) <img src="gifs/seed_113_data_expectation.gif" alt="CIFAR 10 data expectation over sampling" style="width:600px;"/> Updated Prior (Input distribution) <img src="gifs/seed_113_updated_prior.gif" alt="CIFAR 10 updated prior over sampling" style="width:600px;"/> ## Discretised Examples ### Distributions over time <img src="gifs/figure_8_discretised.gif" alt="Different distributions over time during training example" style="width:600px;"/> ### Updated Prior & Data Expectation Trajectories and Probability Flow <img src="gifs/updated_prior_trajectories.gif" alt="Discretised 5 bin example, probability flow and example trajectories over time for updated prior." style="width:600px;"/> <img src="gifs/data_expectation_trajectories.gif" alt="Discretised 5 bin example, probability flow and example trajectories over time for data expectation." style="width:600px;"/> ## Discrete Examples ### Simplex with 3 Classes, Trajectories over time and Probablity Flow <img src="gifs/simplex.gif" alt="Bayesian Flow for discrete data visualized on a probability simplex for K=3 classes. White line is the sample trajectory for class 0, which is superimposed on log-scale heatmap of flow distribution over time." style="width:600px;"/> ### Sampling with different steps ![sampling_bfn](https://github.com/rupertmenneer/bayesian_flow/assets/71332436/925f03f8-9584-4e7c-a33b-228569523498) ### Un-conditional inpainting (using something similar to repaint r=20) ![inpainting_bfn](https://github.com/rupertmenneer/bayesian_flow/assets/71332436/ce91efd2-3ab8-4964-8540-19a6f9f8e8f7) ### Toy examples (discretised) with 5 bins ![sample plots](https://github.com/rupertmenneer/bayesian_flow/assets/71332436/823f4924-56ad-451a-b4c1-2fae1f290906) # How does BFN work? We create a 'flow' that uses bayesian updates to transform from a prior to a data sample ![Bayesian update frame](https://github.com/rupertmenneer/bayesian_flow/assets/71332436/59609d53-7ee3-44dc-b730-a25be77cf310) During training we learn the flow, from our prior using noisy samples from our data ![Training frame](https://github.com/rupertmenneer/bayesian_flow/assets/71332436/1e4ed9a0-6071-4f86-9f59-a1e711474382) At sampling time we simply swap out our sender distribution with our receiver distribution ![Sampling frame](https://github.com/rupertmenneer/bayesian_flow/assets/71332436/13959781-1106-4cf1-8c86-2127788c522c) ### This Repo - Replicates BFN with simple toy examples for discrete and discretised datasets. - Train a discretised model on the CIFAR-10 dataset (see results above). - Provides some math breakdown in the_math.md The original paper can be found here: https://arxiv.org/pdf/2308.07037.pdf The official code implementation here: https://github.com/nnaisense/bayesian-flow-networks This repo was part of a paper replication project at the University of Cambridge 2024.
import path from "path"; import { createLogger, transports, format } from "winston"; import "winston-daily-rotate-file"; const consoleLogFormat = format.combine( format.label({ label: path.basename(require.main?.filename || "") }), format.timestamp({ format: "MMM-DD-YYYY HH:mm:ss" }), format.printf((i) => `${[i.timestamp]} -> [${i.level}]: ${i.message}`) ); const fileLogFormat = format.combine(format.json(), format.timestamp()); const logger = createLogger({ transports: [ // console logger new transports.Console(), // file logger with rotation new transports.DailyRotateFile({ filename: "logs/app-%DATE%.log", level: "info", format: fileLogFormat, datePattern: "YYYY-MM-DD", zippedArchive: true, maxSize: "60m", maxFiles: "14d", }), ], format: consoleLogFormat, }); export default logger;
import express from "express"; import mongoose from "mongoose"; import router from "./router.js"; import fileUpload from "express-fileupload"; const mongo_URL = "mongodb+srv://admin:[email protected]/?retryWrites=true&w=majority"; const PORT = 3000; const app = express(); app.use(express.json()); app.use(express.static('static')); app.use(fileUpload({})); app.use("/api", router ); mongoose.set("strictQuery", false); async function startApp() { try { await mongoose.connect(mongo_URL, { useUnifiedTopology: true, useNewUrlParser: true, }); app.listen(PORT, () => console.log(`server listening on port ${PORT}`)); } catch (error) { console.log(error); } } startApp();
/* * This program illustrate the java 8 features for training purpose * Copyright (c) 2019. Ravi Bhushan ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.drclb.collection.map; import com.drclb.common.Person; import com.drclb.common.PersonBuilder; import java.util.List; import java.util.Map; import java.util.function.BiFunction; import java.util.stream.Collectors; /** * This class demonstrate the, {@link Map#compute(Object, BiFunction)} * <p> * Compute is used to modify the value in a lazy manner. Compute method gets the value using the provided key and * apply BiFunctional interface on it */ public class ComputeExample { public static void main(String[] args) { Map<String, List<Person>> persons = PersonBuilder.getDummyPersonList().stream() .collect(Collectors.groupingBy(Person::getLoc)); System.out.println("Before Compute...."); System.out.println(persons); // BiFunction - persons.compute("USA", (existingKey, existingValue) -> existingValue.stream() .map(sr -> sr.setLoc(sr.getLoc().toLowerCase())).collect(Collectors.toList())); System.out.println("After Compute......"); System.out.println(persons); } }
import fs from 'fs-extra'; import path from 'path'; import config from '@/config'; const URL_TEMPLATE = `<url> <loc>%loc%</loc> <lastmod>%lastmod%</lastmod> <changefreq>%changefreq%</changefreq> <priority>%priority%</priority> </url> `; const CHANGE_FREQ = { hourly: 0.8, daily: 0.6, weekly: 0.4, monthly: 0.2, yearly: 0.1, never: 0, }; function getChangeFreq(createdTimeMs: number, lastModifiedTimeMs: number) { const diff = lastModifiedTimeMs - createdTimeMs; if (diff === 0) { return 'never'; } if (diff < 1000 * 60 * 60 * 24) { return 'hourly'; } if (diff < 1000 * 60 * 60 * 24 * 7) { return 'daily'; } if (diff < 1000 * 60 * 60 * 24 * 30) { return 'weekly'; } if (diff < 1000 * 60 * 60 * 24 * 365) { return 'monthly'; } return 'yearly'; } function generateUrlData(file: string, slug: string, type: string) { const stats = fs.statSync(file); return { type, slug, lastModified: stats.mtime, changeFreq: getChangeFreq(stats.birthtimeMs, stats.mtimeMs), priority: CHANGE_FREQ[getChangeFreq(stats.birthtimeMs, stats.mtimeMs)], }; } async function getAllAuthors() { const dir = path.resolve(__dirname, '..', '_content', 'authors'); const files = await fs.readdir(dir); return files.map((file) => generateUrlData(path.join(dir, file), path.basename(file, '.json'), 'author')); } async function getAllTags() { const dir = path.resolve(__dirname, '..', '_content', 'tags'); const files = await fs.readdir(dir); return files.map((file) => generateUrlData(path.join(dir, file), path.basename(file, '.json'), 'tag')); } async function getAllPosts() { const dir = path.resolve(__dirname, '..', '_content', 'posts'); const folders = await fs.readdir(dir); return folders.map((folder) => generateUrlData(path.join(dir, folder, 'index.mdx'), folder, 'blog')); } async function getAllStaticPages() { const dir = path.resolve(__dirname, '..', '_content', 'pages'); const folders = await fs.readdir(dir); return folders.map((folder) => generateUrlData(path.join(dir, folder, 'index.mdx'), folder, 'page')); } async function main() { console.log('Generating sitemap.xml...'); await fs.ensureDir(path.resolve(__dirname, '..', 'public')); const resources = [ ...(await getAllPosts()), ...(await getAllAuthors()), ...(await getAllTags()), ...(await getAllStaticPages()), ]; console.log(`Found ${resources.length} resources.`); let sitemap = ''; sitemap += '<?xml version="1.0" encoding="UTF-8"?>'; sitemap += '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'; for (const resource of resources) { let finalUrl = URL_TEMPLATE; finalUrl = finalUrl.replace('%lastmod%', resource.lastModified.toISOString()); finalUrl = finalUrl.replace('%changefreq%', resource.changeFreq); finalUrl = finalUrl.replace('%priority%', resource.priority.toString()); if (resource.type === 'page') { finalUrl = finalUrl.replace('%loc%', `${config.site.url}/${resource.slug}`); } else { finalUrl = finalUrl.replace('%loc%', `${config.site.url}/${resource.type}/${resource.slug}`); } sitemap += finalUrl; } sitemap += '</urlset>'; console.log('Writing sitemap.xml...'); await fs.writeFile(path.resolve(__dirname, '..', 'public', 'sitemap.xml'), sitemap); console.log('Done!'); } main();
class Maiz { var property posicion var property estado = 0 const property estados = [ "corn_baby.png", "corn_adult.png" ] var property imagen = estados.first() const property precio = 150 method teSembraron(alguien) { imagen = estados.first() posicion = alguien.posicion().clone() } method teRegaron() { estado = if (estado >= estados.size() - 1) estado else +1 imagen = estados.get(estado) } method teCosecharon() { game.removeVisual(self) } } class Trigo { var property posicion var property estado = 0 var property precio var property imagen method teSembraron(alguien) { imagen = "wheat_" + estado.toString() + ".png" posicion = alguien.posicion().clone() } method teRegaron() { estado = (estado + 1) % 4 imagen = "wheat_" + estado.toString() + ".png" precio = (estado - 1) * 100 } method teCosecharon() { if (estado > 1) { game.removeVisual(self) } } } class Tomaco { var property posicion const property imagen = "tomaco.png" const property precio = 80 method teSembraron(alguien) { posicion = alguien.posicion().clone() } method teRegaron() { if (posicion.y() < 9) { posicion = posicion.up(1) } else { posicion = posicion.down(9) } } method teCosecharon() { game.removeVisual(self) } }
import {Component, Input, OnInit} from '@angular/core'; import {Answer, AnswerVote} from '../../../../../models/questions.models'; import {QuestionsFacade} from '../../../../../states/questions/questions.facade'; import {AuthFacade} from '../../../../../states/auth/auth.facade'; import {VotersListComponent} from '../../../../dialogs/voters-list/voters-list.component'; import {MatDialog} from '@angular/material'; @Component({ selector: 'app-answer-card', templateUrl: './answer-card.component.html', styleUrls: ['./answer-card.component.scss'] }) export class AnswerCardComponent implements OnInit { @Input('answer') answer: Answer; @Input('questionAuthorId') questionAuthorId: number; public userVote: 'U' | 'D' = null; public isQuestionAuthor: boolean = false; public isVoting: boolean = false; public votes: { upVotes: AnswerVote[]; downVotes: AnswerVote[]; }; constructor( private questionsFacade: QuestionsFacade, private authFacade: AuthFacade, public dialog: MatDialog ) { } ngOnInit() { this.questionsFacade.isVoting$.subscribe(isVoting => { this.isVoting = isVoting; }); this.authFacade.userID$.subscribe(userID => { this.isQuestionAuthor = userID === this.questionAuthorId; this.answer.answerVotes.forEach(answerVote => { if (answerVote.voterId === userID) { this.userVote = answerVote.voteType; } }); }); this.questionsFacade.answerVotes$(this.answer.id).subscribe(votes => { this.votes = votes; }); } onVoteClick(voteType: 'U' | 'D') { if(!this.isVoting){ this.questionsFacade._addAnswerVote({ questionAnswerId: this.answer.id, voteType: voteType }); } } onCountClick() { this.dialog.open(VotersListComponent, { data: this.votes, height: '400px', width: '600px' }); } onSelectAnswerClick() { this.questionsFacade._selectAnswer({ questionId: this.answer.questionId, answerId: this.answer.id }); } }
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Venta extends Model { use HasFactory; protected $table = 'ventas'; protected $fillable = [ 'nro_venta', 'cliente_id', 'tipo_pago_id', 'user_id', 'fecha', 'total', 'completado', ]; public function Cliente(){ return $this->belongsTo(Cliente::class); } public function TipoPago(){ return $this->belongsTo(TipoPago::class); } public function User(){ return $this->belongsTo(User::class); } public function __toString() { return $this->nro_venta; } }
## 快速上手 ### 安装 #### 切换到所托内部镜像源,安装该组件 > 安装该组件库 `npm / pnpm` 都行; 推荐 pnpm ```shell pnpm add @soterea-f2e/so-ui ``` #### 推荐使用`nrm`管理镜像源 > 安装 nrm ```shell npm i -g nrm ``` > nrm 查看镜像源(检测 nrm 是否安装成功) ```shell nrm ls ``` > nrm 新增一个自定义(如:soterea)的镜像源 ```shell nrm add soterea http://nexus.soterea.cn/repository/soterea-npm/ ``` > nrm 切换镜像源 ```shell nrm use soterea ``` ### 使用 (下面是组件vue3 jsx 语法中 使用的主要代码片段 其他省略...) > 按需加载 ```jsx import { Button as SoButton } from '@soterea-f2e/so-ui' import '@soterea-f2e/so-ui/es/button/style' export default defineComponent({ components: { SoButton }, setup (props, ctx){ return () => { return ( <SoButton>按钮</SoButton> ) } } }) ``` > 全量加载 ```jsx # main.js 中引入并注册 import SoUI from '@soterea-f2e/so-ui' import '@soterea-f2e/so-ui/es/style' createApp(App).use(SoUI) # 页面中使用: <SoButton></SoButton> <EButton></EButton> .... ```
#include<iostream> #include<map> using namespace std; class Node{ public: int data; Node* prev; Node* next; // constructor Node(int d){ this->data = d; this->prev = NULL; this->next = NULL; } // destructor ~Node(){ int value = this->data; // memory free if(next!=NULL){ delete next; next = NULL; } cout<<"Memory Free: "<<value<<endl; } }; // Traversing a linked list void print(Node* &head){ Node* temp = head; while(temp!=NULL){ cout<<temp->data<<" "; temp = temp->next; } cout<<endl; } // gives length of linked list int getlength(Node* head){ int len = 0; Node* temp = head; while(temp!=NULL){ len++; temp = temp->next; } return len; } void insertAtHead(Node* &tail,Node* &head,int d){ // empty list if(head==NULL){ Node* temp = new Node(d); head = temp; tail = temp; } else{ Node* temp = new Node(d); temp->next = head; head->prev = temp; head = temp; } } void insertAtTail(Node* &tail,Node* &head,int d){ // empty list if(tail==NULL){ Node* temp = new Node(d); tail = temp; head = temp; } else{ Node* temp = new Node(d); tail->next = temp; temp->prev = tail; tail = temp; } } void insertAtPosition(Node* &tail,Node* &head,int position,int d){ // insert at start if(position==1){ insertAtHead(tail,head,d); return ; } Node* temp = head; int cnt = 1; while(cnt<position-1){ temp = temp->next; cnt++; } // inserting at last position if(temp->next==NULL){ insertAtTail(tail,head,d); return; } // creating a node for d Node* nodeToInsert = new Node(d); nodeToInsert->next = temp->next; temp->next->prev = nodeToInsert; temp->next = nodeToInsert; nodeToInsert->prev = temp; } void deleteNode(int position,Node* &head){ // deleting first or start node if(position==1){ Node* temp = head; temp->next->prev = NULL; head = temp->next; temp->next = NULL; delete temp; } else{ // deleting any middle node or last node Node* curr = head; Node* prev = NULL; int cnt = 1; while(cnt<position){ prev = curr; curr = curr->next; cnt++; } prev->next = curr->next; curr->next = NULL; delete curr; } } int main(){ Node* head = NULL; Node* tail = NULL; print(head); cout<<"Length: "<<getlength(head)<<endl; insertAtHead(tail,head,11); print(head); cout<<"Head: "<<head->data<<endl; cout<<"Tail: "<<tail->data<<endl; insertAtHead(tail,head,13); print(head); cout<<"Head: "<<head->data<<endl; cout<<"Tail: "<<tail->data<<endl; insertAtHead(tail,head,8); print(head); cout<<"Head: "<<head->data<<endl; cout<<"Tail: "<<tail->data<<endl; insertAtTail(tail,head,25); print(head); cout<<"Head: "<<head->data<<endl; cout<<"Tail: "<<tail->data<<endl; insertAtPosition(tail,head,2,100); print(head); cout<<"Head: "<<head->data<<endl; cout<<"Tail: "<<tail->data<<endl; insertAtPosition(tail,head,1,101); print(head); cout<<"Head: "<<head->data<<endl; cout<<"Tail: "<<tail->data<<endl; insertAtPosition(tail,head,7,102); print(head); cout<<"Head: "<<head->data<<endl; cout<<"Tail: "<<tail->data<<endl; deleteNode(7,head); print(head); cout<<"Head: "<<head->data<<endl; cout<<"Tail: "<<tail->data<<endl; return 0; } // Length: 0 // 11 // Head: 11 // Tail: 11 // 13 11 // Head: 13 // Tail: 11 // 8 13 11 // Head: 8 // Tail: 11 // 8 13 11 25 // Head: 8 // Tail: 25 // 8 100 13 11 25 // Head: 8 // Tail: 25 // 101 8 100 13 11 25 // Head: 101 // Tail: 25 // 101 8 100 13 11 25 102 // Head: 101 // Tail: 102 // Memory Free: 102 // 101 8 100 13 11 25 // Head: 101 // Tail: 102
import { Dialog, DialogRef } from '@angular/cdk/dialog'; import { ChangeDetectorRef, Component, Injector, Renderer2 } from '@angular/core'; import { FormBuilder, Validators } from '@angular/forms'; import { WalletService } from 'src/app/services/wallet.service'; import { MatSnackBar } from '@angular/material/snack-bar'; import { LockConfirmDialog } from '../confirm-lock/confirm-lock.component'; import { MatDialog } from '@angular/material/dialog'; import { ConfirmDialog } from 'src/app/core/confirm-dialog/confirm-dialog.component'; import { TranslocoService } from '@ngneat/transloco'; import { ThemeService } from 'src/app/services/theme.service'; import { QubicDialogWrapper } from 'src/app/core/dialog-wrapper/dialog-wrapper'; @Component({ selector: 'qli-unlock', templateUrl: './unlock.component.html', styleUrls: ['./unlock.component.scss'] }) export class UnLockComponent extends QubicDialogWrapper { public file: File | null = null; public newUser = false; importForm = this.fb.group({ password: [null, [Validators.required, Validators.minLength(8)]], }); dialogRef: DialogRef | null = null; constructor(renderer: Renderer2, themeService: ThemeService, public walletService: WalletService, private transloco: TranslocoService, private cdr: ChangeDetectorRef, private fb: FormBuilder, private dialog: MatDialog, private _snackBar: MatSnackBar, private injector: Injector) { super(renderer, themeService); this.dialogRef = injector.get(DialogRef, null) this.newUser = this.walletService.getSeeds().length <= 0 && !this.walletService.publicKey; } isNewUser() { return this.newUser; } toggleNewUser(v:boolean) { this.newUser = v; this.cdr.detectChanges(); } startCreateProcess() { this.walletService.clearConfig(); this.walletService.createNewKeys(); const lockRef = this.dialog.open(LockConfirmDialog, { restoreFocus: false, data: { command: "keyDownload" } }); // Manually restore focus to the menu trigger since the element that // opens the dialog won't be in the DOM any more when the dialog closes. lockRef.afterClosed().subscribe(() => { // do anything :) this.dialogRef?.close(); }); } gengerateNew() { if(this.walletService.getSeeds().length > 0 || this.walletService.publicKey){ const confirmDialo = this.dialog.open(ConfirmDialog, { restoreFocus: false, data: { message: this.transloco.translate("unlockComponent.overwriteVault") } }); confirmDialo.afterClosed().subscribe(result => { if (result) { this.startCreateProcess(); } }) }else{ this.startCreateProcess(); } } lock() { const dialogRef = this.dialog.open(LockConfirmDialog, { restoreFocus: false }); // Manually restore focus to the menu trigger since the element that // opens the dialog won't be in the DOM any more when the dialog closes. dialogRef.afterClosed().subscribe(() => { // do anything :) }); } unlock() { if (this.importForm.valid && this.importForm.controls.password.value && this.file) { this.file.arrayBuffer().then(b => { this.walletService.unlock(b, (<any>this.importForm.controls.password.value)).then(r => { if (r) { this.dialogRef?.close(); } else { this._snackBar.open("Import Failed", "close", { duration: 5000, panelClass: "error" }); } }); }).catch(r => { this._snackBar.open("Import Failed (passord or file do not match)", "close", { duration: 5000, panelClass: "error" }); }); } else { this.importForm.markAsTouched(); this.importForm.controls.password.markAllAsTouched(); } } onSubmit(event: any): void { event.stopPropagation(); event.preventDefault(); this.unlock(); } onFileSelected(event: any): void { this.file = event?.target.files[0]; } }
# Powershell profile for efficiency gains 💪 A PowerShell profile is a script that runs when PowerShell starts. You can use the profile as a startup script to customize your environment. You can add commands, aliases, functions, variables, modules, PowerShell drives and more. You can also add other session-specific elements to your profile so they're available in every session without having to import or re-create them. PowerShell supports several profiles for users and host programs. However, it doesn't create the profiles for you. ### RTFM: [Link to Microsoft Doc - about_profiles](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_profiles?view=powershell-7.4&viewFallbackFrom=powershell-7.1) ## Profile types and locations PowerShell supports several profile files that are scoped to users and PowerShell hosts. You can have any or all these profiles on your computer. For example, the PowerShell console supports the following basic profile files. The profiles are listed in order that they're executed. All Users, All Hosts Windows - $PSHOME\Profile.ps1 Linux - /opt/microsoft/powershell/7/profile.ps1 macOS - /usr/local/microsoft/powershell/7/profile.ps1 All Users, Current Host Windows - $PSHOME\Microsoft.PowerShell_profile.ps1 Linux - /opt/microsoft/powershell/7/Microsoft.PowerShell_profile.ps1 macOS - /usr/local/microsoft/powershell/7/Microsoft.PowerShell_profile.ps1 Current User, All Hosts Windows - $HOME\Documents\PowerShell\Profile.ps1 Linux - ~/.config/powershell/profile.ps1 macOS - ~/.config/powershell/profile.ps1 Current user, Current Host Windows - $HOME\Documents\PowerShell\Microsoft.PowerShell_profile.ps1 Linux - ~/.config/powershell/Microsoft.PowerShell_profile.ps1 macOS - ~/.config/powershell/Microsoft.PowerShell_profile.ps1 The profile scripts are executed in the order listed. This means that changes made in the AllUsersAllHosts profile can be overridden by any of the other profile scripts. The CurrentUserCurrentHost profile always runs last. In PowerShell Help, the CurrentUserCurrentHost profile is the profile most often referred to as your PowerShell profile. Other programs that host PowerShell can support their own profiles. For example, Visual Studio Code (VS Code) supports the following host-specific profiles. All users, Current Host - $PSHOME\Microsoft.VSCode_profile.ps1 Current user, Current Host - $HOME\Documents\PowerShell\Microsoft.VSCode_profile.ps1 The profile paths include the following variables: The $PSHOME variable stores the installation directory for PowerShell The $HOME variable stores the current user's home directory ## Check if you have a Profile ```powershell $PROFILE | Get-Member -Type NoteProperty ``` If the response has values for all four values, especially CurrentUserCurrentHost, you have a profile. If not you can create one by using the following command: ```powershell if (!(Test-Path -Path $PROFILE)) { New-Item -ItemType File -Path $PROFILE -Force } ``` You should now have a profile for the current user in the current PowerShell host application. ## How to edit a profile You can open PowerShell profile in any text editor. ```powershell notepad $PROFILE ## or vscode code $PROFILE ``` To open other profiles, specify the profile name. For example, to open the profile for all the users of all the host applications, type: ```PowerShell code $PROFILE.AllUsersAllHosts ``` To apply the changes, save the changes, and restart PowerShell or reload the script ```powershell . $PROFILE ``` ## Link the profile to github file in different location to default path [Create symlink in windows](https://woshub.com/create-symlink-windows/) ```powershell New-Item -ItemType SymbolicLink -Path "$HOME\Documents\PowerShell\Microsoft.PowerShell_profile.ps1" -Target "$HOME\Documents\GitHub\YourRepo\Microsoft.PowerShell_profile.ps1" ``` [Create symlink in macOS and Linux](https://www.howtogeek.com/297721/how-to-create-and-use-symbolic-links-aka-symlinks-on-a-mac/) ```bash ln -s "~/.config/powershell/Microsoft.PowerShell_profile.ps1" "~/Documents/GitHub/YourRepo/profile.ps1" ```
# 生成问题简介 对于生成问题来说, 一般有两种生成策略: "各个击破" 和 "一步到位"。 "各个击破" 的含义是一个元素一个元素生成。对于文本生成来说, 就是一个 token 一个 token 生成, 每一个 token 是基于在此之前的所有 token 生成的。对于图像生成来说, 就是一个 pixel 一个 pixel 生成。这样的模型被称为 **自回归模型** (autoregressive model)。 "一步到位" 的含义是所有的元素一次性生成。对于文本生成来说, 就是一次性生成所有的 token。对于图像生成来说, 就是所有的 pixel 一起生成。这样的模型被称为 **非自回归模型** (non-autogressive model)。 生成问题有什么特点呢? 那就是很多时候你往左走可以, 往右走也可以, 但是 不左不右 就会出问题。什么意思呢? 举例来说, "李宏毅" 是一个常见的中文名, 在网上比较火的有两个人, 一个是演员, 一个是台大的教授。如果是一个问答模型, 你问: "李宏毅是谁?", 那么模型输出 "李宏毅是演员" 或者 "李宏毅是教授" 都是可以的, 但是如果输出 "李宏毅是演授" 就会让人觉得莫名其妙。 现在的模型都是基于 概率论 的。对于自回归模型而言, 预测 "李宏毅是" 下一个 token 时, "演" 和 "教" 的概率都很高, 我们可以随机选择一个, 比方说 "演"。那么在预测 "演" 的下一个 token 时, 只有 "员" 的概率会很高, "授" 的概率很低, 此时只会选择 "员", 而不会选择 "授"。 但是对于非自回归模型, 预测的结果很可能时在第五个 token 的位置, "演" 和 "教" 的概率都很高; 在第六个 token 的位置, "员" 和 "授" 的概率也都很高。那么此时输出的内容不一定是 "演员" 或者 "教授", 也有可能是 "演授" 这样的词语。从而产生很大的问题。 一直以来, 我对语言模型是有疑问的。文本真的符合序列模型吗? 从这个角度来解释, 似乎也挺合理的。 对于图像生成来说, 也有类似的问题。有时候生成的图片是多张图叠加的结果, 此时表现就是图片很模糊, 或者产生分裂的情况。可以参考 [Adversarial_Video_Generation](https://github.com/dyelax/Adversarial_Video_Generation) 中的例子。 那么自回归模型有什么问题呢? 答案是慢, 巨慢无比。和 CRF 一样, 没有办法并行化计算, 只能一步一步地生成。对于文字生成, 还能够接受, 对于图片生成, 像素点过多, 很难接受。 因此, 文字生成一般是 自回归模型, 图片生成一般是 非自回归模型。而对于语音生成来说, 介于两者之间: 先通过自回归模型生成一个中间产物, 再根据中间产物通过非自回归模型生成语音。 ## 图像生成 任务分类: + Unconditional Generation + Text-to-Image Generation + Image-to-Image Translation 更多的可以参考 [paperswithcode](https://paperswithcode.com/area/computer-vision/image-generation)。 方法速览: + VAE + Flow-based model + Diffusion model GAN 可以当作是一个额外的技巧, 和 VAE, Flow 以及 Diffusion 模型都是可以融合的。 除此之外, 还有像 [image-gpt](https://openai.com/research/image-gpt) 这样的自回归模型。 maskgit mask-predict 2202.04200 2202.04200 2301.00704 acl: D19-1633
// PlanService.cs // // Modified MIT License (MIT) // // Copyright (c) 2015 Completely Fair Games Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // The following content pieces are considered PROPRIETARY and may not be used // in any derivative works, commercial or non commercial, without explicit // written permission from Completely Fair Games: // // * Images (sprites, textures, etc.) // * 3D Models // * Sound Effects // * Music // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using DwarfCorp.GameStates; using Microsoft.Xna.Framework; using Newtonsoft.Json; namespace DwarfCorp { /// <summary> /// A goal region is an abstract way of specifing when a dwarf has reached a goal. /// </summary> public abstract class GoalRegion { /// <summary> /// Determines whetherthe specified voxel is within the goal region. /// </summary> /// <param name="voxel">The voxel.</param> /// <returns> /// <c>true</c> if [is in goal region] [the specified voxel]; otherwise, <c>false</c>. /// </returns> public abstract bool IsInGoalRegion(VoxelHandle voxel); /// <summary> /// Gets a voxel associated with this goal region. /// </summary> /// <returns>The voxel associated with this goal region.</returns> public abstract VoxelHandle GetVoxel(); /// <summary> /// Returns an admissible heuristic for A* planning from the given voxel to this region. /// </summary> /// <param name="voxel">The voxel.</param> /// <returns>An admissible heuristic value.</returns> public abstract float Heuristic(VoxelHandle voxel); /// <summary> /// Determines whether the goal is a.priori possible. /// </summary> /// <returns> /// <c>true</c> if this instance is possible; otherwise, <c>false</c>. /// </returns> public abstract bool IsPossible(); public abstract bool IsReversible(); } }