text stringlengths 184 4.48M |
|---|
/*
* TaskService
*
* Project: KStA ZHQUEST
*
* Copyright 2014 by ELCA Informatik AG
* Steinstrasse 21, CH-8036 Zurich
* All rights reserved.
*
* This software is the confidential and proprietary information
* of ELCA Informatik AG ("Confidential Information"). You
* shall not disclose such "Confidential Information" and shall
* use it only in accordance with the terms of the license
* agreement you entered into with ELCA.
*/
package vn.elca.training.service.impl;
import com.querydsl.jpa.impl.JPAQuery;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vn.elca.training.model.entity.Project;
import vn.elca.training.model.entity.QProject;
import vn.elca.training.model.entity.QTask;
import vn.elca.training.model.entity.Task;
import vn.elca.training.model.entity.TaskAudit.AuditType;
import vn.elca.training.model.entity.TaskAudit.Status;
import vn.elca.training.model.exception.ApplicationUnexpectedException;
import vn.elca.training.model.exception.DeadlineAfterFinishingDateException;
import vn.elca.training.repository.TaskRepository;
import vn.elca.training.service.AuditService;
import vn.elca.training.service.TaskService;
import vn.elca.training.validator.TaskValidator;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
/**
* @author vlp
*/
@Service
@Transactional
public class TaskServiceImpl implements TaskService {
private static final int FETCH_LIMIT = 10;
private final Log logger = LogFactory.getLog(getClass());
@Autowired
private TaskRepository taskRepository;
@Autowired
private AuditService auditService;
@Autowired
private TaskValidator taskValidator;
@PersistenceContext
EntityManager entityManager;
@Override
public List<Project> findProjectsByTaskName(String taskName) {
return taskRepository.findProjectsByTaskName(taskName);
}
@Override
public List<String> listNumberOfTasks(List<Project> projects) {
List<String> result = new ArrayList<>(projects.size());
for (Project project : projects) {
result.add(String.format("Project %s has %s tasks.", project.getName(), project.getTasks().size()));
}
return result;
}
@Override
public List<String> listProjectNameOfRecentTasks() {
//FETCH_LIME = 10
List<String> projectNames = new ArrayList<>(FETCH_LIMIT);//Create array for 10 elements
List<Task> tasks = taskRepository.listRecentTasks(FETCH_LIMIT);//Get 10 most recent tasks
for (Task task : tasks) {//Start adding project name into array
projectNames.add(task.getProject().getName());//Getting project name from task
}
return projectNames;
}
@Override
public List<String> listProjectNameOfRecentTasks2() {
//FETCH_LIME = 10
List<String> projectNames = new ArrayList<>(FETCH_LIMIT);//Create array for 10 elements
// a way to fix Select n + 1 issue
//-> fetch type : EAGER
//-> query dsl
//-> use .fecthJoin()
// write a query by QueryDSL to remove a "SELECT N + 1" issue
List<Project> projectlist = new JPAQuery<QProject>(entityManager)
.select(QProject.project)
.from(QProject.project)
.join(QProject.project.tasks, QTask.task)
.orderBy(QTask.task.id.desc())
.limit(FETCH_LIMIT)
.fetch();
for(Project p : projectlist){
projectNames.add(p.getName());
}
return projectNames;
}
@Override
public List<Task> listTasksById(List<Long> ids) {
List<Task> tasks = new ArrayList<>(ids.size());
for (Long id : ids) {
tasks.add(getTaskById(id));
}
return tasks;
}
@Override
public List<Task> listTasksById2(List<Long> ids) {
return new JPAQuery<QTask>(entityManager)
.select(QTask.task)
.from(QTask.task)
.where(QTask.task.id.in(ids))
.fetch();
}
@Override
public Task getTaskById(Long id) {
return taskRepository.findById(id).orElse(null);
// Should throw exception if not found
}
@Override
@Transactional(rollbackFor = DeadlineAfterFinishingDateException.class)
public void updateDeadline(Long taskId, LocalDate deadline) throws DeadlineAfterFinishingDateException {
Optional<Task> optional = taskRepository.findById(taskId);
if (optional.isPresent()) {
Task task = optional.get();
task.setDeadline(deadline);
save(task);
}
// Should throw exception if not found
}
@Override
// vì ApplicationUnexpectedException là 1 uncheckException và default rollbackFor của 1 transaction là 1 uncheck
//-> nó khớp và sẽ rollback lại được enity Task bị sai date
// chỉ rollback những gì trong 1 transaction sẽ làm, ngoài trans sẽ ko đc rollback
public void createTaskForProject(String taskName, LocalDate deadline, Project project) {
Task task = new Task(project, taskName);
task.setDeadline(deadline);
AuditType auditType = AuditType.INSERT;
try {
task = save(task);
auditService.saveAuditDataForTask(task, auditType, Status.SUCCESS, "Task was saved successfully.");
} catch (Exception e) {
String errorMessage = String.format("An exception (Error-ID = %s) happened when saving/updating task: %s",
UUID.randomUUID(), e.getMessage());
logger.error(errorMessage, e);
auditService.saveAuditDataForTask(task, auditType, Status.FAILED, errorMessage);
throw new ApplicationUnexpectedException(e);
}
}
// @Transactional(rollbackFor = DeadlineAfterFinishingDateException.class)
private Task save(Task task) throws DeadlineAfterFinishingDateException {
Task result = taskRepository.save(task);
taskValidator.validate(task);
return result;
}
} |
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class DocumentDueNotification extends Notification
{
use Queueable;
protected $document;
/**
* Create a new notification instance.
*/
public function __construct($document)
{
$this->document = $document;
}
/**
* Get the notification's delivery channels.
*
* @return array<int, string>
*/
public function via(object $notifiable): array
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*/
public function toMail($notifiable)
{
$dueDate = $this->document->due_date->format('Y-m-d');
$documentName = $this->document->document;
return (new MailMessage)
->subject("Document Due Soon: {$documentName}")
->line("The document '{$documentName}' is due on {$dueDate}.")
->action('View Document', url('/documents/' . $this->document->id))
->line('Thank you for using our application!');
}
/**
* Get the array representation of the notification.
*
* @return array<string, mixed>
*/
public function toArray(object $notifiable): array
{
return [
//
];
}
} |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
#ifndef GBN_NETDEVICE_HELPER_H
#define GBN_NETDEVICE_HELPER_H
#include <string>
#include "ns3/attribute.h"
#include "ns3/object-factory.h"
#include "ns3/net-device-container.h"
#include "ns3/node-container.h"
#include "ns3/gbn-channel.h"
namespace ns3 {
/**
* \brief build a set of GbnNetDevice objects
*/
class GbnNetDeviceHelper : public PcapHelperForDevice
{
public:
/**
* Construct a GbbnNetDeviceHelper.
*/
GbnNetDeviceHelper ();
virtual ~GbnNetDeviceHelper () {}
/**
* Each net device must have a queue to pass packets through.
* This method allows one to set the type of the queue that is automatically
* created when the device is created and attached to a node.
*
* \param type the type of queue
* \param n1 the name of the attribute to set on the queue
* \param v1 the value of the attribute to set on the queue
* \param n2 the name of the attribute to set on the queue
* \param v2 the value of the attribute to set on the queue
* \param n3 the name of the attribute to set on the queue
* \param v3 the value of the attribute to set on the queue
* \param n4 the name of the attribute to set on the queue
* \param v4 the value of the attribute to set on the queue
*
* Set the type of queue to create and associated to each
* GbnNetDevice created through GbbnNetDeviceHelper::Install.
*/
void SetQueue (std::string type,
std::string n1 = "", const AttributeValue &v1 = EmptyAttributeValue (),
std::string n2 = "", const AttributeValue &v2 = EmptyAttributeValue (),
std::string n3 = "", const AttributeValue &v3 = EmptyAttributeValue (),
std::string n4 = "", const AttributeValue &v4 = EmptyAttributeValue ());
/**
* Each net device must have a channel to pass packets through.
* This method allows one to set the type of the channel that is automatically
* created when the device is created and attached to a node.
*
* \param type the type of queue
* \param n1 the name of the attribute to set on the queue
* \param v1 the value of the attribute to set on the queue
* \param n2 the name of the attribute to set on the queue
* \param v2 the value of the attribute to set on the queue
* \param n3 the name of the attribute to set on the queue
* \param v3 the value of the attribute to set on the queue
* \param n4 the name of the attribute to set on the queue
* \param v4 the value of the attribute to set on the queue
*
* Set the type of channel to create and associated to each
* GbnNetDevice created through GbbnNetDeviceHelper::Install.
*/
void SetChannel (std::string type,
std::string n1 = "", const AttributeValue &v1 = EmptyAttributeValue (),
std::string n2 = "", const AttributeValue &v2 = EmptyAttributeValue (),
std::string n3 = "", const AttributeValue &v3 = EmptyAttributeValue (),
std::string n4 = "", const AttributeValue &v4 = EmptyAttributeValue ());
/**
* \param n1 the name of the attribute to set
* \param v1 the value of the attribute to set
*
* Set these attributes on each ns3::GbnNetDevice created
* by GbnNetDeviceHelper::Install
*/
void SetDeviceAttribute (std::string n1, const AttributeValue &v1);
/**
* \param n1 the name of the attribute to set
* \param v1 the value of the attribute to set
*
* Set these attributes on each ns3::CsmaChannel created
* by GbnNetDeviceHelper::Install
*/
void SetChannelAttribute (std::string n1, const AttributeValue &v1);
/**
* GbnNetDevice is Broadcast capable and ARP needing. This function
* limits the number of GbnNetDevices on one channel to two, disables
* Broadcast and ARP and enables PointToPoint mode.
*
* \warning It must be used before installing a NetDevice on a node.
*
* \param pointToPointMode True for PointToPoint GbnNetDevice
*/
void SetNetDevicePointToPointMode (bool pointToPointMode);
/**
* This method creates an ns3::GbnChannel with the attributes configured by
* GbbnNetDeviceHelper::SetChannelAttribute, an ns3::GbnNetDevice with the attributes
* configured by GbnNetDeviceHelper::SetDeviceAttribute and then adds the device
* to the node and attaches the channel to the device.
*
* \param node The node to install the device in
* \returns A container holding the added net device.
*/
NetDeviceContainer Install (Ptr<Node> node) const;
/**
* This method creates an ns3::GbnNetDevice with the attributes configured by
* GbbnNetDeviceHelper::SetDeviceAttribute and then adds the device to the node and
* attaches the provided channel to the device.
*
* \param node The node to install the device in
* \param channel The channel to attach to the device.
* \returns A container holding the added net device.
*/
NetDeviceContainer Install (Ptr<Node> node, Ptr<GbnChannel> channel) const;
/**
* This method creates an ns3::GbnChannel with the attributes configured by
* GbbnNetDeviceHelper::SetChannelAttribute. For each Ptr<node> in the provided
* container: it creates an ns3::GbnNetDevice (with the attributes
* configured by GbnNetDeviceHelper::SetDeviceAttribute); adds the device to the
* node; and attaches the channel to the device.
*
* \param c The NodeContainer holding the nodes to be changed.
* \returns A container holding the added net devices.
*/
NetDeviceContainer Install (const NodeContainer &c) const;
/**
* For each Ptr<node> in the provided container, this method creates an
* ns3::GbnNetDevice (with the attributes configured by
* GbbnNetDeviceHelper::SetDeviceAttribute); adds the device to the node; and attaches
* the provided channel to the device.
*
* \param c The NodeContainer holding the nodes to be changed.
* \param channel The channel to attach to the devices.
* \returns A container holding the added net devices.
*/
NetDeviceContainer Install (const NodeContainer &c, Ptr<GbnChannel> channel) const;
/**
* \param a first node
* \param b second node
* \return a NetDeviceContainer for nodes
*
* Saves you from having to construct a temporary NodeContainer.
* Also, if MPI is enabled, for distributed simulations,
* appropriate remote point-to-point channels are created.
*/
NetDeviceContainer Install (Ptr<Node> a, Ptr<Node> b);
private:
/**
* \brief Enable pcap output the indicated net device.
*
* NetDevice-specific implementation mechanism for hooking the trace and
* writing to the trace file.
*
* \param prefix Filename prefix to use for pcap files.
* \param nd Net device for which you want to enable tracing.
* \param promiscuous If true capture all possible packets available at the device.
* \param explicitFilename Treat the prefix as an explicit filename if true
*/
virtual void EnablePcapInternal (std::string prefix, Ptr<NetDevice> nd, bool promiscuous, bool explicitFilename);
/**
* This method creates an ns3::GbnNetDevice with the attributes configured by
* GbbnNetDeviceHelper::SetDeviceAttribute and then adds the device to the node and
* attaches the provided channel to the device.
*
* \param node The node to install the device in
* \param channel The channel to attach to the device.
* \returns The new net device.
*/
Ptr<NetDevice> InstallPriv (Ptr<Node> node, Ptr<GbnChannel> channel) const;
ObjectFactory m_queueFactory; //!< Queue factory
ObjectFactory m_deviceFactory; //!< NetDevice factory
ObjectFactory m_channelFactory; //!< Channel factory
bool m_pointToPointMode; //!< Install PointToPoint GbnNetDevice or Broadcast ones
};
} // namespace ns3
#endif /* GBN_NETDEVICE_HELPER_H */ |
% embedding encoding polar coordinates for fixed patch pixel positions
%
% Usage: [epos, phi] = embfixedpos(cphi, crho, s)
%
% cphi : embedding coefficients for phi
% crho : embedding coefficients for rho
% s : patch size
% epos : embeddings for all pixel positions
% phi : angle phi for all pixels
%
% Authors: A. Bursuc, G. Tolias, H. Jegou. 2015.
%
% Modified for Multiple-Kernel Local-Patch Descriptor, BMVC 20107
% Authors: A. Mukundan, G. Tolias, O. Chum, 2017
function [epos, phi, gmask] = embfixedpos(c1, c2, s, coord, gsigma)
if ~exist('gsigma'), gsigma = 1.0; end
if ~exist('coord'), coord = 'polar'; end
% fixed grid of the patch
xx = (-(s-1):2:s-1);
yy = xx';
xx = repmat(xx, [s 1]);
yy = repmat(yy, [1 s]);
xx = xx(:);
yy = yy(:);
% polar coordinates
[phi, rho] = cart2pol(xx, yy);
rho = rho ./ sqrt(2*(s-1).^2);
% gaussian weight
gmask = reshape(exp(-rho.^2/gsigma.^2), s, s);
switch coord
case 'polar'
% embeddings for rho and phi
ephi = angle2vec(c1, phi(:)');
erho = angle2vec(c2, rho(:)'*pi);
% pre-compute phi-rho kronecker
epos = zeros(size(erho,1)*size(ephi,1),size(ephi,2));
for i = 1:size(ephi,2)
epos(:,i) = kron(ephi(:,i), erho(:,i));
end
% apply the gaussian mask
epos = bsxfun(@times, epos', gmask(:))';
case 'cart'
% embeddings for x and y
ex = angle2vec(c1, 0.5*pi*xx(:)'/(s-1));
ey = angle2vec(c2, 0.5*pi*yy(:)'/(s-1));
% pre-compute x-y kronecker
epos = zeros(size(ex,1)*size(ey,1),size(ey,2));
for i = 1:size(ex,2)
epos(:,i) = kron(ex(:,i), ey(:,i));
end
% apply the gaussian mask
epos = bsxfun(@times, epos', gmask(:))';
otherwise
error('Unknown coordinate system\n');
end |
package com.spring.board.model.entity;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import java.time.ZonedDateTime;
import java.util.Objects;
@Entity
@Table(
name = "follow",
uniqueConstraints = {@UniqueConstraint(columnNames = {"follower", "following"})})
public class FollowEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long followId;
@ManyToOne
@JoinColumn(name = "follower")
private UserEntity follower;
@ManyToOne
@JoinColumn(name = "following")
private UserEntity following;
@Column private ZonedDateTime createdDateTime;
public FollowEntity() {}
public static FollowEntity of(UserEntity follower, UserEntity following) {
FollowEntity follow = new FollowEntity();
follow.setFollower(follower);
follow.setFollowing(following);
return follow;
}
public Long getFollowId() {
return followId;
}
public void setFollowId(Long followId) {
this.followId = followId;
}
public UserEntity getFollower() {
return follower;
}
public void setFollower(UserEntity follower) {
this.follower = follower;
}
public UserEntity getFollowing() {
return following;
}
public void setFollowing(UserEntity following) {
this.following = following;
}
public ZonedDateTime getCreatedDateTime() {
return createdDateTime;
}
public void setCreatedDateTime(ZonedDateTime createdDateTime) {
this.createdDateTime = createdDateTime;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof FollowEntity that)) return false;
return Objects.equals(getFollowId(), that.getFollowId())
&& Objects.equals(getFollower(), that.getFollower())
&& Objects.equals(getFollowing(), that.getFollowing())
&& Objects.equals(getCreatedDateTime(), that.getCreatedDateTime());
}
@Override
public int hashCode() {
return Objects.hash(getFollowId(), getFollower(), getFollowing(), getCreatedDateTime());
}
@PrePersist
private void prePersist() {
this.createdDateTime = ZonedDateTime.now();
}
} |
---
title: 使用 ReportViewer 控件集成 Reporting Services | Microsoft Docs
ms.custom: ''
ms.date: 03/06/2017
ms.prod: sql-server-2014
ms.reviewer: ''
ms.technology: reporting-services
ms.topic: reference
helpviewer_keywords:
- ReportViewer controls
- integrating reports [Reporting Services]
ms.assetid: 3ba47fb4-73a9-4059-89fd-329adebe94a8
author: maggiesMSFT
ms.author: maggies
manager: kfile
ms.openlocfilehash: 18e28dbf1557bf36106b454738d0c0bfc037f2a7
ms.sourcegitcommit: ad4d92dce894592a259721a1571b1d8736abacdb
ms.translationtype: MT
ms.contentlocale: zh-CN
ms.lasthandoff: 08/04/2020
ms.locfileid: "87577408"
---
# <a name="integrating-reporting-services-using-the-reportviewer-controls"></a>使用 ReportViewer 控件集成 Reporting Services
[!INCLUDE[msCoName](../../includes/msconame-md.md)][!INCLUDE[vsOrcas](../../includes/vsorcas-md.md)]提供两个 ReportViewer 控件,用于将报表查看功能集成到应用程序中。 一个控件版本针对基于 Windows 窗体的应用程序,另一个版本针对 Web 窗体应用程序。 每个控件都提供类似的功能,但分别设计为针对其各自的环境。 这两个控件都可以处理已部署到 Report Server (远程处理模式的报表) 或已复制到 [!INCLUDE[msCoName](../../includes/msconame-md.md)] [!INCLUDE[ssNoVersion](../../includes/ssnoversion-md.md)] [!INCLUDE[ssRSnoversion](../../includes/ssrsnoversion-md.md)] 未安装 (本地处理模式的计算机) 。
ReportViewer 控件不包括对动态适应具有不同屏幕分辨率的不同设备的内置支持。
## <a name="remote-processing-mode"></a>远程处理模式
远程处理模式是用于查看已部署到某一报表服务器的报表的首选方法。 远程处理模式具备以下优点:
- 远程处理为运行报表提供优化的解决方案,因为报表服务器处理该报表。
- 因为所有处理均由报表服务器进行,所以,报表请求可由扩展部署中的多个报表服务器或在某一扩展方案中具有多个处理器的服务器处理。
此外,在远程模式下运行的报表可利用报表服务器的全部功能,包括所有呈现和数据扩展插件。
> [!NOTE]
> 当该控件在远程处理模式下运行时可用于 ReportViewer 控件的扩展插件的列表取决于在报表服务器上安装的 [!INCLUDE[ssRSnoversion](../../includes/ssrsnoversion-md.md)] 的版本。
## <a name="local-processing-mode"></a>本地处理模式
本地处理模式提供在未安装 [!INCLUDE[ssRSnoversion](../../includes/ssrsnoversion-md.md)] 时用于查看和呈现报表的替代方法。 与远程处理不同,在该控件中只有报表服务器提供的一部分功能可用。 在本地处理模式中,数据处理不是由该控件处理的,而是由宿主应用程序实现的。 但是,报表处理由控件本身处理。 在本地处理模式中,只有 PDF、Excel、Word 和图像呈现扩展插件才可用。
## <a name="see-also"></a>另请参阅
[将 Reporting Services 集成到应用程序中](../application-integration/integrating-reporting-services-into-applications.md)
[使用 Visual Studio 创建 SSRS 报表 (博客) ](https://jwcooney.com/2015/01/07/ssrs-basics-set-up-visual-studio-to-write-a-new-ssrs-report/) |
package edu.ntnu.idatt2001.view;
import edu.ntnu.idatt2001.model.screentype.ApplicationScreenType;
import edu.ntnu.idatt2001.model.state.ApplicationState;
import edu.ntnu.idatt2001.util.Widgets;
import javafx.geometry.Pos;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Region;
import javafx.util.Builder;
/**
* This class provides a builder for the main application screen in the game.
* The screen can display various sub-views such as the title,
* game, character, and settings screens.
*/
public class ApplicationScreenBuilder implements Builder<Region> {
private final ApplicationState state;
private final Region titleView;
private final Region gameView;
private final Region characterView;
private final Region settingsView;
private final Region menubarView;
/**
* Constructor for ApplicationScreenBuilder.
*
* @param state the ApplicationState model containing the current application state
* @param titleView the Region to display as the title screen
* @param gameView the Region to display as the game screen
* @param characterView the Region to display as the character screen
* @param settingsView the Region to display as the settings screen
* @param menubarView the Region to display as the menu bar
*/
public ApplicationScreenBuilder(ApplicationState state,
Region titleView,
Region gameView,
Region characterView,
Region settingsView,
Region menubarView) {
this.state = state;
this.titleView = titleView;
this.gameView = gameView;
this.characterView = characterView;
this.settingsView = settingsView;
this.menubarView = menubarView;
}
/**
* Builds the main application screen as a Region.
* Sets up the layout and binds the current screen to the model's current screen.
*
* @return a Region containing the application screen
*/
public Region build() {
BorderPane results = new BorderPane();
results.getStylesheets().add("/css/application.css");
results.getStyleClass().add("app-pane");
results.setTop(menubarView);
results.setBottom(Widgets.createLabel("All Rights Reserved ©", "bottom-text"));
results.setCenter(getScreen(state.getCurrentScreen()));
results.setAlignment(results.getTop(), Pos.TOP_RIGHT);
results.setCenter(getScreen(ApplicationScreenType.TITLE_SCREEN));
state.currentScreenProperty()
.addListener((observable, oldValue, newValue) -> results.setCenter(getScreen(newValue)));
return results;
}
/**
* Retrieves the appropriate screen based on the provided ApplicationScreenType.
*
* @param screen the type of screen to retrieve
* @return the Region corresponding to the provided screen type
*/
private Region getScreen(ApplicationScreenType screen) {
return switch (screen) {
case TITLE_SCREEN -> titleView;
case CREATION_SCREEN -> characterView;
case SETTINGS_SCREEN -> settingsView;
case GAME_SCREEN -> gameView;
};
}
} |
import React from 'react';
import Document, { Html, Head, Main, NextScript, DocumentContext } from 'next/document';
class MyDocument extends Document {
static async getInitialProps(ctx: DocumentContext) {
const initialProps = await Document.getInitialProps(ctx);
return { ...initialProps };
}
render() {
return (
<Html lang="en">
<Head>
<meta charSet="utf-8" />
<meta name="theme-color" content="#696969" />
<meta name="description" content="Official website for Scott Horlacher." />
<link rel="shortcut icon" href="sh.ico" type="image/x-icon" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"></link>
<link rel="preconnect" href="https://fonts.gstatic.com"/>
<link href="https://fonts.googleapis.com/css2?family=Dancing+Script&display=swap" rel="stylesheet"/>
<link href="https://fonts.googleapis.com/css2?family=Abril+Fatface&family=Alfa+Slab+One&family=Oswald&family=Spectral&display=swap" rel="stylesheet"/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument; |
#include "compiler/ast.hpp"
#include "compiler/compilation_config.hpp"
#include "compiler/source_location.hpp"
#include "compiler/variable.hpp"
#include "context.hpp"
#include "io/write.hpp"
#include "memory/free_store.hpp"
#include "module.hpp"
#include "util/define_struct.hpp"
#include "util/sum_type.hpp"
#include <algorithm>
#include <format>
#include <stdexcept>
namespace insider {
static expression
pop(result_stack& stack) {
assert(!stack.empty());
expression result = stack.back();
stack.pop_back();
return result;
}
template <typename T>
static ptr<T>
pop(result_stack& stack) {
return assume<T>(pop(stack));
}
static std::vector<expression>
pop_vector(result_stack& stack, std::size_t n) {
std::vector<expression> result;
result.reserve(n);
for (std::size_t i = 0; i < n; ++i)
result.push_back(pop(stack));
return result;
}
static std::vector<expression>
pop_vector_reverse(result_stack& stack, std::size_t n) {
std::vector<expression> result;
result.resize(n);
for (std::size_t i = 0; i < n; ++i)
result[result.size() - i - 1] = pop(stack);
return result;
}
static std::string
make_indent(std::size_t indent) {
return std::string(indent, ' ');
}
literal_expression::literal_expression(ptr<> value)
: value_{value}
{ }
void
literal_expression::visit_members(member_visitor const& f) const {
f(value_);
}
void
literal_expression::update(context&, result_stack&) { }
std::string
literal_expression::show(context& ctx, std::size_t indent) const {
return std::format("{}- literal-expression: {}\n",
make_indent(indent), datum_to_string(ctx, value_));
}
local_reference_expression::local_reference_expression(
ptr<local_variable> var
)
: variable_{var}
{ }
void
local_reference_expression::visit_members(member_visitor const& f) const {
f(variable_);
}
void
local_reference_expression::update(context&, result_stack&) { }
std::string
local_reference_expression::show(context&, std::size_t indent) const {
return std::format("{}- local-reference: {}@{}\n",
make_indent(indent),
variable_->name(), static_cast<void*>(variable_.value()));
}
top_level_reference_expression::top_level_reference_expression(
ptr<top_level_variable> v
)
: variable_{v}
{ }
void
top_level_reference_expression::visit_members(member_visitor const& f) const {
f(variable_);
}
void
top_level_reference_expression::update(context&, result_stack&) { }
std::string
top_level_reference_expression::show(context&, std::size_t indent) const {
return std::format("{}- top-level-reference: {}@{}\n",
make_indent(indent),
variable_->name(), static_cast<void*>(variable_.value()));
}
unknown_reference_expression::unknown_reference_expression(ptr<syntax> name)
: name_{name}
{ }
void
unknown_reference_expression::visit_members(member_visitor const& f) const {
f(name_);
}
void
unknown_reference_expression::update(context&, result_stack&) { }
std::string
unknown_reference_expression::show(context& ctx, std::size_t indent) const {
return std::format("{}- unknown-reference: {}\n",
make_indent(indent), datum_to_string(ctx, name_));
}
application_expression::application_expression(source_location loc,
expression t,
std::vector<expression> args)
: target_{init(t)}
, arguments_{init(std::move(args))}
, argument_names_(init(std::vector<ptr<keyword>>(args.size())))
, origin_loc_{std::move(loc)}
{ }
application_expression::application_expression(
source_location loc,
expression t,
std::vector<expression> args,
std::vector<ptr<keyword>> arg_names
)
: target_{init(t)}
, arguments_{init(std::move(args))}
, argument_names_{init(std::move(arg_names))}
, origin_loc_{std::move(loc)}
{
assert(arguments_.get().size() == argument_names_.get().size());
}
void
application_expression::visit_members(member_visitor const& f) const {
target_.visit_members(f);
for (auto const& arg : arguments_.get())
arg.visit_members(f);
for (auto const& kw : argument_names_.get())
f(kw);
}
static void
update_member(free_store& fs, auto owner, auto& ref, auto new_value) {
if (ref != new_value) {
ref = new_value;
fs.notify_arc(owner, new_value);
}
}
static void
update_member(free_store& fs, auto owner, expression& ref, expression new_value) {
if (ref != new_value) {
ref = new_value;
fs.notify_arc(owner, new_value.get());
}
}
template <typename T>
static void
update_member(free_store& fs, auto owner, member<T>& ref, T new_value) {
ref.assign(fs, owner, new_value);
}
static void
update_member(free_store& fs, auto owner, std::vector<expression>& v,
std::vector<expression> new_values) {
if (v != new_values) {
v = std::move(new_values);
for (expression member : v)
fs.notify_arc(owner, member.get());
}
}
void
application_expression::update(context& ctx, result_stack& stack) {
expression target = pop(stack);
auto args = pop_vector(stack, arguments_.get().size());
update_member(ctx.store, this, target_, target);
update_member(ctx.store, this, arguments_, std::move(args));
update_size_estimate();
}
static std::size_t
sum_size_estimates(std::vector<expression> const& expressions) {
std::size_t result = 0;
for (expression e : expressions)
result += size_estimate(e);
return result;
}
void
application_expression::update_size_estimate() {
size_estimate_
= insider::size_estimate(target_.get())
+ sum_size_estimates(arguments_.get())
+ 1;
}
std::string
application_expression::show(context& ctx, std::size_t indent) const {
std::string i = make_indent(indent);
std::string t = insider::show(ctx, target_.get(), indent + 4);
std::string args;
for (expression e : arguments_.get())
args += insider::show(ctx, e, indent + 4);
return std::format("{}- application:\n"
"{} target:\n"
"{}"
"{} arguments:\n"
"{}",
i, i, t, i, args);
}
bool
has_keyword_arguments(ptr<application_expression> app) {
return std::ranges::any_of(app->argument_names(),
[] (ptr<keyword> kw) { return kw != nullptr; });
}
static std::optional<std::size_t>
argument_index(ptr<lambda_expression> lambda, ptr<keyword> name) {
for (std::size_t i = 0; i < lambda->parameter_names().size(); ++i)
if (lambda->parameter_names()[i] == name)
return i;
return std::nullopt;
}
#define WILL_RAISE_EXCEPTION "Call will raise an exception at run-time."
static bool
fill_keyword_parameter_slots(std::vector<expression>& new_args,
diagnostic_sink& diagnostics,
ptr<application_expression> app,
ptr<lambda_expression> target) {
for (std::size_t i = 0; i < app->argument_names().size(); ++i) {
ptr<keyword> name = app->argument_names()[i];
if (name) {
if (auto index = argument_index(target, name)) {
if (new_args[*index] != nullptr) {
diagnostics.show(app->origin_location(),
std::format("Duplicate keyword argument #:{}. "
WILL_RAISE_EXCEPTION,
name->value()));
return false;
}
else
new_args[*index] = app->arguments()[i];
} else {
diagnostics.show(app->origin_location(),
std::format("{} does not have keyword parameter #:{}. "
WILL_RAISE_EXCEPTION,
target->name(),
name->value()));
return false;
}
}
}
return true;
}
static std::size_t
find_free_index(std::vector<expression> const& args, std::size_t start) {
for (std::size_t i = start; i < args.size(); ++i)
if (!args[i])
return i;
assert(false);
throw std::logic_error{"No slot for unnamed argument"};
}
static void
fill_positional_parameter_slots(std::vector<expression>& new_args,
ptr<application_expression> app) {
std::size_t first_possible_index = 0;
for (std::size_t i = 0; i < app->argument_names().size(); ++i) {
ptr<keyword> name = app->argument_names()[i];
if (!name) {
std::size_t index = find_free_index(new_args, first_possible_index);
new_args[index] = app->arguments()[i];
first_possible_index = index + 1;
}
}
}
static bool
check_required_parameters_are_provided(std::vector<expression> const& new_args,
diagnostic_sink& diagnostics,
ptr<lambda_expression> target,
source_location const& location) {
for (std::size_t i = 0; i < required_parameter_count(target); ++i)
if (!new_args[i]) {
std::string name;
if (auto n = target->parameter_names()[i])
name = std::format("#:{}", n->value());
else
name = std::format("#{}", i + 1);
diagnostics.show(location,
std::format("{}: Required parameter {} not provided. "
WILL_RAISE_EXCEPTION,
target->name(),
name));
return false;
}
return true;
}
static void
fill_unsupplied_optional_parameters_with_defaults(
context& ctx,
std::vector<expression>& new_args,
ptr<lambda_expression> target
) {
for (std::size_t i = required_parameter_count(target);
i < leading_parameter_count(target);
++i)
if (!new_args[i])
new_args[i] = make<literal_expression>(ctx, ctx.constants->default_value);
}
ptr<application_expression>
reorder_supplement_and_validate_application(context& ctx,
diagnostic_sink& diagnostics,
ptr<application_expression> app,
ptr<lambda_expression> target) {
std::vector<expression> new_args;
new_args.resize(std::max(app->arguments().size(),
leading_parameter_count(target)));
if (!fill_keyword_parameter_slots(new_args, diagnostics, app, target))
return {};
fill_positional_parameter_slots(new_args, app);
if (!check_required_parameters_are_provided(new_args, diagnostics, target,
app->origin_location()))
return {};
fill_unsupplied_optional_parameters_with_defaults(ctx, new_args, target);
return make<application_expression>(ctx, app->origin_location(), app->target(),
std::move(new_args));
}
built_in_operation_expression::built_in_operation_expression(
opcode op, std::vector<expression> operands, bool has_result,
ptr<native_procedure> proc
)
: operation_{op}
, operands_{init(std::move(operands))}
, has_result_{has_result}
, proc_{proc}
{
update_size_estimate();
}
void
built_in_operation_expression::visit_members(member_visitor const& f) const {
for (expression const& operand : operands_.get())
operand.visit_members(f);
f(proc_);
}
void
built_in_operation_expression::update(context& ctx, result_stack& stack) {
auto operands = pop_vector(stack, operands_.get().size());
update_member(ctx.store, this, operands_, std::move(operands));
update_size_estimate();
}
void
built_in_operation_expression::update_size_estimate() {
size_estimate_ = 1 + sum_size_estimates(operands_.get());
}
std::string
built_in_operation_expression::show(context& ctx, std::size_t indent) const {
std::string i = make_indent(indent);
std::string t = make_indent(indent + 4) + opcode_to_info(operation_).mnemonic;
std::string operands;
for (expression e : operands_.get())
operands += insider::show(ctx, e, indent + 4);
return std::format("{}- built-in-operation {}:\n"
"{} operands:\n"
"{}\n",
i, opcode_to_info(operation_).mnemonic, i, operands);
}
sequence_expression::sequence_expression(std::vector<expression> exprs)
: expressions_{init(std::move(exprs))}
{
update_size_estimate();
}
void
sequence_expression::visit_members(member_visitor const& f) const {
for (auto& e : expressions_.get())
e.visit_members(f);
}
void
sequence_expression::update(context& ctx, result_stack& stack) {
update_member(ctx.store, this, expressions_,
pop_vector_reverse(stack, expressions_.get().size()));
update_size_estimate();
}
void
sequence_expression::update_size_estimate() {
size_estimate_ = sum_size_estimates(expressions_.get());
}
std::string
sequence_expression::show(context& ctx, std::size_t indent) const {
std::string subexprs;
for (expression e : expressions_.get())
subexprs += insider::show(ctx, e, indent + 2);
return std::format("{}- sequence:\n{}", make_indent(indent), subexprs);
}
definition_pair_expression::definition_pair_expression(
ptr<local_variable> var,
insider::expression expr
)
: variable_{var}
, expression_{expr}
{ }
void
definition_pair_expression::visit_members(member_visitor const& f) const {
f(variable_);
expression_.visit_members(f);
}
let_expression::let_expression(std::vector<definition_pair_expression> defs,
expression body)
: definitions_{init(std::move(defs))}
, body_{init(body)}
{
update_size_estimate();
}
void
let_expression::visit_members(member_visitor const& f) const {
for (definition_pair_expression const& dp : definitions_.get())
dp.visit_members(f);
body_.visit_members(f);
}
void
let_expression::update(context& ctx, result_stack& stack) {
auto body = pop(stack);
auto definition_exprs = pop_vector_reverse(stack, definitions_.get().size());
update_member(ctx.store, this, body_, body);
std::vector<definition_pair_expression> def_pairs;
def_pairs.reserve(definition_exprs.size());
for (std::size_t i = 0; i < definition_exprs.size(); ++i)
def_pairs.emplace_back(definitions_.get()[i].variable(),
definition_exprs[i]);
if (definitions_.get() != def_pairs)
definitions_.assign(ctx.store, this, std::move(def_pairs));
update_size_estimate();
}
void
let_expression::update_size_estimate() {
size_estimate_ = insider::size_estimate(body_.get());
for (definition_pair_expression const& dp : definitions_.get())
size_estimate_ += insider::size_estimate(dp.expression());
}
std::string
let_expression::show(context& ctx, std::size_t indent) const {
std::string defs;
for (definition_pair_expression const& dp : definitions_.get())
defs += std::format("{}- {}@{}\n{}",
make_indent(indent + 4),
dp.variable()->name(),
static_cast<void*>(dp.variable().value()),
insider::show(ctx, dp.expression(), indent + 6));
std::string i = make_indent(indent);
return std::format("{}- let:\n"
"{} variables:\n"
"{}"
"{} body:\n"
"{}",
i, i, defs, i, insider::show(ctx, body_.get(), indent + 4));
}
local_set_expression::local_set_expression(ptr<local_variable> target,
insider::expression expr)
: target_{target}
, expression_{init(expr)}
{
update_size_estimate();
}
void
local_set_expression::visit_members(member_visitor const& f) const {
f(target_);
expression_.visit_members(f);
}
void
local_set_expression::update(context& ctx, result_stack& stack) {
update_member(ctx.store, this, expression_, pop(stack));
update_size_estimate();
}
void
local_set_expression::update_size_estimate() {
size_estimate_ = 1 + insider::size_estimate(expression_.get());
}
std::string
local_set_expression::show(context& ctx, std::size_t indent) const {
return std::format("{}- local-set: {}@{}\n{}",
make_indent(indent),
target_->name(),
static_cast<void*>(target_.value()),
insider::show(ctx, expression_.get(), indent + 2));
}
top_level_set_expression::top_level_set_expression(ptr<top_level_variable> var,
insider::expression expr,
bool is_init)
: variable_{var}
, expression_{init(expr)}
, is_init_{is_init}
{
update_size_estimate();
}
void
top_level_set_expression::visit_members(member_visitor const& f) const {
f(variable_);
expression_.visit_members(f);
}
void
top_level_set_expression::update(context& ctx, result_stack& stack) {
update_member(ctx.store, this, expression_, pop(stack));
update_size_estimate();
}
void
top_level_set_expression::update_size_estimate() {
size_estimate_ = 1 + insider::size_estimate(expression_.get());
}
std::string
top_level_set_expression::show(context& ctx, std::size_t indent) const {
return std::format("{}- top-level-set: {}@{}\n{}",
make_indent(indent),
variable_->name(),
static_cast<void*>(variable_.value()),
insider::show(ctx, expression_.get(), indent + 2));
}
void
lambda_expression::parameter::visit_members(member_visitor const& f) const {
f(variable);
}
lambda_expression::lambda_expression(ptr<lambda_expression> source,
ptr<local_variable> new_self_variable)
: parameters_{source->parameters_}
, has_rest_{source->has_rest_}
, body_{source->body_}
, name_{source->name_}
, self_variable_{new_self_variable}
, num_self_references_{source->num_self_references_}
{ }
lambda_expression::lambda_expression(ptr<lambda_expression> source,
expression new_body)
: parameters_{source->parameters_}
, has_rest_{source->has_rest_}
, body_{init(new_body)}
, name_{source->name_}
, free_variables_{source->free_variables_}
, self_variable_{source->self_variable_}
, num_self_references_{source->num_self_references_}
{ }
lambda_expression::lambda_expression(
context& ctx,
std::vector<parameter> parameters,
std::vector<ptr<keyword>> parameter_names,
bool has_rest,
expression body,
std::string name,
std::vector<ptr<local_variable>> const& free_variables
)
: parameters_{std::move(parameters)}
, parameter_names_{std::move(parameter_names)}
, has_rest_{has_rest}
, body_{init(body)}
, name_{std::move(name)}
, self_variable_{
make<local_variable>(ctx, std::format("<self variable for {}>", name_))
}
{
self_variable_->flags().is_self_variable = true;
self_variable_->set_constant_initialiser(ctx.store,
ptr<lambda_expression>(this));
free_variables_.reserve(free_variables.size());
for (ptr<local_variable> v : free_variables)
free_variables_.emplace_back(init(v));
}
void
lambda_expression::update_body(free_store& fs, expression new_body) {
body_.assign(fs, this, new_body);
}
void
lambda_expression::add_free_variable(free_store& fs, ptr<local_variable> v) {
free_variables_.emplace_back(fs, this, v);
}
void
lambda_expression::visit_members(member_visitor const& f) const {
for (auto const& p : parameters_)
p.visit_members(f);
for (auto const& kw : parameter_names_)
f(kw);
body_.visit_members(f);
for (auto const& fv : free_variables_)
fv.visit_members(f);
f(self_variable_);
}
void
lambda_expression::update(context& ctx, result_stack& stack) {
update_member(ctx.store, this, body_, pop(stack));
}
std::string
lambda_expression::show(context& ctx, std::size_t indent) const {
std::string params;
for (auto const& p : parameters_)
params += std::format("{}@{} ",
p.variable->name(),
static_cast<void*>(p.variable.value()));
return std::format("{}- lambda: {} {}\n{}",
make_indent(indent), name_, params,
insider::show(ctx, body_.get(), indent + 2));
}
std::size_t
required_parameter_count(ptr<lambda_expression> lambda) {
return leading_parameter_count(lambda)
- optional_leading_parameter_count(lambda);
}
std::size_t
optional_leading_parameter_count(ptr<lambda_expression> lambda) {
return std::ranges::count_if(
lambda->parameters(),
[] (lambda_expression::parameter const& p) { return p.optional; }
);
}
std::size_t
leading_parameter_count(ptr<lambda_expression> lambda) {
if (lambda->has_rest())
return lambda->parameters().size() - 1;
else
return lambda->parameters().size();
}
if_expression::if_expression(expression test, expression consequent,
expression alternative)
: test_{init(test)}
, consequent_{init(consequent)}
, alternative_{init(alternative)}
{
update_size_estimate();
}
void
if_expression::visit_members(member_visitor const& f) const {
test_.visit_members(f);
consequent_.visit_members(f);
alternative_.visit_members(f);
}
void
if_expression::update(context& ctx, result_stack& stack) {
auto test = pop(stack);
auto consequent = pop(stack);
auto alternative = pop(stack);
update_member(ctx.store, this, test_, test);
update_member(ctx.store, this, consequent_, consequent);
update_member(ctx.store, this, alternative_, alternative);
update_size_estimate();
}
void
if_expression::update_size_estimate() {
size_estimate_
= 1
+ insider::size_estimate(test_.get())
+ insider::size_estimate(consequent_.get())
+ 1
+ insider::size_estimate(alternative_.get());
}
std::string
if_expression::show(context& ctx, std::size_t indent) const {
std::string i = make_indent(indent);
return std::format("{}- if\n"
"{} test:\n"
"{}"
"{} consequent:\n"
"{}"
"{} alternative:\n"
"{}",
i,
i,
insider::show(ctx, test_.get(), indent + 4),
i,
insider::show(ctx, consequent_.get(), indent + 4),
i,
insider::show(ctx, alternative_.get(), indent + 4));
}
loop_body::loop_body(expression body, ptr<loop_id> id,
std::vector<ptr<local_variable>> loop_vars)
: body_{init(body)}
, id_{id}
, vars_{std::move(loop_vars)}
{ }
void
loop_body::visit_members(member_visitor const& f) const {
body_.visit_members(f);
f(id_);
for (ptr<local_variable> const& var : vars_)
f(var);
}
void
loop_body::update(context& ctx, result_stack& stack) {
update_member(ctx.store, this, body_, pop(stack));
}
std::size_t
loop_body::size_estimate() const {
return insider::size_estimate(body_.get());
}
std::string
loop_body::show(context& ctx, std::size_t indent) const {
return std::format("{}- loop-body: {}\n{}",
make_indent(indent),
static_cast<void*>(id_.value()),
insider::show(ctx, body_.get(), indent + 2));
}
loop_continue::loop_continue(ptr<loop_id> id,
std::vector<definition_pair_expression> vars)
: id_{id}
, vars_{init(std::move(vars))}
{
update_size_estimate();
}
void
loop_continue::visit_members(member_visitor const& f) const {
f(id_);
for (definition_pair_expression const& var : vars_.get())
var.visit_members(f);
}
void
loop_continue::update(context& ctx, result_stack& stack) {
auto var_exprs = pop_vector_reverse(stack, vars_.get().size());
std::vector<definition_pair_expression> new_vars;
new_vars.reserve(vars_.get().size());
for (std::size_t i = 0; i < vars_.get().size(); ++i)
new_vars.emplace_back(vars_.get()[i].variable(), var_exprs[i]);
if (vars_.get() != new_vars)
vars_.assign(ctx.store, this, std::move(new_vars));
update_size_estimate();
}
void
loop_continue::update_size_estimate() {
size_estimate_ = 1;
for (definition_pair_expression const& var : vars_.get())
size_estimate_ += insider::size_estimate(var.expression());
}
std::string
loop_continue::show(context& ctx, std::size_t indent) const {
std::string vars;
for (definition_pair_expression const& dp : vars_.get())
vars += std::format("{}- {}@{}\n{}",
make_indent(indent + 4),
dp.variable()->name(),
static_cast<void*>(dp.variable().value()),
insider::show(ctx, dp.expression(), indent + 6));
std::string i = make_indent(indent);
return std::format("{}- loop-continue: {}\n"
"{} variables:\n"
"{}",
i,
static_cast<void*>(id_.value()),
i,
vars);
}
expression
make_internal_reference(context& ctx, std::string const& name) {
std::optional<module_::binding_type> binding
= ctx.internal_module()->find(ctx.intern(name));
assert(binding);
assert(binding->variable);
assert(is<top_level_variable>(binding->variable));
return make<top_level_reference_expression>(
ctx,
assume<top_level_variable>(binding->variable)
);
}
static ptr<>
application_expression_arguments(context& ctx, ptr<application_expression> app) {
return make_list_from_range(ctx, app->arguments());
}
static ptr<>
sequence_expression_expressions(context& ctx, ptr<sequence_expression> seq) {
return make_list_from_range(ctx, seq->expressions());
}
static ptr<>
let_expression_definitions(context& ctx, ptr<let_expression> let) {
return make_list_from_range(
ctx, let->definitions(),
[&] (definition_pair_expression const& dp) {
return cons(ctx, dp.variable(), dp.expression().get());
}
);
}
static ptr<>
lambda_expression_parameters(context& ctx, ptr<lambda_expression> lambda) {
return make_list_from_range(ctx, lambda->parameters(),
[] (lambda_expression::parameter const& param) {
return param.variable;
});
}
static ptr<>
lambda_expression_free_variables(context& ctx, ptr<lambda_expression> lambda) {
return make_list_from_range(ctx, lambda->free_variables());
}
void
export_ast(context& ctx, ptr<module_> result) {
define_struct<literal_expression>(ctx, "literal-expression", result)
.field<&literal_expression::value>("value");
define_struct<local_reference_expression>(ctx, "local-reference-expression",
result)
.field<&local_reference_expression::variable>("variable");
define_struct<top_level_reference_expression>(ctx,
"top-level-reference-expression",
result)
.field<&top_level_reference_expression::variable>("variable");
define_struct<unknown_reference_expression>(ctx,
"unknown-reference-expression",
result)
.field<&unknown_reference_expression::name>("name");
define_struct<application_expression>(ctx, "application-expression", result)
.field<&application_expression::target>("target")
.field<application_expression_arguments>("arguments")
;
define_struct<sequence_expression>(ctx, "sequence-expression", result)
.field<sequence_expression_expressions>("expressions");
define_struct<let_expression>(ctx, "let-expression", result)
.field<let_expression_definitions>("definitions")
.field<&let_expression::body>("body")
;
define_struct<local_set_expression>(ctx, "local-set!-expression", result)
.field<&local_set_expression::target>("target")
.field<&local_set_expression::expression>("expression")
;
define_struct<top_level_set_expression>(ctx, "top-level-set!-expression",
result)
.field<&top_level_set_expression::target>("target")
.field<&top_level_set_expression::expression>("expression")
;
define_struct<lambda_expression>(ctx, "lambda-expression", result)
.field<lambda_expression_parameters>("parameters")
.field<&lambda_expression::has_rest>("has-rest?")
.field<&lambda_expression::body>("body")
.field<&lambda_expression::name>("name")
.field<lambda_expression_free_variables>("free-variables")
;
define_struct<if_expression>(ctx, "if-expression", result)
.field<&if_expression::test>("test")
.field<&if_expression::consequent>("consequent")
.field<&if_expression::alternative>("alternative")
;
}
} // namespace insider |
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *left, *right;
};
struct node* newNode(int data)
{
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
int height(struct node * node) {
if (node == NULL)
return 0;
else {
int lheight = height(node -> left);
int rheight = height(node -> right);
if (lheight > rheight)
return (lheight + 1);
else return (rheight + 1);
}
}
void CurrentLevel(struct node * root, int level) {
if (root == NULL)
return;
if (level == 1)
printf("%d ", root -> data);
else if (level > 1) {
CurrentLevel(root -> left, level - 1);
CurrentLevel(root -> right, level - 1);
}
}
void LevelOrder(struct node * root) {
int h = height(root);
int i;
for (i = 1; i <= h; i++)
CurrentLevel(root, i);
}
int main() {
// Your code goes here;
struct node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
LevelOrder(root);
return 0;
} |
import Data.List
-- Basic Declarations
type Grid = Matrix Value
type Matrix a = [Row a]
type Row a = [a]
type Value = Char
-- Basic Definitions
boxsize :: Int
boxsize = 3
-- returns True or False if a Value is a '.'
empty :: Value -> Bool
empty = (== '.')
-- list of all possible values 1 to 9 - Note that Value type defined above as Char
values :: [Value]
values = ['1'..'9']
-- returns true if singleton list
single :: [a] -> Bool
single [_] = True
single _ = False
-- Empty Grid
blank :: Grid
blank = replicate 9 (replicate 9 '.')
-- Easy Grid - note the dots represent blank cells in the grid
easy :: Grid
easy = ["2....1.38",
"........5",
".7...6...",
".......13",
".981..257",
"31....8..",
"9..8...2.",
".5..69784",
"4..25...."]
-- Gentle Grid - slightly higher difficulty than Easy
gentle :: Grid
gentle = [".1.42...5",
"..2.71.39",
".......4.",
"2.71....6",
"....4....",
"6....74.3",
".7.......",
"12.73.5..",
"3...82.7."]
-- diabolical Grid (more difficulty)
diabolical :: Grid
diabolical = [".9.7..86.",
".31..5.2.",
"8.6......",
"..7.5...6",
"...3.7...",
"5...1.7..",
"......1.9",
".2.6..35.",
".54..8.7."]
-- "unsolvable" Grid - more difficult than diabolical
unsolvable :: Grid
unsolvable = ["1..9.7..3",
".8.....7.",
"..9...6..",
"..72.94..",
"41.....95",
"..85.43..",
"..3...7..",
".5.....4.",
"2..8.6..9"]
-- extremely difficult, this is basically the minimal elements needed to have something that
-- is solvable... this one takes more time to solve, but it does return an answer after
-- several seconds
minimal :: Grid
minimal = [".98......",
"....7....",
"....15...",
"1........",
"...2....9",
"...9.6.82",
".......3.",
"5.1......",
"...4...2."]
-- define rows
rows :: Matrix a -> [Row a]
rows = id
-- note that rows has the property: "rows . rows = id"
-- define columns
cols :: Matrix a -> [Row a]
cols = transpose
-- Example: cols [[1,2],[3,4]] = [[1,3],[2,4]].
-- note that cols has the property: "cols . cols = id"
-- define boxes
boxs :: Matrix a -> [Row a]
boxs = unpack . map cols . pack
where
pack = split . map split
split = chop boxsize
unpack = map concat . concat
chop :: Int -> [a] -> [[a]]
chop n [] = []
chop n xs = take n xs : chop n (drop n xs)
-- note that boxs has the property: "boxs . boxs = id"
-- Validity checking
-- check if dupes are in grid by checking rows, columns, and boxes
valid :: Grid -> Bool
valid g = all nodups (rows g) &&
all nodups (cols g) &&
all nodups (boxs g)
-- check for dupes in a list
nodups :: Eq a => [a] -> Bool
nodups [] = True
nodups (x:xs) = not (elem x xs) && nodups xs
-- A basic sudoku solver
solve :: Grid -> [Grid]
-- filters only the valid matrices out of all possible matrices of all possible choices
-- in principal this will work, but not efficient since the possibilities before doing the
-- validation check are HUGE i.e. 9^51 possible choices
solve = filter valid . collapse . choices
type Choices = [Value]
-- takes Grid as parameter and returns a Matrix of all possible values
-- if cell is empty, then the cell will contain a list of all possible choices from 1 to 9
choices :: Grid -> Matrix Choices
choices = map (map choice)
where
-- "empty" defined above - empty returns true if cell value is a '.'
-- "values" defined above - values is list of chars ['1'..'9']
-- replaces empty cell with list of possible values, if not empty, it leaves the value already populated
choice v = if empty v then values else [v]
-- Reducing a matrix of choices to a choice of matrices can be defined
-- in terms of the normal cartesian product of a list of lists, which
-- generalises the cartesian product of two lists:
-- produces all possible combinations from a list of lists
-- For example, cp [[1,2],[3,4],[5,6]] gives:
-- [[1,3,5],[1,3,6],[1,4,5],[1,4,6],[2,3,5],[2,3,6],[2,4,5],[2,4,6]]
cp :: [[a]] -> [[a]]
cp [] = [[]]
cp (xs:xss) = [y:ys | y <- xs, ys <- cp xss]
-- returns a list of all possible matrices with all possible choices
collapse :: Matrix [a] -> [Matrix a]
collapse = cp . map cp -- 'map cp' collapses each row. the outside 'cp' collapses each col
-- Pruning the search space
---------------------------
-- Our first step to making things better is to introduce the idea
-- of "pruning" the choices that are considered for each square.
-- Prunes go well with wholemeal programming! In particular, from
-- the set of all possible choices for each square, we can prune
-- out any choices that already occur as single entries in the
-- associated row, column, and box, as otherwise the resulting
-- grid will be invalid. Here is the code for this:
prune :: Matrix Choices -> Matrix Choices
prune = pruneBy boxs . pruneBy cols . pruneBy rows
where pruneBy f = f . map reduce . f
-- eliminate choices that can't be successful i.e. if we have one cell with a single
-- possibility, that can't be a possibility for any other cell in the row
reduce :: Row Choices -> Row Choices
reduce xss = [xs `minus` singles | xs <- xss]
where singles = concat (filter single xss)
minus :: Choices -> Choices -> Choices
xs `minus` ys = if single xs then xs else xs \\ ys
-- Note that pruneBy relies on the fact that rows . rows = id, and
-- similarly for the functions cols and boxs, in order to decompose
-- a matrix into its rows, operate upon the rows in some way, and
-- then reconstruct the matrix. Now we can write a new solver:
solve2 :: Grid -> [Grid]
solve2 = filter valid . collapse . prune . choices
-- For example, for the easy grid, pruning leaves an average of around
-- 2.4 choices for each of the 81 squares, or 1027134771639091200000000
-- possible grids. A much smaller number, but still not feasible.
-- (this leaves 10^24 grids, which is an improvement over the original
-- solve function which had 9^51 grids).
-- Repeatedly pruning
---------------------
-- After pruning, there may now be new single entries, for which pruning
-- again may further reduce the search space. More generally, we can
-- iterate the pruning process until this has no further effect, which
-- in mathematical terms means that we have found a "fixpoint". The
-- simplest Sudoku puzzles can be solved in this way.
solve3 :: Grid -> [Grid]
solve3 = filter valid . collapse . fix prune . choices
fix :: Eq a => (a -> a) -> a -> a
fix f x = if x == x' then x else fix f x'
where x' = f x
-- For example, for our easy grid, the pruning process leaves precisely
-- one choice for each square, and solve3 terminates immediately. However,
-- for the gentle grid we still get around 2.8 choices for each square, or
-- 154070215745863680000000000000 possible grids.
-- Back to the drawing board...
-- Properties of matrices
--------------------------
-- In this section we introduce a number of properties that may hold of
-- a matrix of choices. First of all, let us say that such a matrix is
-- "complete" if each square contains a single choice:
complete :: Matrix Choices -> Bool
complete = all (all single)
-- Similarly, a matrix is "void" if some square contains no choices:
void :: Matrix Choices -> Bool
void = any (any null)
-- In turn, we use the term "safe" for matrix for which all rows,
-- columns and boxes are consistent, in the sense that they do not
-- contain more than one occurrence of the same single choice:
safe :: Matrix Choices -> Bool
safe cm = all consistent (rows cm) &&
all consistent (cols cm) &&
all consistent (boxs cm)
consistent :: Row Choices -> Bool
consistent = nodups . concat . filter single
-- Finally, a matrix is "blocked" if it is void or unsafe:
blocked :: Matrix Choices -> Bool
blocked m = void m || not (safe m)
-- Making choices one at a time
--------------------------------
-- Clearly, a blocked matrix cannot lead to a solution. However, our
-- previous solver does not take account of this. More importantly,
-- a choice that leads to a blocked matrix can be duplicated many
-- times by the collapse function, because this function simply
-- considers all possible combinations of choices. This is the
-- primary source of inefficiency in our previous solver.
-- This problem can be addressed by expanding choices one square at
-- a time, and filtering out any resulting matrices that are blocked
-- before considering any further choices. Implementing this idea
-- is straightforward, and gives our final Sudoku solver:
solve4 :: Grid -> [Grid]
solve4 = search . prune . choices
search :: Matrix Choices -> [Grid]
search m
| blocked m = []
| complete m = collapse m
| otherwise = [g | m' <- expand m,
g <- search (prune m')]
-- The function expand behaves in the same way as collapse, except that
-- it only collapses the first square with more than one choice:
expand :: Matrix Choices -> [Matrix Choices]
expand m =
[rows1 ++ [row1 ++ [c] : row2] ++ rows2 | c <- cs]
where
(rows1,row:rows2) = break (any (not . single)) m
(row1,cs:row2) = break (not . single) row
-- Note that there is no longer any need to check for valid grids at
-- the end, because the process by which solutions are constructed
-- guarantees that this will always be the case. There also doesn't
-- seem to be any benefit in using "fix prune" rather than "prune"
-- above; the program is faster without using fix. In fact, our
-- program now solves any newspaper Sudoku puzzle in an instant!
-- Exercise: modify the expand function to collapse a square with the
-- smallest number of choices greater than one, and see what effect
-- this change has on the performance of the solver. |
<?php
namespace App\Http\Controllers;
use App\Models\Company;
use App\Models\History;
use App\Models\StockHistory;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Symfony\Component\Console\Output\ConsoleOutput;
class CompanyController extends Controller
{
public function getCompanies()
{
$companies = Company::orderBy('created_at', 'desc')->get();
return response()->json($companies,200);
}
public function addCompany(Request $request)
{
$company = new Company();
$company->name = $request->name;
$company->adresse = $request->adresse;
$company->phone_number = $request->phone_number;
$company->tax_id = $request->tax_id;
$destination="public/images/companies";
$image=$request->file('image');
$imageName=$image->getClientOriginalName();
$image->storeAs($destination,$imageName);
$company->url = $imageName;
$company->save();
History::create([
'type'=>"create",
'body'=>"The company $request->name has been created at ".Carbon::now()->toDateTimeString()."\nLocation : $request->adresse",
]);
return response()->json($company, 200);
}
public function deleteCompany($id)
{
$company = Company::find($id);
$company->delete();
History::create([
'type'=>"delete",
'body'=>"The company $company->name has been deleted at ".Carbon::now()->toDateTimeString(),
]);
return response()->json($company, 200);
}
public function updateCompany(Request $request,$id){
$company=Company::find($id);
$company->name=$request->name;
$company->phone_number=$request->phone_number;
$company->tax_id=$request->tax_id;
$company->adresse=$request->adresse;
if ($request->hasFile('image')) {
$destination="public/images/companies";
$image=$request->file('image');
$imageName=$image->getClientOriginalName();
$image->storeAs($destination,$imageName);
$company->url = $imageName;
}
$company->save();
return response()->json($company,200);
}
} |
class Monkey {
inspectedItems = 0;
constructor(items, operation, divisibleBy, ifTrue, ifFalse, withRelief = true) {
this.items = items
this.operation = operation
this.divisibleBy = divisibleBy
this.ifTrue = ifTrue
this.ifFalse = ifFalse
this.withRelief = withRelief
}
/**
* Inspect items by doing operation & dividing it by 3
* @param {number} item
* @returns number
*/
inspectItem(item) {
const updatedOp = this.operation.replace(/old/g, item).split(' ')
if (updatedOp[1] === '+') item = Number(updatedOp[0]) + Number(updatedOp[2])
if (updatedOp[1] === '*') item = Number(updatedOp[0]) * Number(updatedOp[2])
if (this.withRelief) {
/**
* Day11 prompt says 'round to nearest integer',
* but in examples, monkey 1 has item 65, which gets added 6 then divided by 3 = 23.6666...
* The nearest integer should be 24, but the example results give 23, which is floored.
*/
item = Math.floor(item / 3)
}
this.inspectedItems++
return item
}
/**
* Test item if divisible by this.divisibleBy
* @param {number} item
* @returns boolean
*/
testItem(item) {
return item % this.divisibleBy === 0
}
}
module.exports = Monkey |
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score
from sklearn.tree import DecisionTreeClassifier
def decision_tree_classification(df, dependentVar):
# Separate features (X) and target variable (y)
X = df.loc[:, df.columns != dependentVar]
y = df[dependentVar].values
# One-hot encode categorical variables
X = pd.get_dummies(X)
# Standardize features
sc = StandardScaler()
X = sc.fit_transform(X)
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=32)
# Train Decision Tree model
dtModel = DecisionTreeClassifier()
dtModel.fit(X_train, y_train)
# Predictions on the test set
y_pred = dtModel.predict(X_test)
# Evaluation metrics
cm = confusion_matrix(y_test, y_pred)
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred, average='weighted') # Use 'weighted' for multiclass
recall = recall_score(y_test, y_pred, average='weighted') # Use 'weighted' for multiclass
f1 = f1_score(y_test, y_pred, average='weighted') # Use 'weighted' for multiclass
# Return results as a dictionary
results = {
'confusion_matrix': cm,
'accuracy_score': accuracy,
'precision_score': precision,
'recall_score': recall,
'f1_score': f1
}
return results
def naive_bayes_classification(df, dependentVar):
# Separate features (X) and target variable (y)
X = df.loc[:, df.columns != dependentVar]
y = df[dependentVar].values
# One-hot encode categorical variables
X = pd.get_dummies(X)
# Standardize features
sc = StandardScaler()
X = sc.fit_transform(X)
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=32)
# Train Gaussian Naive Bayes model
nbModel = GaussianNB()
nbModel.fit(X_train, y_train)
# Predictions on the test set
y_pred = nbModel.predict(X_test)
# Evaluation metrics
cm = confusion_matrix(y_test, y_pred)
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred, average='weighted') # Use 'weighted' for multiclass
recall = recall_score(y_test, y_pred, average='weighted') # Use 'weighted' for multiclass
f1 = f1_score(y_test, y_pred, average='weighted') # Use 'weighted' for multiclass
# Return results as a dictionary
results = {
'confusion_matrix': cm,
'accuracy_score': accuracy,
'precision_score': precision,
'recall_score': recall,
'f1_score': f1
}
return results
# Example Usage
df = pd.read_csv('./cereal.csv')
dependentVar = 'protein'
classification_results = naive_bayes_classification(df, dependentVar)
print(" Naive Bayes Classification Results:")
print(classification_results)
print("-----\n")
df1 = pd.read_csv('./cereal.csv')
dependentVar = 'protein'
classification_results_dt = decision_tree_classification(df1, dependentVar)
print("Decision Tree Classification Results:")
print(classification_results_dt) |
const NavigateBack = {
name: 'PageStackNavigateBack',
displayNodeName: 'Pop Component Stack',
category: 'Navigation',
docs: 'https://docs.noodl.net/nodes/component-stack/pop-component',
inputs: {
navigate: {
displayName: 'Navigate',
group: 'Actions',
valueChangedToTrue: function () {
this.scheduleNavigate();
}
},
results: {
type: { name: 'stringlist', allowEditOnly: true },
group: 'Results',
set: function (value) {
this._internal.results = value;
}
},
backActions: {
type: { name: 'stringlist', allowEditOnly: true },
group: 'Back Actions',
set: function (value) {
this._internal.backActions = value;
}
}
},
initialize: function () {
this._internal.resultValues = {};
},
methods: {
scheduleNavigate: function () {
var _this = this;
var internal = this._internal;
if (!internal.hasScheduledNavigate) {
internal.hasScheduledNavigate = true;
this.scheduleAfterInputsHaveUpdated(function () {
internal.hasScheduledNavigate = false;
_this.navigate();
});
}
},
_setBackCallback(cb) {
this._internal.backCallback = cb;
},
navigate() {
if (this._internal.backCallback === undefined) return;
this._internal.backCallback({
backAction: this._internal.backAction,
results: this._internal.resultValues
});
},
setResultValue: function (key, value) {
this._internal.resultValues[key] = value;
},
backActionTriggered: function (name) {
this._internal.backAction = name;
this.scheduleNavigate();
},
registerInputIfNeeded: function (name) {
if (this.hasInput(name)) {
return;
}
if (name.startsWith('result-'))
return this.registerInput(name, {
set: this.setResultValue.bind(this, name.substring('result-'.length))
});
if (name.startsWith('backAction-'))
return this.registerInput(name, {
set: _createSignal({
valueChangedToTrue: this.backActionTriggered.bind(this, name)
})
});
}
}
};
function setup(context, graphModel) {
if (!context.editorConnection || !context.editorConnection.isRunningLocally()) {
return;
}
function _managePortsForNode(node) {
function _updatePorts() {
var ports = [];
// Add results inputs
var results = node.parameters.results;
if (results) {
results = results ? results.split(',') : undefined;
for (var i in results) {
var p = results[i];
ports.push({
type: {
name: '*'
},
plug: 'input',
group: 'Results',
name: 'result-' + p,
displayName: p
});
}
}
// Add back actions
var backActions = node.parameters.backActions;
if (backActions) {
backActions = backActions ? backActions.split(',') : undefined;
for (var i in backActions) {
var p = backActions[i];
ports.push({
type: 'signal',
plug: 'input',
group: 'Back Actions',
name: 'backAction-' + p,
displayName: p
});
}
}
context.editorConnection.sendDynamicPorts(node.id, ports);
}
_updatePorts();
node.on('parameterUpdated', function (event) {
if (event.name === 'results' || event.name === 'backActions') {
_updatePorts();
}
});
}
graphModel.on('editorImportComplete', () => {
graphModel.on('nodeAdded.PageStackNavigateBack', function (node) {
_managePortsForNode(node);
});
for (const node of graphModel.getNodesWithType('PageStackNavigateBack')) {
_managePortsForNode(node);
}
});
}
module.exports = {
node: NavigateBack,
setup: setup
}; |
import { useEffect } from 'react';
import { MoonLoader } from 'react-spinners';
import { useAuth } from 'contexts/AuthContext';
import { useTweets } from 'contexts/TweetsContext';
import TweetHeader from 'users/components/TweetHeader/TweetHeader';
import TweetList from 'users/components/TweetList/TweetList';
import TweetPost from 'users/components/TweetPost/TweetPost';
import styles from 'users/pages/Home.module.scss';
function UserTweet() {
const { tweets, fetchTweets, isLoading } = useTweets();
const { currentUser } = useAuth();
// fetchTweets when user logs in
useEffect(() => {
const authToken = localStorage.getItem('authToken');
if (authToken && tweets.length === 0) {
fetchTweets();
}
}, [fetchTweets, tweets.length]);
return (
<div className={styles.tweet}>
<TweetHeader label="首頁" />
<TweetPost
placeholder="有什麼新鮮事嗎?"
userId={currentUser?.id}
image={currentUser?.avatar}
/>
{!isLoading ? (
<TweetList listType="homeTweets" listItems={tweets} />
) : undefined}
<MoonLoader
color="#FF974A"
loading={isLoading}
speedMultiplier={1}
cssOverride={{
margin: '0 auto',
position: 'relative',
top: '25%',
}}
/>
</div>
);
}
export default UserTweet; |
@if $toc {
/* - Example__________________ITCSS examples (image, url, detail, favorite button) styles */
} @else {
/* Example (component)
/**
* @note We assume that the default font-size is 16px
*/
.c-example {
position: relative;
}
.c-example__img {
display: block;
text-align: center;
}
.c-example__detail {
position: absolute;
right: 0;
bottom: 0;
left: 0;
padding: em(12, 14) em(18, 14); // 12px 18px
font-size: rem(14); // 14px
color: #fff;
background-color: #3d3d3d;
}
.c-example__url:hover,
.c-example__url:focus {
color: #ffae00;
color: var(--example__url-focus-hover-txt);
}
// Add - Withdraw favorite button
.c-example__favorite {
position: absolute;
top: rem(10); // 10px
right: rem(10); // 10px
border: 0;
padding: 0;
background: none;
cursor: pointer;
}
.c-example__favorite:hover {
filter: brightness(100%) sepia(100) saturate(50) hue-rotate(-50deg);
}
.c-example__favorite:focus {
outline: 1px dotted rgba(#fff, 0.5);
outline-offset: 0.25em;
background-color: rgba(#fff, 0.1);
}
} |
/* eslint-disable @typescript-eslint/no-unsafe-call */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
import { NoopScrollStrategy } from '@angular/cdk/overlay';
import { CommonModule } from '@angular/common';
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { MatchesApiService, Status } from '@components/home/components/matches/api/matches-api.service';
import { NoMoreLikesDialogComponent } from '@components/home/components/matches/components/match/components/no-more-likes-dialog/no-more-likes-dialog.component';
import { Match } from '@components/home/components/matches/components/match/interfaces/match-interface';
import { MouseActionsComponent } from '@components/home/components/matches/components/mouse-actions/mouse-actions.component';
import { MatchesService } from '@components/home/components/matches/service/matches.service';
import { LoadingComponent } from '@shared/components/loading/loading.component';
import { MatchImageComponent } from '@shared/components/match-image/match-image.component';
import { MoreInfoComponent } from '@shared/components/more-info/more-info.component';
import { OperatorFunction, SchedulerLike, async, concat, publish, take } from 'rxjs';
import { BehaviorSubject } from 'rxjs/internal/BehaviorSubject';
import { Observable } from 'rxjs/internal/Observable';
import { debounceTime } from 'rxjs/internal/operators/debounceTime';
import { filter } from 'rxjs/internal/operators/filter';
import { switchMap } from 'rxjs/internal/operators/switchMap';
import { tap } from 'rxjs/internal/operators/tap';
@Component({
selector: 'match',
standalone: true,
imports: [CommonModule, MatIconModule, LoadingComponent, MouseActionsComponent, MoreInfoComponent, MatchImageComponent, MatDialogModule],
providers: [MatchesApiService],
templateUrl: './match.component.html',
styleUrls: ['./match.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MatchComponent implements OnInit {
currentMatch$: Observable<Match>;
expanded$: Observable<boolean>;
isLoaded$ = new BehaviorSubject<boolean>(false);
swipeAction$ = new BehaviorSubject<Status>(null);
constructor(
private matchesService: MatchesService,
private matchesApiService: MatchesApiService,
private dialog: MatDialog,
) { }
ngOnInit(): void {
this.currentMatch$ = this.matchesService.getMatchSwipeListener().pipe(
debounceTimeAfterFirst(1230),
switchMap((res) => this.matchesApiService.getNewMatch(res)),
tap((res) => {
if (res?.showLikesDialog) {
const classToAdd = res.showLikesDialog === 'Like' ? 'dialog-background-like' : 'dialog-background-superLike';
this.dialog.open(NoMoreLikesDialogComponent, {
data: res.showLikesDialog,
panelClass: ['move-dialog', classToAdd],
width: '375px',
autoFocus: false,
scrollStrategy: new NoopScrollStrategy(),
});
}
}),
tap(() => this.matchesService.forceSetCurrentImageIndex(0)),
tap(() => this.isLoaded$.next(true)),
tap((res) => res && this.matchesService.setImagesCount(res.images.length))
);
this.matchesService.getMatchSwipeListener().pipe(
filter((res) => res !== null),
).subscribe((res) => {
this.swipeAction$.next(res);
setTimeout(() => {
this.isLoaded$.next(false);
}, 850);
setTimeout(() => {
this.swipeAction$.next(null);
}, 1250);
});
this.expanded$ = this.matchesService.getProfileClosedListener();
}
}
export function debounceTimeAfter(amount: number, dueTime: number, scheduler: SchedulerLike = async): OperatorFunction<number, number> {
return publish((value) => concat(value.pipe(take(amount)), value.pipe(debounceTime(dueTime, scheduler))),);
}
export function debounceTimeAfterFirst(dueTime: number, scheduler: SchedulerLike = async): OperatorFunction<number, number> {
return debounceTimeAfter(1, dueTime, scheduler);
} |
<?php
namespace Drupal\domain_role\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\user\RoleInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
/**
* Class DomainRoleConfigForm.
*/
class DomainRoleConfigForm extends ConfigFormBase {
/**
* Drupal\Core\Entity\EntityTypeManagerInterface definition.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs a new DomainRoleConfigForm object.
*/
public function __construct(
ConfigFactoryInterface $config_factory,
EntityTypeManagerInterface $entity_type_manager
) {
parent::__construct($config_factory);
$this->entityTypeManager = $entity_type_manager;
}
public static function create(ContainerInterface $container) {
return new static(
$container->get('config.factory'),
$container->get('entity_type.manager')
);
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return [
'domain_role.roles',
];
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'domain_role_config_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$roles_storage = $this->entityTypeManager->getStorage('user_role');
$all_roles = $roles_storage->loadMultiple();
// No configuration entities for authenticated or anonymous users, so unset those.
unset($all_roles[RoleInterface::ANONYMOUS_ID]);
unset($all_roles[RoleInterface::AUTHENTICATED_ID]);
$all_roles = array_map(function ($item) {
return $item->label();
}, $all_roles);
$config = $this->config('domain_role.roles');
$form['domain_roles'] = [
'#type' => 'checkboxes',
'#title' => $this->t('Roles to apply per domain'),
'#description' => $this->t('Select roles that should be applied per domain.'),
'#options' => $all_roles,
'#default_value' => $config->get('domain_roles'),
];
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
parent::validateForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
parent::submitForm($form, $form_state);
$domain_roles = array_filter($form_state->getValue('domain_roles'));
$this->config('domain_role.roles')
->set('domain_roles', $domain_roles)
->save();
$domains = $this->entityTypeManager->getStorage('domain')->loadMultiple();
foreach($domain_roles as $domain_role) {
foreach($domains as $domain_id => $domain) {
$config = $this->configFactory()
->getEditable('domain.config.' . $domain_id . '.user.role.' . $domain_role);
$config->set('name', $domain_id . '-' . $domain_role)
->set('label', $domain->label() . ' '. $domain_role)
->set('id', $domain_role)
->save();
}
}
}
} |
<?php
namespace Core\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
class CreateResourceFactory extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'create:resource-factory {name} {context}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command: php artisan create:resource-factory {factory-name} {context-name}';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$ds = DIRECTORY_SEPARATOR;
$application_path = config('app.layers.application');
$context = $this->argument('context');
$factory_name = $this->argument('name');
$stub_path = config('app.layers.core')."Stubs{$ds}ResourceFactory.stub";
$factoriesDirectory = $application_path.$context.$ds.'Http'.$ds.'ResourceFactories';
$filePath = $factoriesDirectory.$ds.$factory_name.'.php';
try {
$content = File::get($stub_path);
$content = str_replace('{{factory_name}}', $factory_name,
str_replace('{{context}}', $context, $content));
if(!File::isDirectory($factoriesDirectory)) {
File::makeDirectory($factoriesDirectory);
}
File::put($filePath, $content);
} catch(Throwable $e) {
$this->info($e->getMessage());
}
$this->info($factory_name.' criado com sucesso!');
return 0;
}
} |
package fun.mousewich.effect;
import net.minecraft.entity.attribute.EntityAttributeModifier;
import net.minecraft.entity.attribute.EntityAttributes;
import net.minecraft.entity.effect.StatusEffect;
import net.minecraft.entity.effect.StatusEffectCategory;
import java.util.List;
import static fun.mousewich.ModBase.EN_US;
import static fun.mousewich.registry.ModRegistry.Register;
public class ModStatusEffects {
public static final StatusEffect BOO = new ModStatusEffect(StatusEffectCategory.NEUTRAL,0xBE331F);
public static final StatusEffect DARKNESS = new ModStatusEffect(StatusEffectCategory.HARMFUL, 2696993); //Minecraft 1.19
public static final StatusEffect BLEEDING = new BleedingEffect().milkImmune();
public static final StatusEffect DENSE_BREW = new ModStatusEffect(StatusEffectCategory.BENEFICIAL, 0x676767)
.addAttributeModifier(EntityAttributes.GENERIC_KNOCKBACK_RESISTANCE, "AF8B6E3F-3328-4C0A-AA36-5BA2BB9DBEF5",
0.5f, EntityAttributeModifier.Operation.MULTIPLY_TOTAL)
.addAttributeModifier(EntityAttributes.GENERIC_ARMOR, "AF8B6E3F-3328-4C0A-AA36-5BA2BB9DBEF6",
1, EntityAttributeModifier.Operation.ADDITION); //Minecraft Dungeons
public static final StatusEffect FLASHBANGED = new ModStatusEffect(StatusEffectCategory.HARMFUL, 0xFFFFFF);
public static final StatusEffect FREEZING_RESISTANCE = new ModStatusEffect(StatusEffectCategory.BENEFICIAL, 14981690); //Minecraft Dungeons
public static final StatusEffect FRENZIED = new ModStatusEffect(StatusEffectCategory.BENEFICIAL, 0xBE371F)
.addAttributeModifier(EntityAttributes.GENERIC_MOVEMENT_SPEED, "AF8B6E3F-3328-4C0A-AA36-5BA2BB9DBEF4",
0.1f, EntityAttributeModifier.Operation.MULTIPLY_TOTAL); //Minecraft Dungeons
public static final StatusEffect KILLJOY = new ModStatusEffect(StatusEffectCategory.NEUTRAL,0x1F8B33);
public static final StatusEffect SILENT = new ModStatusEffect(StatusEffectCategory.NEUTRAL, 0x7F7F7F);
public static final StatusEffect STICKY = new StickyEffect();
//Goggles
public static final StatusEffect RUBY_GOGGLES = new GogglesEffect(0xA00A34).milkImmune();
public static final StatusEffect TINTED_GOGGLES = new GogglesEffect(0x6F4FAB).milkImmune();
public static void RegisterEffects() {
Register("flashbanged", FLASHBANGED, List.of(EN_US.Flashbanged()));
Register("freezing_resistance", FREEZING_RESISTANCE, List.of(EN_US.Resistance(EN_US.Freezing())));
Register("frenzied", FRENZIED, List.of(EN_US.Frenzied()));
Register("bleeding", BLEEDING, List.of(EN_US.Bleeding()));
Register("silent", SILENT, List.of(EN_US.Silent()));
Register("sticky", STICKY, List.of(EN_US.Sticky()));
//Throwable Tomato
Register("boo", BOO, List.of(EN_US.Boo()));
Register("killjoy", KILLJOY, List.of(EN_US.Killjoy()));
//Goggles
Register("tinted_goggles", TINTED_GOGGLES, List.of(EN_US.Goggles(EN_US.Tinted())));
Register("ruby_goggles", RUBY_GOGGLES, List.of(EN_US.Goggles(EN_US.Ruby())));
//Minecraft
Register("minecraft:darkness", DARKNESS, List.of(EN_US.Darkness())); //1.19
Register("dense_brew", DENSE_BREW, List.of(EN_US.Brew(EN_US.Dense()))); //Dungeons
}
} |
-- What is the type of (,)? When you use it in ghci, what does it do? What about
-- (,,)?
-- (,) is a 2-tuple data constructor
ghci> :t (,)
(,) :: a -> b -> (a, b)
ghci> (,) 1 2
(1,2)
ghci> t = (,) 1
ghci> :t t
t :: Num a => b -> (a, b)
ghci> t 2
(1,2)
-- (,,) is a 3-tuple data constructor
ghci> :t (,,)
(,,) :: a -> b -> c -> (a, b, c)
ghci> (,,) 1 2 3
(1,2,3)
ghci> t = (,,) 1
ghci> :t t
t :: Num a => b -> c -> (a, b, c)
ghci> u = t 2
ghci> :t u
u :: (Num a, Num b) => c -> (a, b, c)
ghci> u 3
(1,2,3) |
#include <vector>
#include <string>
class MapSum {
public:
MapSum() {}
struct TrieNode {
int value = 0;
TrieNode* child[26] = {nullptr};
};
void insert(std::string key, int val) {
TrieNode* curr = root_;
for (char& c : key) {
if (curr->child[c - 'a'] == nullptr) {
curr->child[c - 'a'] = new TrieNode();
}
curr = curr->child[c - 'a'];
}
curr->value = val;
}
int sum(std::string prefix) {
TrieNode* curr = root_;
for (char& c : prefix) {
curr = curr->child[c - 'a'];
if (curr == nullptr) break;
}
return sum(curr);
}
int sum(TrieNode* node) {
if (node == nullptr) return 0;
int total = node->value;
for (TrieNode* n : node->child) {
total += sum(n);
}
return total;
}
private:
TrieNode* root_ = new TrieNode();
};
/**
* Your MapSum object will be instantiated and called as such:
* MapSum* obj = new MapSum();
* obj->insert(key,val);
* int param_2 = obj->sum(prefix);
*/ |
import { getAuthSession } from "@/lib/auth";
import { db } from "@/lib/db";
import { PinValidator } from "@/lib/validators/pin";
import { z } from "zod";
export async function POST(req: Request) {
try {
const session = await getAuthSession();
if (!session?.user) {
return new Response("Unauthorized", { status: 401 });
}
const body = await req.json();
const { title, description, image } = PinValidator.parse(body);
await db.pin.create({
data: {
title,
description,
userId: session.user.id,
image,
},
});
return new Response("OK");
} catch (error) {
if (error instanceof z.ZodError) {
return new Response("Invalid request data passed", { status: 422 });
}
return new Response(
"Could not post the pin at this time, please try again later.",
{
status: 500,
},
);
}
} |
##DESCRIPTION
## insert description here
##ENDDESCRIPTION
## DBsubject(Electricity)
## DBchapter(Electric Current, Resistance, and Ohm's Law)
## DBsection(Current)
## Date(2 January 2018)
## Institution(Brock University)
## Author(Kyle Winch)
## Edited (Sara Hesse, May 29 2018)
## TitleText('College Physics')
## AuthorText('Urone et al')
## EditionText('2017')
## Section('20.1')
## Problem('011')
## KEYWORDS('charge','electron','current')
DOCUMENT();
loadMacros( "PGbasicmacros.pl",
"MathObjects.pl",
"PGauxiliaryFunctions.pl",
"PGchoicemacros.pl",
"PGanswermacros.pl",
"PG_CAPAmacros.pl",
"BrockPhysicsMacros.pl",
"answerHints.pl"
);
TEXT(beginproblem());
$showPartialCorrectAnswers = 1;
$showHint = 3;
$C = random(950,1050,10);
$I = $C/(1.6*10**(-19));
$E = (6.02*10**23)/$I;
BEGIN_TEXT
<strong>If you don't solve this problem correctly in $showHint tries, you can get a hint.</strong>
$PAR
The batteries of a submerged non-nuclear submarine supply \($C \, \(\textrm{A}\) at full speed ahead. How long does it take to move Avogadro's number ( \(6.02 \times 10^{23}\) ) of electrons at this rate?
$PAR
\{ans_rule(40)\} \(\textrm{s}\)
$PAR
END_TEXT
ANS(num_cmp("$E"));
BEGIN_HINT
What charge would be produce by Avogadro's number of electrons.
END_HINT
Context()->normalStrings;
ENDDOCUMENT() |
# frozen_string_literal: true
module Api
module V1
class EntriesController < ApplicationController
before_action :set_default_response_format
def show
@entry = Entry.find(params[:id])
end
def popular
@entries = Entry.includes(:site, :tags).where(total_count: 1..).a_day_ago.order(total_count: :desc).limit(25)
end
def latest
@entries = Entry.includes(:site, :tags).order(published_at: :desc).limit(30)
end
def search
tag = params[:query]
@entries = Entry.includes(:site, :tags).tagged_with(tag).order(published_at: :desc).limit(25)
end
def similar
@entry = Entry.find_by(url: params[:url])
@entries = Entry.tagged_with(@entry.tags, any: true).order(published_at: :desc).limit(25) if @entry.present?
end
private
def set_default_response_format
request.format = :json
end
end
end
end |
package vn.ztech.software.ecomSeller.ui.category
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.*
import androidx.fragment.app.Fragment
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.appcompat.widget.PopupMenu
import androidx.core.os.bundleOf
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel
import vn.ztech.software.ecomSeller.R
import vn.ztech.software.ecomSeller.common.StoreDataStatus
import vn.ztech.software.ecomSeller.databinding.FragmentListProductsInCategoryBinding
import vn.ztech.software.ecomSeller.exception.RefreshTokenExpiredException
import vn.ztech.software.ecomSeller.model.Category
import vn.ztech.software.ecomSeller.model.Product
import vn.ztech.software.ecomSeller.ui.MyOnFocusChangeListener
import vn.ztech.software.ecomSeller.ui.auth.LoginSignupActivity
import vn.ztech.software.ecomSeller.ui.common.ItemDecorationRecyclerViewPadding
import vn.ztech.software.ecomSeller.ui.product.ListProductsAdapter
import vn.ztech.software.ecomSeller.ui.product.ProductViewModel
import vn.ztech.software.ecomSeller.ui.splash.ISplashUseCase
import vn.ztech.software.ecomSeller.util.CustomError
import vn.ztech.software.ecomSeller.util.extension.showErrorDialog
open class ListProductsInCategoryFragment : Fragment() {
private lateinit var binding: FragmentListProductsInCategoryBinding
private val viewModel: CategoryViewModel by viewModel()
private val productViewModel: ProductViewModel by sharedViewModel()
private lateinit var listProductsAdapter: ListProductsAdapter
protected val focusChangeListener = MyOnFocusChangeListener()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.takeIf { it.containsKey("category") }?.let {
viewModel.currentSelectedCategory.value = arguments!!.getParcelable<Category>("category")
}
if (viewModel.products.value == null) viewModel.getProductsInCategory()
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
binding = FragmentListProductsInCategoryBinding.inflate(layoutInflater)
setViews()
setObservers()
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.swipeRefresh.setOnRefreshListener {
viewModel.existed = false
viewModel.getProductsInCategory()
}
}
private fun setViews() {
binding.cateAppBar.topAppBar.title = viewModel.currentSelectedCategory.value?.name?:"List product in category"
binding.cateAppBar.topAppBar.setNavigationOnClickListener {
findNavController().navigateUp()
}
setHomeTopAppBar()
if (context != null) {
setUpProductAdapter()
}
binding.homeFabAddProduct.setOnClickListener {
findNavController().navigate(R.id.action_listProductsInCategoryFragment_to_addEditProductFragment)
}
binding.loaderLayout.loaderFrameLayout.visibility = View.VISIBLE
binding.loaderLayout.circularLoader.showAnimationBehavior
}
@SuppressLint("NotifyDataSetChanged")
private fun setObservers() {
viewModel.storeDataStatus.observe(viewLifecycleOwner) { status ->
if(status == StoreDataStatus.LOADING) {
binding.loaderLayout.loaderFrameLayout.visibility = View.VISIBLE
binding.loaderLayout.circularLoader.showAnimationBehavior
}else{
binding.loaderLayout.circularLoader.hideAnimationBehavior
binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
binding.swipeRefresh.isRefreshing = false
}
}
viewLifecycleOwner.lifecycleScope.launch {
viewModel.products.observe(viewLifecycleOwner) { listProducts ->
listProducts?.let {
binding.productsRecyclerView.adapter?.apply {
listProductsAdapter.submitData(lifecycle, listProducts)
}
}
}
}
// viewModel.allProducts.observe(viewLifecycleOwner) { listProducts->
// listProducts?.let{
// if (listProducts.isEmpty()) {
// binding.tvNoProductFound.visibility = View.VISIBLE
// binding.productsRecyclerView.visibility = View.GONE
// }else {
// binding.tvNoProductFound.visibility = View.GONE
// binding.loaderLayout.circularLoader.hideAnimationBehavior
// binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
// binding.productsRecyclerView.visibility = View.VISIBLE
// binding.productsRecyclerView.adapter?.apply {
// listProductsAdapter.data =
// getMixedDataList(listProducts, getAdsList())
// notifyDataSetChanged()
// }
// }
// }
// if (listProducts==null){
// binding.loaderLayout.circularLoader.hideAnimationBehavior
// binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
// binding.productsRecyclerView.visibility = View.GONE
// binding.tvNoProductFound.visibility = View.VISIBLE
// }
// }
viewModel.productViewModel.deletedProductStatus.observe(viewLifecycleOwner){
it?.let {
Toast.makeText(requireContext(), "Delete product successfully!", Toast.LENGTH_LONG).apply {
setGravity(Gravity.CENTER, 0, 0)
}.show()
viewModel.productViewModel.deletedProductStatus.value = null
viewModel.getProductsInCategory()
}
}
viewModel.error.observe(viewLifecycleOwner){
it ?: return@observe
handleError(it)
}
}
fun handleError(error: CustomError){
if(error is RefreshTokenExpiredException){
openLogInSignUpActivity(ISplashUseCase.PAGE.LOGIN)
}else{
showErrorDialog(error)
}
}
fun openLogInSignUpActivity(page: ISplashUseCase.PAGE){
val intent = Intent(activity, LoginSignupActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK
intent.putExtra("PAGE", page)
startActivity(intent)
activity?.finish()
}
private fun setHomeTopAppBar() {
val inputManager = requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputManager.hideSoftInputFromWindow(activity?.currentFocus?.windowToken, 0)
var lastInput = ""
// val debounceJob: Job? = null
// val uiScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
// binding.homeTopAppBar.topAppBar.inflateMenu(R.menu.home_app_bar_menu)
binding.homeTopAppBar.homeSearchEditText.onFocusChangeListener = focusChangeListener
// binding.homeTopAppBar.homeSearchEditText.doAfterTextChanged { editable ->
// if (editable != null) {
// val newtInput = editable.toString()
// debounceJob?.cancel()
// if (lastInput != newtInput) {
// lastInput = newtInput
// uiScope.launch {
// delay(500)
// if (lastInput == newtInput) {
// performSearch(newtInput)
// }
// }
// }
// }
// }
binding.homeTopAppBar.homeSearchEditText.setOnEditorActionListener { textView, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
textView.clearFocus()
val inputManager =
requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputManager.hideSoftInputFromWindow(textView.windowToken, 0)
performSearch(textView.text.toString())
true
} else {
false
}
}
binding.homeTopAppBar.searchOutlinedTextLayout.setEndIconOnClickListener {
Log.d("SEARCH", "setEndIconOnClickListener")
it.clearFocus()
binding.homeTopAppBar.homeSearchEditText.setText("")
val inputManager =
requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputManager.hideSoftInputFromWindow(it.windowToken, 0)
}
binding.homeTopAppBar.searchOutlinedTextLayout.setStartIconOnClickListener {
it.clearFocus()
val inputManager =
requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputManager.hideSoftInputFromWindow(it.windowToken, 0)
performSearch(binding.homeTopAppBar.searchOutlinedTextLayout.editText?.text.toString())
}
}
private fun performSearch(searchWords: String) {
viewModel.searchProductsInCategory(searchWords)
}
private fun setUpProductAdapter() {
listProductsAdapter = ListProductsAdapter(requireContext())
listProductsAdapter.onClickListener = object : ListProductsAdapter.OnClickListener {
override fun onClickAdvancedActionsButton(view: View, productData: Product) {
showPopup(view, productData)
}
override fun onEditClick(productData: Product) {
findNavController().navigate(
R.id.action_listProductsInCategoryFragment_to_quickEditProductFragment,
bundleOf(
"product" to productData
)
)
}
override fun onProductClicked(productId: String) {
findNavController().navigate(
R.id.action_listProductsInCategoryFragment_to_productDetailsFragment,
bundleOf(
"productId" to productId
)
)
}
}
listProductsAdapter.stateRestorationPolicy = RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY
binding.productsRecyclerView.adapter = listProductsAdapter
listProductsAdapter.addLoadStateListener {loadState->
// show empty list
if (loadState.refresh is androidx.paging.LoadState.Loading ||
loadState.append is androidx.paging.LoadState.Loading){
if(!viewModel.existed){
binding.loaderLayout.circularLoader.showAnimationBehavior
binding.loaderLayout.loaderFrameLayout.visibility = View.VISIBLE
}
}
else {
binding.loaderLayout.circularLoader.hideAnimationBehavior
binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
if (listProductsAdapter.itemCount == 0){
binding.tvNoProductFound.visibility = View.VISIBLE
binding.productsRecyclerView.visibility = View.GONE
}else{
binding.tvNoProductFound.visibility = View.GONE
binding.productsRecyclerView.visibility = View.VISIBLE
}
// If we have an error, show a toast
val errorState = when {
loadState.append is androidx.paging.LoadState.Error -> loadState.append as androidx.paging.LoadState.Error
loadState.prepend is androidx.paging.LoadState.Error -> loadState.prepend as androidx.paging.LoadState.Error
loadState.refresh is androidx.paging.LoadState.Error -> loadState.refresh as androidx.paging.LoadState.Error
else -> null
}
errorState?.let {
handleError(CustomError(it.error, it.error.message?:"System error"))
}
}
}
}
private fun showPopup(view: View, productData: Product) {
val popup = PopupMenu(requireContext(), view).apply {
setOnMenuItemClickListener {
when(it.itemId){
R.id.actionFullEdit -> {
editProduct(productData)
true
}
R.id.actionForkProduct -> {
forkProduct(productData)
true
}
R.id.actionDelete -> {
deleteProduct(productData)
true
}
else -> {false}
}
}
inflate(R.menu.advanced_action_product_menu)
show()
}
}
private fun forkProduct(productData: Product) {
findNavController().navigate(
R.id.action_listProductsInCategoryFragment_to_addEditProductFragment,
bundleOf(
"product" to productData,
"editType" to "forkProduct"
)
)
}
private fun editProduct(productData: Product) {
findNavController().navigate(
R.id.action_listProductsInCategoryFragment_to_addEditProductFragment,
bundleOf(
"product" to productData,
"editType" to "fullEdit"
)
)
}
private fun deleteProduct(productData: Product) {
showDeleteDialog(productData._id)
}
private fun showDeleteDialog(productId: String) {
context?.let {
MaterialAlertDialogBuilder(it)
.setTitle(getString(R.string.delete_dialog_title_text))
.setMessage(getString(R.string.delete_product_message_text))
.setNeutralButton(getString(R.string.pro_cat_dialog_cancel_btn)) { dialog, _ ->
dialog.cancel()
}
.setPositiveButton(getString(R.string.delete_dialog_delete_btn_text)) { dialog, _ ->
viewModel.productViewModel.deleteProduct(productId)
dialog.cancel()
}
.show()
}
}
private fun getMixedDataList(data: List<Product>, adsList: List<Int>): List<Any> {
val itemsList = mutableListOf<Any>()
itemsList.addAll(data.sortedBy { it._id })
var currPos = 0
if (itemsList.size >= 4) {
adsList.forEach label@{ ad ->
if (itemsList.size > currPos + 1) {
itemsList.add(currPos, ad)
} else {
return@label
}
currPos += 5
}
}
return itemsList
}
private fun getAdsList(): List<Int> {
//feature: for now, ad is not supported
return listOf()
}
override fun onResume() {
super.onResume()
viewModel.productViewModel.clearSelected()
productViewModel.clearSelected()
if (viewModel.existed) {
listProductsAdapter.refresh()
}
}
override fun onPause() {
super.onPause()
viewModel.existed = true
}
override fun onStop() {
super.onStop()
viewModel.clearErrors()
productViewModel.clearErrors()
}
// private lateinit var binding: FragmentListProductsInCategoryBinding
// private val viewModel: CategoryViewModel by viewModel()
// private lateinit var listProductsAdapter: ListProductsAdapter
// protected val focusChangeListener = MyOnFocusChangeListener()
//
// override fun onCreateView(
// inflater: LayoutInflater, container: ViewGroup?,
// savedInstanceState: Bundle?
// ): View {
// // Inflate the layout for this fragment
// binding = FragmentListProductsInCategoryBinding.inflate(layoutInflater)
// setViews()
// setObservers()
// return binding.root
// }
//
// override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// super.onViewCreated(view, savedInstanceState)
// val category = arguments?.getParcelable("category") as Category?
// Log.d("LIST", category.toString())
// viewModel.currentSelectedCategory.value = category
//
// viewModel.getProductsInCategory()
// binding.swipeRefresh.setOnRefreshListener {
// viewModel.getProductsInCategory()
// }
// }
//
// private fun setViews() {
// setHomeTopAppBar()
// if (context != null) {
// setUpProductAdapter()
// binding.productsRecyclerView.apply {
// val gridLayoutManager = GridLayoutManager(context, 2)
// gridLayoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
// override fun getSpanSize(position: Int): Int {
// return when (listProductsAdapter.getItemViewType(position)) {
// 2 -> 2 //ad
// else -> {
// 1
// }
// }
// }
// }
// layoutManager = gridLayoutManager
// adapter = listProductsAdapter
// val itemDecoration = ItemDecorationRecyclerViewPadding()
// if (itemDecorationCount == 0) {
// addItemDecoration(itemDecoration)
// }
// }
// }
// //feature: this will be add when the app supports seller.
//// if (!viewModel.isUserASeller) {
//// binding.homeFabAddProduct.visibility = View.GONE
//// }
//// binding.homeFabAddProduct.setOnClickListener {
//// showDialogWithItems(ProductCategories, 0, false)
//// }
// binding.loaderLayout.loaderFrameLayout.visibility = View.VISIBLE
// binding.loaderLayout.circularLoader.showAnimationBehavior
// }
//
// @SuppressLint("NotifyDataSetChanged")
// private fun setObservers() {
// viewModel.storeDataStatus.observe(viewLifecycleOwner) { status ->
// if(status == StoreDataStatus.LOADING) {
// binding.loaderLayout.loaderFrameLayout.visibility = View.VISIBLE
// binding.loaderLayout.circularLoader.showAnimationBehavior
// binding.productsRecyclerView.visibility = View.GONE
// }else{
// binding.loaderLayout.circularLoader.hideAnimationBehavior
// binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
// binding.swipeRefresh.isRefreshing = false
// }
// }
// viewModel.error.observe(viewLifecycleOwner) {
// it?.let {
// Log.d("ERROR:","viewModel.searchError: $it")
// showErrorDialog(it)
// }
// }
// viewLifecycleOwner.lifecycleScope.launch {
// viewModel.products.observe(viewLifecycleOwner) { products ->
// products?.let {
// binding.productsRecyclerView.adapter?.apply {
// listProductsAdapter.submitData(lifecycle, products)
// }
// }
// }
// }
//// viewModel.products.observe(viewLifecycleOwner) { listProducts->
//// if (listProducts.isNotEmpty()) {
//// binding.tvNoProductFound.visibility = View.GONE
//// binding.loaderLayout.circularLoader.hideAnimationBehavior
//// binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
//// binding.productsRecyclerView.visibility = View.VISIBLE
//// binding.productsRecyclerView.adapter?.apply {
//// listProductsAdapter.data =
//// getMixedDataList(listProducts, getAdsList())
//// notifyDataSetChanged()
//// }
//// }else{
//// binding.tvNoProductFound.visibility = View.VISIBLE
//// }
//// }
// }
//
// private fun setHomeTopAppBar() {
// var lastInput = ""
// binding.homeTopAppBar.topAppBar.setNavigationOnClickListener {
// findNavController().navigateUp()
// }
//// val debounceJob: Job? = null
//// val uiScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
//// binding.homeTopAppBar.topAppBar.inflateMenu(R.menu.home_app_bar_menu)
// binding.homeTopAppBar.homeSearchEditText.onFocusChangeListener = focusChangeListener
//// binding.homeTopAppBar.homeSearchEditText.doAfterTextChanged { editable ->
//// if (editable != null) {
//// val newtInput = editable.toString()
//// debounceJob?.cancel()
//// if (lastInput != newtInput) {
//// lastInput = newtInput
//// uiScope.launch {
//// delay(500)
//// if (lastInput == newtInput) {
//// performSearch(newtInput)
//// }
//// }
//// }
//// }
//// }
// binding.homeTopAppBar.homeSearchEditText.setOnEditorActionListener { textView, actionId, _ ->
// if (actionId == EditorInfo.IME_ACTION_SEARCH) {
// textView.clearFocus()
// val inputManager = requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
// inputManager.hideSoftInputFromWindow(textView.windowToken, 0)
// performSearch(textView.text.toString())
// true
// } else {
// false
// }
// }
// binding.homeTopAppBar.searchOutlinedTextLayout.setEndIconOnClickListener {
// Log.d("SEARCH", "setEndIconOnClickListener")
// it.clearFocus()
// binding.homeTopAppBar.homeSearchEditText.setText("")
// val inputManager =
// requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
// inputManager.hideSoftInputFromWindow(it.windowToken, 0)
//// viewModel.filterProducts("All")
// }
//// binding.homeTopAppBar.topAppBar.setOnMenuItemClickListener { menuItem ->
//// setAppBarItemClicks(menuItem)
//// }
// }
//
// private fun performSearch(searchWordsProduct: String) {
// viewModel.searchProductsInCategory(searchWordsProduct)
// }
//
// private fun setAppBarItemClicks(menuItem: MenuItem): Boolean {
// return true //this line should be deleted when the codes below is uncommented
//// return when (menuItem.itemId) {
//// R.id.home_filter -> {
//// val extraFilters = arrayOf("All", "None")
//// val categoryList = ProductCategories.plus(extraFilters)
//// val checkedItem = categoryList.indexOf(viewModel.filterCategory.value)
//// showDialogWithItems(categoryList, checkedItem, true)
//// true
//// }
//// else -> false
//// }
// }
//
// private fun setUpProductAdapter() {
// listProductsAdapter = ListProductsAdapter(requireContext())
// listProductsAdapter.onClickListener = object : ListProductsAdapter.OnClickListener {
//
// override fun onClickAdvancedActionsButton(view: View, productData: Product) {
// TODO("Not yet implemented")
// }
//
//// override fun onDeleteClick(productData: Product) {
////// Log.d(TAG, "onDeleteProduct: initiated for ${productData.productId}")
////// showDeleteDialog(productData.name, productData.productId)
//// }
//
// override fun onEditClick(productData: Product) {
//// Log.d(TAG, "onEditProduct: initiated for $productId")
//// navigateToAddEditProductFragment(isEdit = true, productId = productId)
// }
//
// }
//
// listProductsAdapter.stateRestorationPolicy = RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY
// binding.productsRecyclerView.adapter = listProductsAdapter
// listProductsAdapter.addLoadStateListener {loadState->
// // show empty list
// if (loadState.refresh is androidx.paging.LoadState.Loading ||
// loadState.append is androidx.paging.LoadState.Loading){
// binding.loaderLayout.loaderFrameLayout.visibility = View.VISIBLE
// binding.loaderLayout.circularLoader.showAnimationBehavior
// }
// else {
// binding.loaderLayout.circularLoader.hideAnimationBehavior
// binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
// // If we have an error, show a toast
// val errorState = when {
// loadState.append is androidx.paging.LoadState.Error -> loadState.append as androidx.paging.LoadState.Error
// loadState.prepend is androidx.paging.LoadState.Error -> loadState.prepend as androidx.paging.LoadState.Error
// loadState.refresh is androidx.paging.LoadState.Error -> loadState.refresh as androidx.paging.LoadState.Error
// else -> null
// }
// errorState?.let {
// handleError(CustomError(it.error, it.error.message?:"System error"))
// }
// }
// }
// }
//
// fun handleError(error: CustomError){
// if(error is RefreshTokenExpiredException){
// openLogInSignUpActivity(ISplashUseCase.PAGE.LOGIN)
// }else{
// showErrorDialog(error)
// }
// }
//
// fun openLogInSignUpActivity(page: ISplashUseCase.PAGE){
// val intent = Intent(activity, LoginSignupActivity::class.java)
// intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
// intent.putExtra("PAGE", page)
// startActivity(intent)
// }
//
// private fun getMixedDataList(data: List<Product>, adsList: List<Int>): List<Any> {
// val itemsList = mutableListOf<Any>()
// itemsList.addAll(data.sortedBy { it._id })
// var currPos = 0
// if (itemsList.size >= 4) {
// adsList.forEach label@{ ad ->
// if (itemsList.size > currPos + 1) {
// itemsList.add(currPos, ad)
// } else {
// return@label
// }
// currPos += 5
// }
// }
// return itemsList
// }
// private fun getAdsList(): List<Int> {
// //feature: for now, ad is not supported
// return listOf()
// }
// override fun onStop() {
// super.onStop()
// viewModel.clearErrors()
// }
} |
'use strict';
class Shape {
#name;
#color;
constructor(name, color){
this.name = name;
this.color = color;
this.getInfo;
}
set name(name) {
if(name === 'circle' || name ==='square') {
this.#name = name;
} else {
throw 'Shape, select a shape';
}
}
get name() {
return this.#name;
}
set color(color) {
if(color === 'blue' || color === 'green' || color === 'pink'
|| color === 'orange' || color === 'purple') {
this.#color = color;
} else {
throw 'Color, select a color';
}
}
get color() {
return this.#color;
}
getInfo() {
return `${this.#name} ${this.#color}`;
}
}
const container = document.querySelector('.grid-container');
const button = document.querySelector('.button');
const shapeSelected = document.querySelector('#shapes');
const colorSelected = document.querySelector('#colors');
const message = document.querySelector('.message p');
const shapesArray = new Array();
function getHexaColor(col) {
switch(col){
case 'blue': return '#09f';
case 'green': return '#9f0';
case 'orange': return '#f90';
case 'pink': return '#f09';
case 'purple': return '#90f';
default: return 'Select a color';
}
}
function createShape(shape,color) {
const div = document.createElement('div');
div.classList.add('shape');
if (shape === 'circle') div.classList.add('circle');
if (shape === 'square') div.classList.add('square');
div.style.backgroundColor = getHexaColor(color);
container.appendChild(div);
try {
const newShape = new Shape(shape, color);
shapesArray.push(newShape);
//console.log(shapesArray);
div.id = shapesArray.length;
div.style.gridArea = 's'+ div.id;
//console.log(div.style.gridArea);
div.addEventListener('click', function() {
console.log(div.id);
message.innerHTML = `Shape ${div.id} : ${shapesArray[div.id - 1].getInfo()}`;
});
} catch (error) {
console.log(error);
}
}
button.addEventListener('click', () => {
console.log(shapeSelected.value);
console.log(colorSelected.value);
console.log(shapesArray.length);
if (!(shapesArray.length === 24)) {
createShape(shapeSelected.value, colorSelected.value);
} else {
message.innerHTML = 'Storage is full';
}
}); |
import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import * as jwt from 'jwt-decode';
import Application from "../auxiliarComponents/home/application.jsx";
import Map from "../auxiliarComponents/home/map.jsx";
import Carroussel from "../auxiliarComponents/home/carroussel";
import News from "../auxiliarComponents/home/news.jsx";
const Everyone = () => {
const navigate = useNavigate();
const token = sessionStorage.getItem('token');
let tipo = 'Everyone';
if (token){
const tokenDecoded = jwt.jwtDecode(token);
tipo = tokenDecoded.userType;
}
return (
<div className="home-container">
<h1 className="text-center">Escuela Infantil Virgen Inmaculada</h1>
<hr className="borde mt-0"></hr>
<div className='row mx-2 flex-grow-1'>
{/* Primera fila de elementos */}
<div className='col-lg-8'>
<h2>Nuestro centro:</h2>
<div className='d-flex flex-column main-content mb-5'>
<Carroussel />
</div>
</div>
<div className='col-lg-4 d-flex flex-column'>
<div className='noticias-section' tabIndex={0}>
<h2>Últimas noticias:</h2>
<div className='d-flex flex-column mb-5'>
<News publico={tipo} />
</div>
</div>
</div>
</div>
<div className='row mx-2 mt-2'>
{/* Segunda fila de elementos */}
<div className='col-lg-8'>
<h2>Encuéntranos:</h2>
<section className='map-section mb-5'>
<Map />
</section>
</div>
<div className='col-lg-4'>
<h2>Escríbanos:</h2>
<section className='application-section'>
<Application />
</section>
</div>
</div>
</div>
);
}
export default Everyone; |
import { HttpErrorResponse } from '@angular/common/http';
import { Component, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, NgForm, Validators } from '@angular/forms';
import { Movement } from 'src/app/domain/movement';
import { Profile } from 'src/app/domain/profile';
import { MovementService } from 'src/app/services/movement.service';
import { ProfileService } from 'src/app/services/profile.service';
import Decimal from 'decimal.js';
import { MatPaginator, PageEvent } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
@Component({
selector: 'app-movements',
templateUrl: './movements.component.html',
styleUrls: ['./movements.component.sass']
})
export class MovementsComponent {
public selectedProfile !: Profile;
public movements !: Movement[];
public matMovements !: MatTableDataSource<Movement>;
public addMovement !: Movement;
public addMovementForm !: FormGroup;
public editMovement ?: Movement;
public deleteMovement ?: Movement;
public profileDataLoaded : boolean = false;
public movementsDataLoaded : boolean = false;
public isIncome !: boolean;
public balance : Decimal = new Decimal(0);
public submitted = false;
displayedColumns: string[] = ['Concept', 'Description', 'Amount', 'Date'];
@ViewChild(MatPaginator) paginator!: MatPaginator;
@ViewChild(MatSort) sort!: MatSort;
constructor(private formBuilder: FormBuilder, private profileService: ProfileService, private movementService : MovementService){
}
ngOnInit(){
this.getSelectedProfile();
this.getMovements();
this.getBalance();
this.addMovementForm = this.formBuilder.group({
concept:['', [
Validators.required
]],
description:['', [
Validators.maxLength(200)
]],
amount:['', [
Validators.required,
Validators.pattern(/^\d+(\.\d{1,2})?$/)
]],
date: ['', [
Validators.required
]]
})
}
getSelectedProfile() {
this.profileDataLoaded = false;
this.profileService.getProfileById(parseInt(localStorage.getItem('selectedProfileId')!)).subscribe(
(response : Profile) => {
console.log(response);
this.selectedProfile = response;
this.profileDataLoaded = true;
},
(error : HttpErrorResponse) => {
alert(error.message);
}
)
}
public async getMovements() : Promise<void>{
this.movementsDataLoaded = false;
await this.waitForProfileDataLoaded();
this.movementService.getProfileMovements(this.selectedProfile.id).subscribe(
(response: Movement[]) => {
this.movements = response;
response.sort((a, b) => {
return new Date(b.date).getTime() - new Date(a.date).getTime();
});
this.matMovements = new MatTableDataSource(response);
this.matMovements.paginator = this.paginator;
this.matMovements.sort = this.sort;
console.log(this.movements);
this.movementsDataLoaded = true;
},
(error : HttpErrorResponse) => {
alert(error.message);
}
)
}
public async getBalance() {
this.balance = new Decimal(0);
await this.waitForMovementsDataLoaded();
this.movements.forEach(movement => {
this.balance = this.balance.plus(new Decimal(movement.amount));
});
}
public onAddMovement() {
this.submitted = true;
if(this.addMovementForm.invalid){
return
}
document.getElementById('add-movement-form')!.click();
this.addMovement = this.addMovementForm.value;
this.addMovement.profile = this.selectedProfile;
if(this.isIncome === false){
const originalAmount = new Decimal(this.addMovement.amount);
this.addMovement.amount = originalAmount.neg();
}
this.movementService.addMovement(this.addMovement).subscribe(
(response : Movement) => {
console.log(response);
this.addMovementForm.reset();
this.getMovements();
this.balance = this.balance.plus(new Decimal(response.amount));
this.submitted = false;
},
(error : HttpErrorResponse) => {
alert(error.message);
this.addMovementForm.reset();
this.submitted = false;
}
)
}
public onUpdateMovement(movement : Movement) : void {
movement.profile = this.selectedProfile;
this.movementService.updateMovement(movement).subscribe(
(response : Movement) => {
console.log(response);
},
(error : HttpErrorResponse) => {
alert(error.message);
}
)
this.ngOnInit();
}
public onDeleteMovement(movementId : number) : void {
this.movementService.deleteMovement(movementId).subscribe(
(response : void) => {
console.log(response);
this.ngOnInit();
},
(error : HttpErrorResponse) => {
alert(error.message);
}
)
}
public searchMovements(key: string): void {
console.log(key);
const results: Movement[] = [];
for (const employee of this.movements) {
if (employee.concept.toLowerCase().indexOf(key.toLowerCase()) !== -1
|| employee.description.toLowerCase().indexOf(key.toLowerCase()) !== -1) {
results.push(employee);
}
}
this.movements = results;
if (results.length === 0 || !key) {
this.getMovements();
}
}
sortMovementsByConcept() {
this.movements = this.movements.sort((a, b) => {
if (a.concept < b.concept) {
return -1;
}
if (a.concept > b.concept) {
return 1;
}
return 0;
});
}
applyFilter(event: Event) {
const filterValue = (event.target as HTMLInputElement).value;
this.matMovements.filter = filterValue.trim().toLowerCase();
if (this.matMovements.paginator) {
this.matMovements.paginator.firstPage();
}
}
public onOpenModal(movement : Movement | null, mode: string): void {
const container = document.getElementById('movements')!;
const button = document.createElement('button');
button.type = 'button';
button.style.display = 'none';
button.setAttribute('data-toggle', 'modal');
if (mode === 'addIncome') {
this.isIncome = true;
button.setAttribute('data-target', '#addMovementModal');
}
if (mode === 'addExpense') {
this.isIncome = false;
button.setAttribute('data-target', '#addMovementModal');
}
if (mode === 'edit') {
this.editMovement = movement!;
button.setAttribute('data-target', '#editMovementModal');
}
if (mode === 'delete') {
this.deleteMovement = movement!;
button.setAttribute('data-target', '#deleteMovementModal');
}
container.appendChild(button);
button.click();
}
resetAddMovementForm() {
this.addMovementForm.reset();
this.submitted = false;
}
waitForProfileDataLoaded(): Promise<void> {
return new Promise(resolve => {
const intervalId = setInterval(() => {
if (this.profileDataLoaded) {
clearInterval(intervalId);
resolve();
}
}, 100);
});
}
waitForMovementsDataLoaded(): Promise<void> {
return new Promise(resolve => {
const intervalId = setInterval(() => {
if (this.movementsDataLoaded) {
clearInterval(intervalId);
resolve();
}
}, 100);
});
}
} |
// Require packages.
const multer = require('multer');
const sharp = require('sharp');
// Import Tour from tourModel.js.
const Tour = require('./../models/tourModel');
// Require function from catchAsync.js.
const catchAsync = require('./../utils/catchAsync');
// Require AppError class from AppError.js.
const AppError = require('./../utils/appError');
// Require functions from handlerFactory.js.
const factory = require('./handlerFactory');
// Store the file in a buffer.
const multerStorage = multer.memoryStorage();
// Filter out files that are not images.
const multerFilter = (req, file, cb) => {
if (file.mimetype.startsWith('image')) {
cb(null, true);
} else {
cb(new AppError('Not an image! Please upload only images.', 400), false);
}
};
// Set the storage and fileFilter.
const upload = multer({
storage: multerStorage,
fileFilter: multerFilter
});
// First image is the stored as imageCover. Next 3 images are placed in the images array.
exports.uploadTourImages = upload.fields([
{
name: 'imageCover',
maxCount: 1
},
{
name: 'images',
maxCount: 3
}
]);
// If req.files don't have imageCover or images, go the next function.
// For imageCover image, resize it to 3:2 ratio, save as jpeg, save it in public/img/tours.
// Use map() to save all images, resize it to 3:2 ratio, save as jpeg, save it in public/img/tours.
exports.resizeTourImages = catchAsync(async(req, res, next) => {
console.log(req.files);
if(!req.files.imageCover || !req.files.images) {
return next();
}
else {
req.body.imageCover = `tour-${req.params.id}-${Date.now()}-cover.jpeg`;
await sharp(req.files.imageCover[0].buffer)
.resize(2000, 1333)
.toFormat('jpeg')
.jpeg({ quality: 90 })
.toFile(`public/img/tours/${req.body.imageCover}`);
req.body.images = [];
await Promise.all(req.files.images.map(async(file, i) => {
const filename = `tour-${req.params.id}-${Date.now()}-${i + 1}.jpeg`;
await sharp(file.buffer)
.resize(2000, 1333)
.toFormat('jpeg')
.jpeg({ quality: 90 })
.toFile(`public/img/tours/${filename}`);
req.body.images.push(filename);
}));
next();
}
});
// Use a middleware function to display 5 tours on a page.
// Sort from highest ratingsAverage to lowest ratingsAverage, then sort from lowest price to highest price.
// Only display name, price, ratingsAverage, summary, and difficulty.
exports.aliasTopTours = (req, res, next) => {
req.query.limit = '5';
req.query.sort = '-ratingsAverage,price';
req.query.fields = 'name,price,ratingsaverage,summary,difficulty';
next();
}
// Invoke getOne, pass in Tour as argument.
exports.getAllTours = factory.getAll(Tour);
// Invoke createOne, pass in Tour as argument.
exports.createTour = factory.createOne(Tour);
// Invoke getOne, pass in Tour and { path: 'reviews' } as arguments.
exports.getTour = factory.getOne(Tour, { path: 'reviews'});
// Invoke updateOne, pass in Tour as argument.
exports.updateTour = factory.updateOne(Tour);
// Invoke deleteOne, pass in Tour as argument.
exports.deleteTour = factory.deleteOne(Tour);
// Wrap the catchAsync function around the async function to catch the error without having the try-catch block.
// Use an aggregation pipeline to manipulate the data.
// Calculate the number of documents, total number of ratingsQuantity,
// average ratingsAverage, average price, minimum price, maximum price of all documents with greater than 4.5 ratingsAverage.
// Seperate the groups by difficulty's value. So we will get the likes of average price for each difficulty level.
// Sort by avgPrice, from lowest to highest.
exports.getTourStats = catchAsync(async(req, res) => {
const stats = await Tour.aggregate([
{
$match: { ratingsAverage: { $gte: 4.5 } }
},
{
$group: {
_id: { $toUpper: '$difficulty' },
num: { $sum: 1 },
numRatings: { $sum: '$ratingsQuantity' },
avgRating: { $avg: '$ratingsAverage' },
avgPrice: { $avg: '$price' },
minPrice: { $min: '$price' },
maxPrice: { $max: '$price' },
}
},
{
$sort: { avgPrice: 1 }
}
]);
res.status(200).json({
status: 'success',
data: {
stats
}
});
});
// Wrap the catchAsync function around the async function to catch the error without having the try-catch block.
// Get the year from the parameter, make it into a number.
// Unwind documents by startDates, the document with an array of 3 startDates elements will unwind into 3 documents with each having
// a different startDates value. Use $match to get only results from the year. Then, group the documents by startDates' month,
// count the amount of tours for each month on that year, and list all the tour names of that month in an array.
// Add the field month, which is the same as _consoleid. Hide the _id property using $project keyword.
// Sort the objects in the plan array from highest numToursStarts value to lowest numTourStarts value.
// Only display up to 12 objects in the plan array.
exports.getMonthlyPlan = catchAsync(async(req, res) => {
const year = req.params.year * 1;
const plan = await Tour.aggregate([
{
$unwind: '$startDates'
},
{
$match: {
startDates: {
$gte: new Date(`${year}-01-01`),
$lte: new Date(`${year}-12-31`)
}
}
},
{
$group: {
_id: { $month: '$startDates' },
numTourStarts: { $sum: 1 },
tours: { $push: '$name' }
}
},
{
$addFields: { month: '$_id' }
},
{
$project: { _id: 0 }
},
{
$sort: { numTourStarts: -1 }
},
{
$limit: 12
}
]);
res.status(200).json({
status: 'success',
data: {
plan
}
});
});
// Wrap the catchAsync function around the async function to catch the error without having the try-catch block.
// Use destructuring to get distance, latlng, and unit from the parameters.
// Because latlng is a string with a comma splitting the lat and lng, use split() method to retrieve individual lat and lng values.
// If there's no lat or lng, render an error. Get the radius value, if unit is mi, distance is divide distance by 3963.2, that's the radius of the Earth
// in miles, if distance is not mi, it's default to km, then radius is distance divide by 6378.1, that's the radius of the Earth in kilometers.
// Use geospatial query to find the tours that are within the distance.
exports.getToursWithin = catchAsync(async(req, res, next) => {
const { distance, latlng, unit } = req.params;
const [lat, lng] = latlng.split(',');
const radius = unit === 'mi' ? distance / 3963.2 : distance / 6378.1;
if(!lat || !lng) {
next(new AppError('Please provide latitude and longtitude in the format of "lat,lng".'), 400);
}
const tours = await Tour.find(
{ startLocation: { $geoWithin: { $centerSphere: [[lng, lat], radius]} } });
res.status(200).json({
status: 'success',
results: tours.length,
data: {
data: tours
}
});
});
// Wrap the catchAsync function around the async function to catch the error without having the try-catch block.
// Use destructuring to get distance, center, and unit from the parameters.
// Because latlng is a string with a comma splitting the lat and lng, use split() method to retrieve individual lat and lng values.
// If there's no lat or lng, render an error. Get the multiplier, if unit is "mi", set multiplier to 0.000621371, if unit is not specified, treat
// the unit as km, which means multiplier is 0.001. Use aggregation pipeline to calculate the distance.
// Use geospatial aggregation, $geoNear is always the first query, set near equals a Point type object with lng and lat as coordinates.
// The returned distance is in meters, use distanceMultiplier to convert the unit to km or mi. Only keep the distance and name for each tour.
exports.getDistances = catchAsync(async(req, res, next) => {
const { latlng, unit } = req.params;
const [lat, lng] = latlng.split(',');
const multiplier = unit === "mi" ? 0.000621371 : 0.001;
if(!lat || !lng) {
next(new AppError('Please provide latitude and longtitude in the format of "lat,lng".'), 400);
}
const distances = await Tour.aggregate([
{
$geoNear: {
near: {
type: 'Point',
coordinates: [lng * 1, lat * 1]
},
distanceField: 'distance',
distanceMultiplier: multiplier
}
},
{
$project: {
distance: 1,
name: 1
}
}
]);
res.status(200).json({
status: 'success',
data: {
data: distances
}
});
}); |
import React, { useRef } from 'react';
import { project } from '../../utils/types';
import axios from '../../axios';
import Styles from './ProjectContainer.module.scss';
import { projects } from '../../atoms/allProjectAtom';
import produce from 'immer';
import { useSetNotification } from '../../utils/customHooks/useAddNotification';
import { useSetRecoilState } from 'recoil';
type projectTitleProps = {
inputValue: string | undefined;
onChangeInput: (val: string) => void;
initialInputValue: string | undefined;
project: project | undefined;
onHideInput: () => void;
};
function ProjectTitle({
inputValue,
onChangeInput,
initialInputValue,
project,
onHideInput,
}: projectTitleProps) {
const inputRef = useRef<HTMLInputElement | null>(null);
const setProjects = useSetRecoilState(projects);
const { addNotification } = useSetNotification();
function inputChangeHandler(e: React.ChangeEvent<HTMLInputElement>) {
onChangeInput(e.target.value);
}
function enterHandler(e: React.KeyboardEvent<HTMLInputElement>) {
if (e.key === 'Enter' && !e.altKey && !e.shiftKey && !e.ctrlKey) {
inputRef.current?.blur();
}
}
// storing Value
async function inputBlurHandler() {
if (inputValue?.trim()) {
try {
if (window.navigator.onLine) {
const res = await axios.patch<project>(
'/api/project',
{
updatedProjectName: inputValue.trim(),
projectId: project?.id,
},
{ timeoutErrorMessage: 'unable to update list title' },
);
if (res.status === 200) {
setProjects((projects) =>
produce(projects, (draft) => {
const editIndex = draft.findIndex(
(givenProject) => givenProject.id === res.data.id,
);
if (editIndex > -1) {
draft[editIndex].projectName = res.data.projectName;
}
}),
);
onChangeInput(res.data.projectName);
}
} else {
throw new Error('there is no internet connection');
}
} catch (e) {
addNotification(e.message, 'Newtowork Error');
if (initialInputValue) {
onChangeInput(initialInputValue);
}
}
} else {
if (initialInputValue) {
onChangeInput(initialInputValue);
}
}
onHideInput();
}
return (
<input
type='text'
ref={inputRef}
value={inputValue}
onBlur={inputBlurHandler}
onChange={inputChangeHandler}
onKeyUp={enterHandler}
className={Styles.projectTitle}
size={inputValue ? inputValue.length - 1 : 0}
maxLength={255}
autoFocus
/>
);
}
export default ProjectTitle; |
# diff-notebooks
Github Actions to compare notebook files.
diff-notebooks store html files as artifacts.

You can confirm diff of notebooks in your browser.

# Dependencies
- [kuromt/nbdiff-web-exporter](https://github.com/kuromt/nbdiff-web-exporter)
# Input
```yaml
inputs:
base:
required: false
description: |
The base notebook filename OR base git-revision.
default: ""
remote:
required: false
description: |
The remote modified notebook filename OR remote git-revision.
default: HEAD
port:
required: false
description: |
specify the port you want the server to run on. Default is 8888.
default: 8888
export_dir:
required: false
description: |
directory for saving diff file.
default: "./atricacts"
nbdiff_web_exporter_options:
required: false
description: |
options of nbdiff-web-exporter. Do not set port and export-dir options.
default: ''
```
# Outputs
```yaml
outputs:
nbdiff_web_export_dir:
description: "directory for saving diff file"
```
# Usage
```yaml
name: nbdiff-web-exporter
on: [pull_request]
jobs:
diff-action-test:
runs-on: ubuntu-latest
name: diff notebooks
steps:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: diff notebooks
uses: kuromt/diff-notebooks
id: nbdiff-web-exporter-action
with:
remote: "origin/diff-notebooks"
export_dir: "./artifacts"
- uses: actions/upload-artifact@v2
with:
name: diff-notebooks
path: ${{steps.nbdiff-web-exporter-action.outputs.export_dir}}
``` |
<?php
namespace App\Http\Controllers;
use App\Models\M_Warranty;
use Carbon\Carbon;
use RealRashid\SweetAlert\Facades\Alert;
use Illuminate\Http\Request;
class M_WarrantyController extends Controller
{
public function __construct()
{
$this->middleware(function ($request, $next) {
if (session('success')) {
Alert::success(session('success'));
}
if (session('error')) {
Alert::error(session('error'));
}
if (session('warning')) {
Alert::warning(session('warning'));
}
return $next($request);
});
}
public function index()
{
$data = M_Warranty::all();
return view('m_warranty.index', compact('data'));
}
public function store(Request $request)
{
try {
$checkkategori = M_Warranty::where('tipe', $request->tipe)->first();
if ($checkkategori) {
return redirect()->back()->with('warning', 'Tipe Telah Terdaftar!');
}
M_Warranty::create([
'tipe' =>$request->tipe,
'tahun_berlaku' => $request->tahun,
'create_id' => auth()->user()->id,
'created_at' => Carbon::now()
]);
return redirect('/data-m_warranty')->with('success', 'Data Tersimpan!');
} catch (\Exception $e) {
// Log::error('Error saat menyimpan user: ' . $e->getMessage());
dd($e->getMessage());
return redirect()->back()->with('error', 'Data Tidak Tersimpan, Periksa kembali inputan ada!');
}
}
public function edit($id)
{
//
}
public function update(Request $request)
{
try {
$checkkategori = M_Warranty::where('tipe', $request->tipe)->where('id','!=',$request->id)->first();
if ($checkkategori) {
return redirect()->back()->with('warning', 'Tipe Telah Terdaftar!');
}
M_Warranty::find($request->id)->update([
'tipe'=>$request->tipe,
'tahun_berlaku' => $request->tahun,
'modify_id' => auth()->user()->id,
'updated_at' => Carbon::now()
]);
return redirect('/data-m_warranty')->with('success', 'Data Berhasil Diubah!');
} catch (\Exception $e) {
// dd($e->getMessage());
return redirect()->back()->with('error', 'Data Tidak Berhasil Diubah, Periksa kembali inputan ada!');
}
}
public function destroy($id)
{
//$dataUser = ProfileUsers::all();
try {
$dataKategori = M_Warranty::find($id);
$dataKategori->delete();
return redirect('/data-m_warranty')->with("success", 'Data Berhasil Dihapus');
} catch (\Exception $e) {
return redirect()->back()->with('error', 'Data Tidak Berhasil Dihapus!');
}
}
} |
/*
* Copyright (c) 2009 Chani Armitage <chani@kde.org>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, 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 Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef PLASMA_CONTAINMENTACTIONS_H
#define PLASMA_CONTAINMENTACTIONS_H
#include <QList>
#include <kplugininfo.h>
#include <plasma/plasma.h>
#include <plasma/packagestructure.h>
#include <plasma/version.h>
class QAction;
namespace Plasma
{
class DataEngine;
class Containment;
class ContainmentActionsPrivate;
/**
* @class ContainmentActions plasma/containmentactions.h <Plasma/ContainmentActions>
*
* @short The base ContainmentActions class
*
* "ContainmentActions" are components that provide actions (usually displaying a contextmenu) in
* response to an event with a position (usually a mouse event).
*
* ContainmentActions plugins are registered using .desktop files. These files should be
* named using the following naming scheme:
*
* plasma-containmentactions-\<pluginname\>.desktop
*
*/
class PLASMA_EXPORT ContainmentActions : public QObject
{
Q_OBJECT
Q_PROPERTY(QString name READ name)
Q_PROPERTY(QString pluginName READ pluginName)
Q_PROPERTY(QString icon READ icon)
public:
/**
* Default constructor for an empty or null containmentactions
*/
explicit ContainmentActions(QObject * parent = 0);
~ContainmentActions();
/**
* Returns a list of all known containmentactions plugins.
*
* @return list of containmentactions plugins
**/
static KPluginInfo::List listContainmentActionsInfo();
/**
* Attempts to load a containmentactions
*
* Returns a pointer to the containmentactions if successful.
* The caller takes responsibility for the containmentactions, including
* deleting it when no longer needed.
*
* @param parent the parent containment. Required; if you send null you'll get back null.
* @param name the plugin name, as returned by KPluginInfo::pluginName()
* @param args to send the containmentactions extra arguments
* @return a pointer to the loaded containmentactions, or 0 on load failure
**/
static ContainmentActions *load(Containment *parent, const QString &name, const QVariantList &args = QVariantList());
/**
* Attempts to load a containmentactions
*
* Returns a pointer to the containmentactions if successful.
* The caller takes responsibility for the containmentactions, including
* deleting it when no longer needed.
*
* @param parent the parent containment. Required; if you send null you'll get back null.
* @param info KPluginInfo object for the desired containmentactions
* @param args to send the containmentactions extra arguments
* @return a pointer to the loaded containmentactions, or 0 on load failure
**/
static ContainmentActions *load(Containment *parent, const KPluginInfo &info, const QVariantList &args = QVariantList());
/**
* Returns the Package specialization for containmentactions.
*/
static PackageStructure::Ptr packageStructure();
/**
* Returns the user-visible name for the containmentactions, as specified in the
* .desktop file.
*
* @return the user-visible name for the containmentactions.
**/
QString name() const;
/**
* Returns the plugin name for the containmentactions
*/
QString pluginName() const;
/**
* Returns the icon related to this containmentactions
**/
QString icon() const;
/**
* @return true if initialized (usually by calling restore), false otherwise
*/
bool isInitialized() const;
/**
* This method should be called once the plugin is loaded or settings are changed.
* @param config Config group to load settings
* @see init
**/
void restore(const KConfigGroup &config);
/**
* This method is called when settings need to be saved.
* @param config Config group to save settings
**/
virtual void save(KConfigGroup &config);
/**
* Returns the widget used in the configuration dialog.
* Add the configuration interface of the containmentactions to this widget.
*/
virtual QWidget *createConfigurationInterface(QWidget *parent);
/**
* This method is called when the user's configuration changes are accepted
*/
virtual void configurationAccepted();
/**
* Implement this to respond to events.
* The user can configure whatever button and modifier they like, so please don't look at
* those parameters.
* So far the event could be a QGraphicsSceneMouseEvent or a QGraphicsSceneWheelEvent.
*/
virtual void contextEvent(QEvent *event);
/**
* Implement this to provide a list of actions that can be added to another menu
* for example, when right-clicking an applet, the "Activity Options" submenu is populated
* with this.
*/
virtual QList<QAction*> contextualActions();
/**
* Loads the given DataEngine
*
* Tries to load the data engine given by @p name. Each engine is
* only loaded once, and that instance is re-used on all subsequent
* requests.
*
* If the data engine was not found, an invalid data engine is returned
* (see DataEngine::isValid()).
*
* Note that you should <em>not</em> delete the returned engine.
*
* @param name Name of the data engine to load
* @return pointer to the data engine if it was loaded,
* or an invalid data engine if the requested engine
* could not be loaded
*
*/
Q_INVOKABLE DataEngine *dataEngine(const QString &name) const;
/**
* @return true if the containmentactions currently needs to be configured,
* otherwise, false
*/
bool configurationRequired() const;
/**
* Turns a mouse or wheel event into a string suitable for a ContainmentActions
* @return the string representation of the event
*/
static QString eventToString(QEvent *event);
bool event(QEvent *e);
protected:
/**
* This constructor is to be used with the plugin loading systems
* found in KPluginInfo and KService. The argument list is expected
* to have one element: the KService service ID for the desktop entry.
*
* @param parent a QObject parent; you probably want to pass in 0
* @param args a list of strings containing one entry: the service id
*/
ContainmentActions(QObject *parent, const QVariantList &args);
/**
* This method is called once the containmentactions is loaded or settings are changed.
*
* @param config Config group to load settings
**/
virtual void init(const KConfigGroup &config);
/**
* When the containmentactions needs to be configured before being usable, this
* method can be called to denote that action is required
*
* @param needsConfiguring true if the applet needs to be configured,
* or false if it doesn't
*/
void setConfigurationRequired(bool needsConfiguring = true);
/**
* @return the containment the plugin is associated with.
*/
Containment *containment();
/**
* pastes the clipboard at a given location
*/
void paste(QPointF scenePos, QPoint screenPos);
private:
friend class ContainmentActionsPackage;
friend class ContainmentActionsPrivate;
ContainmentActionsPrivate *const d;
};
} // Plasma namespace
/**
* Register a containmentactions when it is contained in a loadable module
*/
#define K_EXPORT_PLASMA_CONTAINMENTACTIONS(libname, classname) \
K_PLUGIN_FACTORY(factory, registerPlugin<classname>();) \
K_EXPORT_PLUGIN(factory("plasma_containmentactions_" #libname)) \
K_EXPORT_PLUGIN_VERSION(PLASMA_VERSION)
#endif // PLASMA_CONTAINMENTACTIONS_H |
package com.example.demo.controller;
import com.example.demo.dto.CreatePersonRequest;
import com.example.demo.model.Person;
import com.example.demo.service.PersonService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/person")
public class PersonController {
@Autowired
PersonService personService;
@PostMapping("/new")
public void createPerson(@RequestBody CreatePersonRequest createPersonRequest){
personService.create(createPersonRequest.toPerson());
}
@GetMapping("getAll")
public List<Person> getAllPerson(){
return personService.getAll();
}
//TODO : getById
/**
* List operations
*/
@PostMapping("/lpush")
public void createListPerson(@RequestBody @Valid CreatePersonRequest createPersonRequest){
personService.lpush(createPersonRequest.toPerson());
}
@GetMapping("/lrange")
public List<Person> getAllFromList(
@RequestParam(name = "start", required = false, defaultValue = "0") int start,
@RequestParam(name = "end", required = false, defaultValue = "-1") int end
){
return personService.lrange(start,end);
}
/**
*
* @param count by default is 1, if you want to delete more than 1 element, increase the count
* @return Removes and returns the first elements of the list stored at key.
*/
@DeleteMapping("/lpop")
public List<Person> deleteLeftPop(@RequestParam(name = "count", required = false, defaultValue = "1") long count){
return personService.lpop(count);
}
/**
* Time Complexity : O(1) for each element added, so O(N) to add N elements when the command is called with multiple arguments.
* @param createPersonRequest
* Insert all the specified values at the tail of the list stored at key. If key does not exist, it is created as empty list before performing the push operation.
*/
@PostMapping("/rpush")
public void createListPersonRight(@RequestBody CreatePersonRequest createPersonRequest){
personService.rpush(createPersonRequest.toPerson());
}
/**
*
* @param count By default, the command pops a single element from the end of the list. When provided with the optional count argument, the reply will consist of up to count elements, depending on the list's length.
* @return Removes and returns the last elements of the list stored at key.
*/
@DeleteMapping("/rpop")
public List<Person> deleteRightPop(@RequestParam(name = "count", required = false, defaultValue = "1") long count){
return personService.rpop(count);
}
/**
* Hash operation
*/
//set /get/ delete
/**
* Sets the specified fields to their respective values in the hash stored at key.
*
* This command overwrites the values of specified fields that exist in the hash. If key doesn't exist, a new key holding a hash is created.
*
*/
@PostMapping("/hset")
public void addToHashPerson(@RequestBody @Valid CreatePersonRequest createPersonRequest){
personService.addToHash(createPersonRequest.toPerson());
}
@GetMapping("/hgetAll/{personId}")
public Person getPersonFromHash(@PathVariable("personId") String personId){
return personService.getPersonFromHash(personId);
}
} |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Main script for model of single-molecule fluorescence microscopy %
% corrosion experiment. This script contains inputs for physical and %
% model parameters and calls corrosion model and diffusion model scripts. %
% Saves data and movies to specified folder. To run corrosion and %
% diffusion simultaneously, set linked = True, corrT and diffT to 1, %
% corrdT and diffdT to the same value, and use loops to specify %
% how many time steps to run. To run first corrosion for some time and then
% diffusion, set linked = false and input desired time steps and lengths %
% in lines 20-23 %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear
tic
%% Set dimensional parameters
px = 500; %number of pixels in each dimension
pxsize = 10; %pixel size in nm
linked = false; %true will run corrosion and diffusion concurrently/simealteaneaously,
%false will run corrosion first then diffusion in each overall loop
if linked == false %input desired values
diffT = 3000; %number of time steps for diffusion script
diffdT = 0.02; %length of time step for diffusion in seconds
corrT = 1800; %number of time steps for corrosion script
corrdT = 1; %length of corrosion time step in seconds
elseif linked == true
dT = 0.2; %dT for each loop in seconds.
%do not change anything else in this elseif statement
diffdT = dT;
corrdT = dT;
diffT = 1;
corrT = 1;
end
startTime = 0;
numLoops = 1; %number of full corrosion and diffusion loops.
%if linked = true this is the total time steps of the simulation
%% set corrosion parameters
runCorrosion = false; %true will run corrosion script in each loop, false will not
if runCorrosion == true
Pin = 5e-11; %probability of initiation per second per nm^2
PinUncer = 2; %percent uncertainty in Pin
Pgr = 0.0005 ; %growth probability per nearest neighbor per second
%excl = 10; %exclusion zone for pits, the time constant of the exponential representing the exclusion zone probability
%not currently in use (12/18/2020)
else
pitrad = 15; %radius of static pit in nm if not running corrosion
end
%cathLoc will be used to define a 2D gaussian probability distribution
% for the location of the cathodic reaction outside a pit
cathLocMax = 500; %maximum possible distance for cathodic reaction in nm
cathSigma = 10; %standard deviation for cathloc gaussian in nm
cathLoc = zeros(cathLocMax/pxsize); %cathode location probability matrix
for i=1:cathLocMax/pxsize
for j = 1:cathLocMax/pxsize
cathLoc(i,j) = Gauss2D(i,j,ceil(cathLocMax/pxsize/2), ceil(cathLocMax/pxsize/2),cathSigma/pxsize,[]);
end
end
%% set dye parameters
runDyes = true; %true will run diffusion in every loop, false will not
if runDyes == true
Conc=20e-9; %Dye concentration in moles/L
D=1e8; % Diffusion constant D (in nm^2/s)
sensMax = 100; %maximum distance in nm at which a dye can react with the cathode
sensSigma = 1; %standard deviation for the dye sensitivity distribution in nm
dye = 'Resazurin'; %which dye is being used ('Resazurin' or 'FD1'/other. Any input that is not "resazurin" will assume anode sensing dye)
ironProb = 1; %prob that Fe ion detecting dye (like 'FD1') will turn on if over pit
Vol = 18e-6; %volume of flow chamber is 18 uL
Area = pi*(13e-3)^2; %diameter of flow chamber is 13mm
flowRate = 10e-6/60; %flow rate in liters/second
end
turnOnLocs = [];
%% Set file properties
saveMovie = true; %true saves a movie of the CA progression and turned on dyes in imaging plane
saveData = true; %true saves data related to corrosion growth, number of pits, dye turn ons, and number of dyes in view (and more)
plotTurnOns = false; %true will add x's to corrosion movie for turn on events
frameRate = 10; %frames/second
folder = 'C:\Users\User\Documents\MessengerCorrosionSim\CorrosionSim_20201112\SimulationResults'; %folder location where data should be saved
filename = 'FileNameHere';
%be sure to input folder in which you want data saved, and filename
%end of inputs
%% set up folder
if saveData == true
[Path, filename] = SetUpFolder(folder, filename);
else
Path = '';
end
%% initialize data
CA = [];
if linked == true
if runCorrosion == true
corrosionTrackerTotal = [];
pitLocsTotal = [];
end
if runDyes == true
turnOnLocsTotal = [];
dyeTrackerTotal = [];
onLocsTotal = [];
end
end
%% run simulation
clear MoveDyesNormal %clear label number persistant variable
for h=1:numLoops %number of complete corrosion and diffusion loops
corrosionMovie = [];
corrosionFig = figure
diffusionMovie = [];
diffusionFig = figure
sprintf('Loop %d', h)
clear CreateFrameDiffusion %clear the persistent variable in the CreatingFrame function that tracks time
clear CreateFrameCorrosion
if runCorrosion == true
sprintf('Corrosion')
[CA, corrosionTracker, pitLocs, corrosionMovie, corrosionFig] = Corrosion(corrT, corrdT, startTime, frameRate, px, pxsize, Pin, PinUncer, Pgr, CA, turnOnLocs, plotTurnOns, corrosionMovie, corrosionFig, linked);
if linked ~= true %tracks startimes for timestamps on videos
startTime = startTime + corrT*corrdT;
end
CorrosionRate = corrosionTracker(end-10:end)*pxsize^2*10/10*corrdT; %nm^3/s corrosion rate
CRate = CorrosionRate/(0.126^3*pi*4/3); %corrosion rate in atoms of iron (reactions) per second, assuming iron has atomic radius 0.126 nm, sets max number of turn on events per second
else
CA = CreateCirclePit(px, pitrad/pxsize); %if not running the corrosion script, create a
% static pit over which to run
% diffsion
CRate = 1e10; %set an "infinite" value for CRate in trials where I am not running corrosion just for now
end
if runDyes == true
sprintf('Diffusion')
if linked == false
clear MoveDyesNormal
end
[dyeTracker, turnOnLocs, diffusionMovie, diffusionFig, onLocs, dyeProps,labelNumber] = Diffusion(startTime, diffT, diffdT, px, pxsize, Conc, D, sensMax, sensSigma, CA, cathLoc, frameRate, dye, ironProb, diffusionMovie, diffusionFig, linked, Path, filename, h, saveData, saveMovie, CRate, Vol, Area, flowRate);
figOverlay = turnOnOverlay(CA, turnOnLocs);
if saveData == true
saveas(figOverlay, strcat(Path, sprintf('Overlay%d.fig',h)))
end
end
if runDyes == true || linked == true
startTime = startTime + diffT*diffdT; %track starttime for timestamps on movies
end
%save data for this loop if not linked, or append data to last loop if
%linked
if linked == false
if saveData == true
if runCorrosion == true
dlmwrite(strcat(Path,filename, sprintf('_corrosionTracker%d', h)),corrosionTracker);
dlmwrite(strcat(Path,filename, sprintf('_pitLocs%d', h)),pitLocs);
dlmwrite(strcat(Path, filename, sprintf('_CA%d', h)), CA);
end
if runDyes == true
dlmwrite(strcat(Path, filename, sprintf('_turnOnLocs%d',h)), turnOnLocs);
dlmwrite(strcat(Path, filename, sprintf('_dyeTracker%d',h)), dyeTracker);
save(strcat(Path, filename, sprintf('_OnLocations%d.mat', h)), 'onLocs');
%clear turnOnLocs dyeTracker onLocs dyeProps %clear saved
%data to speed up (didn't really make it any faster)
end
dlmwrite(strcat(Path,filename, sprintf('_CA%d',h)), CA);
end
elseif linked == true %append data for linked simulations
if runCorrosion == true
corrosionTrackerTotal = [corrosionTrackerTotal; corrosionTracker];
pitLocsTotal = [pitLocsTotal; pitLocs];
end
if runDyes == true
turnOnLocsTotal = [turnOnLocsTotal; turnOnLocs];
dyeTrackerTotal = [dyeTrackerTotal; dyeTracker];
onLocsTotal = [onLocsTotal; onLocs];
end
end
%save movie for this loop if its not linked
if linked == false && saveMovie == true %creates movie file for each loop
if runCorrosion == true
MovieWriter(corrosionMovie,strcat(filename, sprintf('_corrosion%d',h)), frameRate, Path);
end
if runDyes == true
MovieWriter(diffusionMovie,strcat(filename, sprintf('_dye%d',h)), frameRate, Path);
end
elseif linked == true
if runCorrosion == true
corrosionMovie=CreateFrameCorrosion(corrosionFig, corrosionMovie, CA, startTime, dT, frameRate, turnOnLocs, plotTurnOns);
end
if runDyes == true
diffusionMovie=CreateFrameDiffusion(dyeProps,px,[], diffusionMovie, diffusionFig, startTime, dT, frameRate,CA);
end
end
end %end simulation
%% save data and movie for whole run if it is linked
if saveData == true && linked == true
if runCorrosion == true
dlmwrite(strcat(Path,filename, sprintf('_corrosionTracker')),corrosionTrackerTotal);
dlmwrite(strcat(Path,filename, sprintf('_pitLocs')),pitLocsTotal);
end
if runDyes == true
dlmwrite(strcat(Path, filename, sprintf('_turnOnLocs')), turnOnLocsTotal);
dlmwrite(strcat(Path, filename, sprintf('_dyeTracker')), dyeTrackerTotal);
save(strcat(Path, filename, sprintf('OnLocations.mat')), 'onLocsTotal');
end
dlmwrite(strcat(Path,filename, sprintf('_CA%d',h)), CA);
end
if saveMovie == true && linked == true
if runCorrosion == true
MovieWriter(corrosionMovie, strcat(filename, sprintf('_corrosion')), frameRate, Path);
end
if runDyes == true
MovieWriter(diffusionMovie,strcat(filename, sprintf('_dye')), frameRate, Path);
end
end
%% Save metadata
if saveData == true || saveMovie == true
MetaData.pixels = px;
MetaData.pixelSize = pxsize;
MetaData.pixelSizeUnits = 'nm';
MetaData.numLoops = numLoops;
if runCorrosion == true
MetaData.corrosionTime = corrT;
MetaData.corrosionTimeStep = corrdT;
MetaData.corrosionTimeStepUnits = 's';
MetaData.Pinitiation = Pin;
MetaData.percentUncertaintyInPin = PinUncer;
MetaData.Pgrowth = Pgr;
%MetaData.exclusionZone = excl; (not currently using exlusion zone
%(12/18/2020)
else
MetaData.Corrosion = 'No Corrosion';
MetaData.PitRadius = pitrad;
MetaData.PitRadiusUnits = 'nm';
end
if runDyes == true
MetaData.Dye = dye;
MetaData.diffusionTime = diffT;
MetaData.diffusionTimeStep = diffdT;
MetaData.diffusionTimeStepUnits = 's';
MetaData.diffusionCoeff = D;
MetaData.diffusionCoeffUnits = 'nm^2/s';
MetaData.concentration = Conc;
MetaData.concentrationUnits = 'M/L';
MetaData.sensitivity = sensSigma;
MetaData.sensitivityUnits = 'nm';
MetaData.cathodeSigma = cathSigma;
MetaData.cathodeSigmaUnits = 'nm';
MetaData.SolutionVolume = Vol;
MetaData.SolutionVolumeUnit = 'L';
MetaData.SampleArea = Area;
MetaData.SampleAreaUnits = 'm';
MetaData.FlowRate = flowRate;
MetaData.FlowRateUnits = 'L/s';
else
MetaData.dyes = 'no dyes';
end
save(strcat(Path, filename,'_MetaData'),'-struct', 'MetaData');
end
%% end
toc
beep on;
beep; |
package com.conceiversolutions.hrsystem.performance.goal;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.conceiversolutions.hrsystem.user.user.User;
@CrossOrigin("*")
@RestController
@RequestMapping(path = "api/goal")
public class GoalController {
@Autowired
private final GoalService goalService;
public GoalController(GoalService goalService) {
this.goalService = goalService;
}
@GetMapping(path = "all/{year}")
public List<Goal> getAllGoalsByYear(@PathVariable("year") String year) throws Exception {
return goalService.getAllGoalsByYear(year);
}
@GetMapping(path = "{goalId}")
public Goal getGoalById(@PathVariable("goalId") Long goalId) throws Exception {
return goalService.getGoalById(goalId);
}
@PostMapping(path = "user/{userId}")
public Long addGoal(@RequestParam("type") String type, @RequestParam("description") String description,
@PathVariable("userId") Long userId) throws Exception {
return goalService.addGoal(type, description, userId);
}
@GetMapping(path = "{year}/type/{type}/user/{userId}")
public List<Goal> getUserGoalsForPeriod(@PathVariable("year") String year, @PathVariable("type") String type,
@PathVariable("userId") Long userId)
throws Exception {
return goalService.getUserGoalsForPeriod(year, type, userId);
}
@DeleteMapping(path = "{goalId}")
public String deleteUserGoal(@PathVariable("goalId") Long goalId) throws Exception {
return goalService.deleteUserGoal(goalId);
}
@PutMapping(path = "{goalId}")
public String updateUserGoal(@PathVariable("goalId") Long goalId, @RequestParam("description") String description) throws Exception {
return goalService.updateUserGoal(goalId, description);
}
@PostMapping(path = "/{goalId}/achievement")
public String addAchievement(@PathVariable("goalId") Long goalId, @RequestParam("description") String achievement) {
return goalService.addAchievement(goalId, achievement);
}
@GetMapping(path = "/users/{year}")
public List<User> getAllUserGoals(@PathVariable("year") String year) {
return goalService.getAllUserGoals(year);
}
@GetMapping(path = "/team/{teamId}/{year}")
public List<User> getTeamGoals(@PathVariable("teamId") Long teamId, @PathVariable("year") String year) {
return goalService.getTeamGoals(teamId, year);
}
@GetMapping(path ="/financeReminder/{userId}")
public String addFinanceReminderToUser(@PathVariable("userId") Long userId){
return goalService.addFinanceReminderToUser(userId);
}
@GetMapping(path ="/businessReminder/{userId}")
public String addBusinessReminderToUser(@PathVariable("userId") Long userId){
return goalService.addBusinessReminderToUser(userId);
}
@GetMapping(path = "/employee/{userId}")
public List<Goal> getUserGoals(@PathVariable("userId") Long userId) {
return goalService.getUserGoals(userId);
}
@GetMapping
public List<Goal> getAllGoals() {
return goalService.getAllGoals();
}
@GetMapping(path = "/overdue")
public List<Integer> getOverdueGoals() {
return goalService.getOverdueGoals();
}
@GetMapping(path = "{year}/count")
public List<Integer> getGoalCount(@PathVariable("year") String year) throws Exception {
return goalService.getGoalCount(year);
}
} |
<?php
declare(strict_types=1);
namespace App\Packages\Task\UseCase\Complete;
use App\Packages\Task\Domain\TaskRepositoryInterface;
use App\Packages\Task\UseCase\Complete\TaskCompleteCommand;
use App\Http\Controllers\Utils\Notification\MessageType;
use App\Packages\Util\Exceptions\DomainException;
use Exception;
final class TaskCompleteUseCase
{
public function __construct(private readonly TaskRepositoryInterface $repository)
{}
/**
* タスクを完了状態にする
*
* @param TaskCompleteCommand $command
* @return array
*/
public function execute(TaskCompleteCommand $command): array
{
try {
$task = $this->repository
->findById($command->taskId())
->complete();
$this->repository->save($task);
return MessageType::Saved->toArray();
} catch (DomainException $e) {
return MessageType::Error->toArray($e->getMessage());
} catch (Exception $e) {
return MessageType::Error->toArray($e->getMessage());
}
}
} |
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/* lib/krb5/asn.1/asn1_encode.h */
/*
* Copyright 1994, 2008 by the Massachusetts Institute of Technology.
* All Rights Reserved.
*
* Export of this software from the United States of America may
* require a specific license from the United States Government.
* It is the responsibility of any person or organization contemplating
* export to obtain such a license before exporting.
*
* WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
* distribute this software and its documentation for any purpose and
* without fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright notice and
* this permission notice appear in supporting documentation, and that
* the name of M.I.T. not be used in advertising or publicity pertaining
* to distribution of the software without specific, written prior
* permission. Furthermore if you modify this software you must label
* your software as modified software and not distribute it in such a
* fashion that it might be confused with the original M.I.T. software.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is" without express
* or implied warranty.
*/
#ifndef __ASN1_ENCODE_H__
#define __ASN1_ENCODE_H__
#include "k5-int.h"
#include "krbasn1.h"
#include "asn1buf.h"
#include <time.h>
/*
* Overview
*
* Each of these procedures inserts the encoding of an ASN.1
* primitive in a coding buffer.
*
* Operations
*
* asn1_encode_boolean
* asn1_encode_integer
* asn1_encode_unsigned_integer
* asn1_encode_octetstring
* asn1_encode_generaltime
* asn1_encode_generalstring
* asn1_encode_bitstring
* asn1_encode_oid
*/
asn1_error_code asn1_encode_boolean(asn1buf *buf, asn1_intmax val,
unsigned int *retlen);
asn1_error_code asn1_encode_integer(asn1buf *buf, asn1_intmax val,
unsigned int *retlen);
/*
* requires *buf is allocated
* modifies *buf, *retlen
* effects Inserts the encoding of val into *buf and returns
* the length of the encoding in *retlen.
* Returns ENOMEM to signal an unsuccesful attempt
* to expand the buffer.
*/
asn1_error_code asn1_encode_enumerated(asn1buf *buf, long val,
unsigned int *retlen);
asn1_error_code asn1_encode_unsigned_integer(asn1buf *buf, asn1_uintmax val,
unsigned int *retlen);
/*
* requires *buf is allocated
* modifies *buf, *retlen
* effects Inserts the encoding of val into *buf and returns
* the length of the encoding in *retlen.
* Returns ENOMEM to signal an unsuccesful attempt
* to expand the buffer.
*/
asn1_error_code asn1_encode_octetstring(asn1buf *buf, unsigned int len,
const void *val, unsigned int *retlen);
/*
* requires *buf is allocated
* modifies *buf, *retlen
* effects Inserts the encoding of val into *buf and returns
* the length of the encoding in *retlen.
* Returns ENOMEM to signal an unsuccesful attempt
* to expand the buffer.
*/
#define asn1_encode_charstring asn1_encode_octetstring
/**
* Encode @a val, an object identifier in compressed DER form without a tag or
* length. This function adds the OID tag and length.
*/
asn1_error_code asn1_encode_oid(asn1buf *buf, unsigned int len,
const void *val, unsigned int *retlen);
/*
* requires *buf is allocated
* modifies *buf, *retlen
* effects Inserts the encoding of val into *buf and returns
* the length of the encoding in *retlen.
* Returns ENOMEM to signal an unsuccesful attempt
* to expand the buffer.
*/
asn1_error_code asn1_encode_null(asn1buf *buf, int *retlen);
/*
* requires *buf is allocated
* modifies *buf, *retlen
* effects Inserts the encoding of NULL into *buf and returns
* the length of the encoding in *retlen.
* Returns ENOMEM to signal an unsuccesful attempt
* to expand the buffer.
*/
asn1_error_code asn1_encode_printablestring(asn1buf *buf, unsigned int len,
const char *val, int *retlen);
/*
* requires *buf is allocated
* modifies *buf, *retlen
* effects Inserts the encoding of val into *buf and returns
* the length of the encoding in *retlen.
* Returns ENOMEM to signal an unsuccesful attempt
* to expand the buffer.
*/
asn1_error_code asn1_encode_ia5string(asn1buf *buf, unsigned int len,
const char *val, int *retlen);
/*
* requires *buf is allocated
* modifies *buf, *retlen
* effects Inserts the encoding of val into *buf and returns
* the length of the encoding in *retlen.
* Returns ENOMEM to signal an unsuccesful attempt
* to expand the buffer.
*/
asn1_error_code asn1_encode_generaltime(asn1buf *buf, time_t val,
unsigned int *retlen);
/*
* requires *buf is allocated
* modifies *buf, *retlen
* effects Inserts the encoding of val into *buf and returns
* the length of the encoding in *retlen.
* Returns ENOMEM to signal an unsuccesful attempt
* to expand the buffer.
* Note: The encoding of GeneralizedTime is YYYYMMDDhhmmZ
*/
asn1_error_code asn1_encode_generalstring(asn1buf *buf,
unsigned int len, const void *val,
unsigned int *retlen);
/*
* requires *buf is allocated, val has a length of len characters
* modifies *buf, *retlen
* effects Inserts the encoding of val into *buf and returns
* the length of the encoding in *retlen.
* Returns ENOMEM to signal an unsuccesful attempt
* to expand the buffer.
*/
asn1_error_code asn1_encode_bitstring(asn1buf *buf, unsigned int len,
const void *val,
unsigned int *retlen);
/*
* requires *buf is allocated, val has a length of len characters
* modifies *buf, *retlen
* effects Inserts the encoding of val into *buf and returns
* the length of the encoding in *retlen.
* Returns ENOMEM to signal an unsuccesful attempt
* to expand the buffer.
*/
asn1_error_code asn1_encode_opaque(asn1buf *buf, unsigned int len,
const void *val,
unsigned int *retlen);
/*
* requires *buf is allocated, val has a length of len characters
* modifies *buf, *retlen
* effects Inserts the encoding of val into *buf and returns
* the length of the encoding in *retlen.
* Returns ENOMEM to signal an unsuccesful attempt
* to expand the buffer.
*/
/*
* Type descriptor info.
*
* In this context, a "type" is a combination of a C data type
* and an ASN.1 encoding scheme for it. So we would have to define
* different "types" for:
*
* * unsigned char* encoded as octet string
* * char* encoded as octet string
* * char* encoded as generalstring
* * krb5_data encoded as octet string
* * krb5_data encoded as generalstring
* * int32_t encoded as integer
* * unsigned char encoded as integer
*
* Perhaps someday some kind of flags could be defined so that minor
* variations on the C types could be handled via common routines.
*
* The handling of strings is pretty messy. Currently, we have a
* separate kind of encoder function that takes an extra length
* parameter. Perhaps we should just give up on that, always deal
* with just a single location, and handle strings by via encoder
* functions for krb5_data, keyblock, etc.
*
* We wind up with a lot of load-time relocations being done, which is
* a bit annoying. Be careful about "fixing" that at the cost of too
* much run-time performance. It might work to have a master "module"
* descriptor with pointers to various arrays (type descriptors,
* strings, field descriptors, functions) most of which don't need
* relocation themselves, and replace most of the pointers with table
* indices.
*
* It's a work in progress.
*/
enum atype_type {
/*
* For bounds checking only. By starting with values above 1, we
* guarantee that zero-initialized storage will be recognized as
* invalid.
*/
atype_min = 1,
/* Encoder function to be called with address of <thing>. */
atype_fn,
/*
* Encoder function to be called with address of <thing> and a
* length (unsigned int).
*/
atype_fn_len,
/*
* Pointer to actual thing to be encoded.
*
* Most of the fields are related only to the C type -- size, how
* to fetch a pointer in a type-safe fashion -- but since the base
* type descriptor encapsulates the encoding as well, different
* encodings for the same C type may require different pointer-to
* types as well.
*
* Must not refer to atype_fn_len.
*/
atype_ptr,
/* Sequence, with pointer to sequence descriptor header. */
atype_sequence,
/*
* Sequence-of, with pointer to base type descriptor, represented
* as a null-terminated array of pointers (and thus the "base"
* type descriptor is actually an atype_ptr node).
*/
atype_nullterm_sequence_of,
atype_nonempty_nullterm_sequence_of,
/*
* Encode this object using a single field descriptor. This may
* mean the atype/field breakdown needs revision....
*
* Main expected uses: Encode realm component of principal as a
* GENERALSTRING. Pluck data and length fields out of a structure
* and encode a counted SEQUENCE OF.
*/
atype_field,
/* Tagged version of another type. */
atype_tagged_thing,
/* Integer types. */
atype_int,
atype_uint,
/* Unused except for bounds checking. */
atype_max
};
/*
* Initialized structures could be a lot smaller if we could use C99
* designated initializers, and a union for all the type-specific
* stuff. Maybe use the hack we use for krb5int_access, where we use
* a run-time initialize if the compiler doesn't support designated
* initializers? That's a lot of work here, though, with so many
* little structures. Maybe if/when these get auto-generated.
*/
struct atype_info {
enum atype_type type;
/* used for sequence-of processing */
unsigned int size;
/* atype_fn */
asn1_error_code (*enc)(asn1buf *, const void *, unsigned int *);
/* atype_fn_len */
asn1_error_code (*enclen)(asn1buf *, unsigned int, const void *,
unsigned int *);
/* atype_ptr, atype_fn_len */
const void *(*loadptr)(const void *);
/* atype_ptr, atype_nullterm_sequence_of */
const struct atype_info *basetype;
/* atype_sequence */
const struct seq_info *seq;
/* atype_field */
const struct field_info *field;
/* atype_tagged_thing */
unsigned int tagval : 8, tagtype : 8, construction:8;
/* atype_[u]int */
asn1_intmax (*loadint)(const void *);
asn1_uintmax (*loaduint)(const void *);
};
/*
* The various DEF*TYPE macros must:
*
* + Define a type named aux_typedefname_##DESCNAME, for use in any
* types derived from the type being defined.
*
* + Define an atype_info struct named krb5int_asn1type_##DESCNAME.
*
* + Define any extra stuff needed in the type descriptor, like
* pointer-load functions.
*
* + Accept a following semicolon syntactically, to keep Emacs parsing
* (and indentation calculating) code happy.
*
* Nothing else should directly define the atype_info structures.
*/
/*
* Define a type for which we must use an explicit encoder function.
* The DEFFNTYPE variant uses a function taking a void*, the
* DEFFNXTYPE form wants a function taking a pointer to the actual C
* type to be encoded; you should use the latter unless you've already
* got the void* function supplied elsewhere.
*
* Of course, we need a single, consistent type for the descriptor
* structure field, so we use the function pointer type that uses
* void*, and create a wrapper function in DEFFNXTYPE. However, in
* all our cases so far, the supplied function is static and not used
* otherwise, so the compiler can merge it with the wrapper function
* if the optimizer is good enough.
*/
#define DEFFNTYPE(DESCNAME, CTYPENAME, ENCFN) \
typedef CTYPENAME aux_typedefname_##DESCNAME; \
const struct atype_info krb5int_asn1type_##DESCNAME = { \
atype_fn, sizeof(CTYPENAME), ENCFN, \
}
#define DEFFNXTYPE(DESCNAME, CTYPENAME, ENCFN) \
typedef CTYPENAME aux_typedefname_##DESCNAME; \
static asn1_error_code \
aux_encfn_##DESCNAME(asn1buf *buf, const void *val, \
unsigned int *retlen) \
{ \
return ENCFN(buf, \
(const aux_typedefname_##DESCNAME *)val, \
retlen); \
} \
const struct atype_info krb5int_asn1type_##DESCNAME = { \
atype_fn, sizeof(CTYPENAME), aux_encfn_##DESCNAME, \
}
/*
* XXX The handling of data+length fields really needs reworking.
* A type descriptor probably isn't the right way.
*
* Also, the C type is likely to be one of char*, unsigned char*,
* or (maybe) void*. An enumerator or reference to an external
* function would be more compact.
*
* The supplied encoder function takes as an argument the data pointer
* loaded from the indicated location, not the address of the field.
* This isn't consistent with DEFFN[X]TYPE above, but all of the uses
* of DEFFNLENTYPE are for string encodings, and that's how our
* string-encoding primitives work. So be it.
*/
#ifdef POINTERS_ARE_ALL_THE_SAME
#define DEFFNLENTYPE(DESCNAME, CTYPENAME, ENCFN) \
typedef CTYPENAME aux_typedefname_##DESCNAME; \
const struct atype_info krb5int_asn1type_##DESCNAME = { \
atype_fn_len, 0, 0, ENCFN, \
}
#else
#define DEFFNLENTYPE(DESCNAME, CTYPENAME, ENCFN) \
typedef CTYPENAME aux_typedefname_##DESCNAME; \
static const void *loadptr_for_##DESCNAME(const void *pv) \
{ \
const aux_typedefname_##DESCNAME *p = pv; \
return *p; \
} \
const struct atype_info krb5int_asn1type_##DESCNAME = { \
atype_fn_len, 0, 0, ENCFN, \
loadptr_for_##DESCNAME \
}
#endif
/*
* A sequence, defined by the indicated series of fields, and an
* optional function indicating which fields are present.
*/
#define DEFSEQTYPE(DESCNAME, CTYPENAME, FIELDS, OPT) \
typedef CTYPENAME aux_typedefname_##DESCNAME; \
static const struct seq_info aux_seqinfo_##DESCNAME = { \
OPT, FIELDS, sizeof(FIELDS)/sizeof(FIELDS[0]) \
}; \
const struct atype_info krb5int_asn1type_##DESCNAME = { \
atype_sequence, sizeof(CTYPENAME), 0,0,0,0, \
&aux_seqinfo_##DESCNAME, \
}
/* Integer types. */
#define DEFINTTYPE(DESCNAME, CTYPENAME) \
typedef CTYPENAME aux_typedefname_##DESCNAME; \
static asn1_intmax loadint_##DESCNAME(const void *p) \
{ \
assert(sizeof(CTYPENAME) <= sizeof(asn1_intmax)); \
return *(const aux_typedefname_##DESCNAME *)p; \
} \
const struct atype_info krb5int_asn1type_##DESCNAME = { \
atype_int, sizeof(CTYPENAME), 0, 0, 0, 0, 0, 0, 0, 0, 0, \
loadint_##DESCNAME, 0, \
}
#define DEFUINTTYPE(DESCNAME, CTYPENAME) \
typedef CTYPENAME aux_typedefname_##DESCNAME; \
static asn1_uintmax loaduint_##DESCNAME(const void *p) \
{ \
assert(sizeof(CTYPENAME) <= sizeof(asn1_uintmax)); \
return *(const aux_typedefname_##DESCNAME *)p; \
} \
const struct atype_info krb5int_asn1type_##DESCNAME = { \
atype_uint, sizeof(CTYPENAME), 0, 0, 0, 0, 0, 0, 0, 0, \
0, 0, loaduint_##DESCNAME, \
}
/* Pointers to other types, to be encoded as those other types. */
#ifdef POINTERS_ARE_ALL_THE_SAME
#define DEFPTRTYPE(DESCNAME,BASEDESCNAME) \
typedef aux_typedefname_##BASEDESCNAME * aux_typedefname_##DESCNAME; \
const struct atype_info krb5int_asn1type_##DESCNAME = { \
atype_ptr, sizeof(aux_typedefname_##DESCNAME), 0, 0, 0, \
&krb5int_asn1type_##BASEDESCNAME, 0 \
}
#else
#define DEFPTRTYPE(DESCNAME,BASEDESCNAME) \
typedef aux_typedefname_##BASEDESCNAME * aux_typedefname_##DESCNAME; \
static const void * \
loadptr_for_##BASEDESCNAME##_from_##DESCNAME(const void *p) \
{ \
const aux_typedefname_##DESCNAME *inptr = p; \
const aux_typedefname_##BASEDESCNAME *retptr; \
retptr = *inptr; \
return retptr; \
} \
const struct atype_info krb5int_asn1type_##DESCNAME = { \
atype_ptr, sizeof(aux_typedefname_##DESCNAME), 0, 0, \
loadptr_for_##BASEDESCNAME##_from_##DESCNAME, \
&krb5int_asn1type_##BASEDESCNAME, 0 \
}
#endif
/*
* This encodes a pointer-to-pointer-to-thing where the passed-in
* value points to a null-terminated list of pointers to objects to be
* encoded, and encodes a (possibly empty) SEQUENCE OF these objects.
*
* BASEDESCNAME is a descriptor name for the pointer-to-thing
* type.
*
* When dealing with a structure containing a
* pointer-to-pointer-to-thing field, make a DEFPTRTYPE of this type,
* and use that type for the structure field.
*/
#define DEFNULLTERMSEQOFTYPE(DESCNAME,BASEDESCNAME) \
typedef aux_typedefname_##BASEDESCNAME aux_typedefname_##DESCNAME; \
const struct atype_info krb5int_asn1type_##DESCNAME = { \
atype_nullterm_sequence_of, sizeof(aux_typedefname_##DESCNAME), \
0, 0, \
0 /* loadptr */, \
&krb5int_asn1type_##BASEDESCNAME, 0 \
}
#define DEFNONEMPTYNULLTERMSEQOFTYPE(DESCNAME,BASEDESCNAME) \
typedef aux_typedefname_##BASEDESCNAME aux_typedefname_##DESCNAME; \
const struct atype_info krb5int_asn1type_##DESCNAME = { \
atype_nonempty_nullterm_sequence_of, \
sizeof(aux_typedefname_##DESCNAME), \
0, 0, \
0 /* loadptr */, \
&krb5int_asn1type_##BASEDESCNAME, 0 \
}
/*
* Encode a thing (probably sub-fields within the structure) as a
* single object.
*/
#define DEFFIELDTYPE(DESCNAME, CTYPENAME, FIELDINFO) \
typedef CTYPENAME aux_typedefname_##DESCNAME; \
static const struct field_info aux_fieldinfo_##DESCNAME = FIELDINFO; \
const struct atype_info krb5int_asn1type_##DESCNAME = { \
atype_field, sizeof(CTYPENAME), 0, 0, 0, 0, 0, \
&aux_fieldinfo_##DESCNAME \
}
/* Objects with an APPLICATION tag added. */
#define DEFAPPTAGGEDTYPE(DESCNAME, TAG, BASEDESC) \
typedef aux_typedefname_##BASEDESC aux_typedefname_##DESCNAME; \
const struct atype_info krb5int_asn1type_##DESCNAME = { \
atype_tagged_thing, sizeof(aux_typedefname_##DESCNAME), \
0, 0, 0, &krb5int_asn1type_##BASEDESC, 0, 0, TAG, APPLICATION, \
CONSTRUCTED \
}
/**
* An encoding wrapped in an octet string
*/
#define DEFOCTETWRAPTYPE(DESCNAME, BASEDESC) \
typedef aux_typedefname_##BASEDESC aux_typedefname_##DESCNAME; \
const struct atype_info krb5int_asn1type_##DESCNAME = { \
atype_tagged_thing, sizeof(aux_typedefname_##DESCNAME), \
0, 0, 0, &krb5int_asn1type_##BASEDESC, 0, 0, ASN1_OCTETSTRING, \
UNIVERSAL, PRIMITIVE \
}
/*
* Declare an externally-defined type. This is a hack we should do
* away with once we move to generating code from a script. For now,
* this macro is unfortunately not compatible with the defining macros
* above, since you can't do the typedefs twice and we need the
* declarations to produce typedefs. (We could eliminate the typedefs
* from the DEF* macros, but then every DEF* macro use, even the ones
* for internal type nodes we only use to build other types, would
* need an accompanying declaration which explicitly lists the
* type.)
*/
#define IMPORT_TYPE(DESCNAME, CTYPENAME) \
typedef CTYPENAME aux_typedefname_##DESCNAME; \
extern const struct atype_info krb5int_asn1type_##DESCNAME
/*
* Create a partial-encoding function by the indicated name, for the
* indicated type. Should only be needed until we've converted all of
* the encoders, then everything should use descriptor tables.
*/
extern asn1_error_code
krb5int_asn1_encode_a_thing(asn1buf *buf, const void *val,
const struct atype_info *a, unsigned int *retlen);
#define MAKE_ENCFN(FNAME,DESC) \
static asn1_error_code FNAME(asn1buf *buf, \
const aux_typedefname_##DESC *val, \
unsigned int *retlen) \
{ \
return krb5int_asn1_encode_a_thing(buf, val, \
&krb5int_asn1type_##DESC, \
retlen); \
} \
extern int dummy /* gobble semicolon */
/*
* Sequence field descriptor.
*
* Currently we assume everything is a single object with a type
* descriptor, and then we bolt on some ugliness on the side for
* handling strings with length fields.
*
* Anything with "interesting" encoding handling, like a sequence-of
* or a pointer to the actual value to encode, is handled via opaque
* types with their own encoder functions. Most of that should
* eventually change.
*/
enum field_type {
/* Unused except for range checking. */
field_min = 1,
/* Field ATYPE describes processing of field at DATAOFF. */
field_normal,
/*
* Encode an "immediate" integer value stored in DATAOFF, with no
* reference to the data structure.
*/
field_immediate,
/*
* Encode some kind of string field encoded with pointer and
* length. (A GENERALSTRING represented as a null-terminated C
* string would be handled as field_normal.)
*/
field_string,
/*
* LENOFF indicates a value describing the length of the array at
* DATAOFF, encoded as a sequence-of with the element type
* described by ATYPE.
*/
field_sequenceof_len,
/* Unused except for range checking. */
field_max
};
/* To do: Consider using bitfields. */
struct field_info {
/* Type of the field. */
unsigned int /* enum field_type */ ftype : 3;
/*
* Use of DATAOFF and LENOFF are described by the value in FTYPE.
* Generally DATAOFF will be the offset from the supplied pointer
* at which we find the object to be encoded.
*/
unsigned int dataoff : 9, lenoff : 9;
/*
* If TAG is non-negative, a context tag with that value is added
* to the encoding of the thing. (XXX This would encode more
* compactly as an unsigned bitfield value tagnum+1, with 0=no
* tag.) The tag is omitted for optional fields that are not
* present.
*
* It's a bit illogical to combine the tag and other field info,
* since really a sequence field could have zero or several
* context tags, and of course a tag could be used elsewhere. But
* the normal mode in the Kerberos ASN.1 description is to use one
* context tag on each sequence field, so for now let's address
* that case primarily and work around the other cases (thus tag<0
* means skip tagging).
*/
signed int tag : 5;
/*
* If OPT is non-negative and the sequence header structure has a
* function pointer describing which fields are present, OPT is
* the bit position indicating whether the currently-described
* element is present. (XXX Similar encoding issue.)
*
* Note: Most of the time, I'm using the same number here as for
* the context tag. This is just because it's easier for me to
* keep track while working on the code by hand. The *only*
* meaningful correlation is of this value and the bits set by the
* "optional" function when examining the data structure.
*/
signed int opt : 5;
/*
* For some values of FTYPE, this describes the type of the
* object(s) to be encoded.
*/
const struct atype_info *atype;
/*
* We use different types for "length" fields in different places.
* So we need a good way to retrieve the various kinds of lengths
* in a compatible way. This may be a string length, or the
* length of an array of objects to encode in a SEQUENCE OF.
*
* In case the field is signed and negative, or larger than
* size_t, return SIZE_MAX as an error indication. We'll assume
* for now that we'll never have 4G-1 (or 2**64-1, or on tiny
* systems, 65535) sized values. On most if not all systems we
* care about, SIZE_MAX is equivalent to "all of addressable
* memory" minus one byte. That wouldn't leave enough extra room
* for the structure we're encoding, so it's pretty safe to assume
* SIZE_MAX won't legitimately come up on those systems.
*
* If this code gets ported to a segmented architecture or other
* system where it might be possible... figure it out then.
*/
const struct atype_info *lentype;
};
/*
* Normal or optional sequence fields at a particular offset, encoded
* as indicated by the listed DESCRiptor.
*/
#define FIELDOF_OPT(TYPE,DESCR,FIELDNAME,TAG,OPT) \
{ \
field_normal, OFFOF(TYPE, FIELDNAME, aux_typedefname_##DESCR), \
0, TAG, OPT, &krb5int_asn1type_##DESCR \
}
#define FIELDOF_NORM(TYPE,DESCR,FIELDNAME,TAG) \
FIELDOF_OPT(TYPE,DESCR,FIELDNAME,TAG,-1)
/*
* If encoding a subset of the fields of the current structure (for
* example, a flat structure describing data that gets encoded as a
* sequence containing one or more sequences), use ENCODEAS, no struct
* field name(s), and the indicated type descriptor must support the
* current struct type.
*/
#define FIELDOF_ENCODEAS(TYPE,DESCR,TAG) \
FIELDOF_ENCODEAS_OPT(TYPE,DESCR,TAG,-1)
#define FIELDOF_ENCODEAS_OPT(TYPE,DESCR,TAG,OPT) \
{ \
field_normal, \
0 * sizeof(0 ? (TYPE *)0 : (aux_typedefname_##DESCR *) 0), \
0, TAG, OPT, &krb5int_asn1type_##DESCR \
}
/*
* Reinterpret some subset of the structure itself as something
* else.
*/
#define FIELD_SELF(DESCR, TAG) \
{ field_normal, 0, 0, TAG, -1, &krb5int_asn1type_##DESCR }
#define FIELDOF_OPTSTRINGL(STYPE,DESC,PTRFIELD,LENDESC,LENFIELD,TAG,OPT) \
{ \
field_string, \
OFFOF(STYPE, PTRFIELD, aux_typedefname_##DESC), \
OFFOF(STYPE, LENFIELD, aux_typedefname_##LENDESC), \
TAG, OPT, &krb5int_asn1type_##DESC, &krb5int_asn1type_##LENDESC \
}
#define FIELDOF_OPTSTRING(STYPE,DESC,PTRFIELD,LENFIELD,TAG,OPT) \
FIELDOF_OPTSTRINGL(STYPE,DESC,PTRFIELD,uint,LENFIELD,TAG,OPT)
#define FIELDOF_STRINGL(STYPE,DESC,PTRFIELD,LENDESC,LENFIELD,TAG) \
FIELDOF_OPTSTRINGL(STYPE,DESC,PTRFIELD,LENDESC,LENFIELD,TAG,-1)
#define FIELDOF_STRING(STYPE,DESC,PTRFIELD,LENFIELD,TAG) \
FIELDOF_OPTSTRING(STYPE,DESC,PTRFIELD,LENFIELD,TAG,-1)
#define FIELD_INT_IMM(VALUE,TAG) \
{ field_immediate, VALUE, 0, TAG, -1, 0, }
#define FIELDOF_SEQOF_LEN(STYPE,DESC,PTRFIELD,LENFIELD,LENTYPE,TAG) \
{ \
field_sequenceof_len, \
OFFOF(STYPE, PTRFIELD, aux_typedefname_##DESC), \
OFFOF(STYPE, LENFIELD, aux_typedefname_##LENTYPE), \
TAG, -1, &krb5int_asn1type_##DESC, &krb5int_asn1type_##LENTYPE \
}
#define FIELDOF_SEQOF_INT32(STYPE,DESC,PTRFIELD,LENFIELD,TAG) \
FIELDOF_SEQOF_LEN(STYPE,DESC,PTRFIELD,LENFIELD,int32,TAG)
struct seq_info {
/*
* If present, returns a bitmask indicating which fields are
* present. See the "opt" field in struct field_info.
*/
unsigned int (*optional)(const void *);
/* Indicates an array of sequence field descriptors. */
const struct field_info *fields;
size_t n_fields;
/* Missing: Extensibility handling. (New field type?) */
};
extern krb5_error_code
krb5int_asn1_do_full_encode(const void *rep, krb5_data **code,
const struct atype_info *a);
#define MAKE_FULL_ENCODER(FNAME, DESC) \
krb5_error_code FNAME(const aux_typedefname_##DESC *rep, \
krb5_data **code) \
{ \
return krb5int_asn1_do_full_encode(rep, code, \
&krb5int_asn1type_##DESC); \
} \
extern int dummy /* gobble semicolon */
#include <stddef.h>
/*
* Ugly hack!
* Like "offsetof", but with type checking.
*/
#define WARN_IF_TYPE_MISMATCH(LVALUE, TYPE) \
(sizeof(0 ? (TYPE *) 0 : &(LVALUE)))
#define OFFOF(TYPE,FIELD,FTYPE) \
(offsetof(TYPE, FIELD) \
+ 0 * WARN_IF_TYPE_MISMATCH(((TYPE*)0)->FIELD, FTYPE))
#endif |
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package devicefarm
import (
"context"
"fmt"
"log"
"strings"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/devicefarm"
awstypes "github.com/aws/aws-sdk-go-v2/service/devicefarm/types"
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/hashicorp/terraform-provider-aws/internal/conns"
"github.com/hashicorp/terraform-provider-aws/internal/enum"
"github.com/hashicorp/terraform-provider-aws/internal/errs"
"github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag"
tftags "github.com/hashicorp/terraform-provider-aws/internal/tags"
"github.com/hashicorp/terraform-provider-aws/internal/tfresource"
"github.com/hashicorp/terraform-provider-aws/internal/verify"
"github.com/hashicorp/terraform-provider-aws/names"
)
// @SDKResource("aws_devicefarm_device_pool", name="Device Pool")
// @Tags(identifierAttribute="arn")
func ResourceDevicePool() *schema.Resource {
return &schema.Resource{
CreateWithoutTimeout: resourceDevicePoolCreate,
ReadWithoutTimeout: resourceDevicePoolRead,
UpdateWithoutTimeout: resourceDevicePoolUpdate,
DeleteWithoutTimeout: resourceDevicePoolDelete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
Schema: map[string]*schema.Schema{
names.AttrARN: {
Type: schema.TypeString,
Computed: true,
},
names.AttrName: {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(0, 256),
},
names.AttrDescription: {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(0, 16384),
},
"max_devices": {
Type: schema.TypeInt,
Optional: true,
},
"project_arn": {
Type: schema.TypeString,
Required: true,
ValidateFunc: verify.ValidARN,
},
names.AttrRule: {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"attribute": {
Type: schema.TypeString,
Optional: true,
ValidateDiagFunc: enum.Validate[awstypes.DeviceAttribute](),
},
"operator": {
Type: schema.TypeString,
Optional: true,
ValidateDiagFunc: enum.Validate[awstypes.RuleOperator](),
},
names.AttrValue: {
Type: schema.TypeString,
Optional: true,
},
},
},
},
names.AttrType: {
Type: schema.TypeString,
Computed: true,
},
names.AttrTags: tftags.TagsSchema(),
names.AttrTagsAll: tftags.TagsSchemaComputed(),
},
CustomizeDiff: verify.SetTagsDiff,
}
}
func resourceDevicePoolCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var diags diag.Diagnostics
conn := meta.(*conns.AWSClient).DeviceFarmClient(ctx)
name := d.Get(names.AttrName).(string)
input := &devicefarm.CreateDevicePoolInput{
Name: aws.String(name),
ProjectArn: aws.String(d.Get("project_arn").(string)),
Rules: expandDevicePoolRules(d.Get(names.AttrRule).(*schema.Set)),
}
if v, ok := d.GetOk(names.AttrDescription); ok {
input.Description = aws.String(v.(string))
}
if v, ok := d.GetOk("max_devices"); ok {
input.MaxDevices = aws.Int32(int32(v.(int)))
}
output, err := conn.CreateDevicePool(ctx, input)
if err != nil {
return sdkdiag.AppendErrorf(diags, "creating DeviceFarm Device Pool (%s): %s", name, err)
}
d.SetId(aws.ToString(output.DevicePool.Arn))
if err := createTags(ctx, conn, d.Id(), getTagsIn(ctx)); err != nil {
return sdkdiag.AppendErrorf(diags, "setting DeviceFarm Device Pool (%s) tags: %s", d.Id(), err)
}
return append(diags, resourceDevicePoolRead(ctx, d, meta)...)
}
func resourceDevicePoolRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var diags diag.Diagnostics
conn := meta.(*conns.AWSClient).DeviceFarmClient(ctx)
devicePool, err := FindDevicePoolByARN(ctx, conn, d.Id())
if !d.IsNewResource() && tfresource.NotFound(err) {
log.Printf("[WARN] DeviceFarm Device Pool (%s) not found, removing from state", d.Id())
d.SetId("")
return diags
}
if err != nil {
return sdkdiag.AppendErrorf(diags, "reading DeviceFarm Device Pool (%s): %s", d.Id(), err)
}
arn := aws.ToString(devicePool.Arn)
d.Set(names.AttrName, devicePool.Name)
d.Set(names.AttrARN, arn)
d.Set(names.AttrDescription, devicePool.Description)
d.Set("max_devices", devicePool.MaxDevices)
projectArn, err := decodeProjectARN(arn, "devicepool", meta)
if err != nil {
return sdkdiag.AppendErrorf(diags, "decoding project_arn (%s): %s", arn, err)
}
d.Set("project_arn", projectArn)
if err := d.Set(names.AttrRule, flattenDevicePoolRules(devicePool.Rules)); err != nil {
return sdkdiag.AppendErrorf(diags, "setting rule: %s", err)
}
return diags
}
func resourceDevicePoolUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var diags diag.Diagnostics
conn := meta.(*conns.AWSClient).DeviceFarmClient(ctx)
if d.HasChangesExcept(names.AttrTags, names.AttrTagsAll) {
input := &devicefarm.UpdateDevicePoolInput{
Arn: aws.String(d.Id()),
}
if d.HasChange(names.AttrName) {
input.Name = aws.String(d.Get(names.AttrName).(string))
}
if d.HasChange(names.AttrDescription) {
input.Description = aws.String(d.Get(names.AttrDescription).(string))
}
if d.HasChange(names.AttrRule) {
input.Rules = expandDevicePoolRules(d.Get(names.AttrRule).(*schema.Set))
}
if d.HasChange("max_devices") {
if v, ok := d.GetOk("max_devices"); ok {
input.MaxDevices = aws.Int32(int32(v.(int)))
} else {
input.ClearMaxDevices = aws.Bool(true)
}
}
_, err := conn.UpdateDevicePool(ctx, input)
if err != nil {
return sdkdiag.AppendErrorf(diags, "updating DeviceFarm Device Pool (%s): %s", d.Id(), err)
}
}
return append(diags, resourceDevicePoolRead(ctx, d, meta)...)
}
func resourceDevicePoolDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var diags diag.Diagnostics
conn := meta.(*conns.AWSClient).DeviceFarmClient(ctx)
log.Printf("[DEBUG] Deleting DeviceFarm Device Pool: %s", d.Id())
_, err := conn.DeleteDevicePool(ctx, &devicefarm.DeleteDevicePoolInput{
Arn: aws.String(d.Id()),
})
if errs.IsA[*awstypes.NotFoundException](err) {
return diags
}
if err != nil {
return sdkdiag.AppendErrorf(diags, "deleting DeviceFarm Device Pool (%s): %s", d.Id(), err)
}
return diags
}
func expandDevicePoolRules(s *schema.Set) []awstypes.Rule {
rules := make([]awstypes.Rule, 0)
for _, r := range s.List() {
rule := awstypes.Rule{}
tfMap := r.(map[string]interface{})
if v, ok := tfMap["attribute"].(string); ok && v != "" {
rule.Attribute = awstypes.DeviceAttribute(v)
}
if v, ok := tfMap["operator"].(string); ok && v != "" {
rule.Operator = awstypes.RuleOperator(v)
}
if v, ok := tfMap[names.AttrValue].(string); ok && v != "" {
rule.Value = aws.String(v)
}
rules = append(rules, rule)
}
return rules
}
func flattenDevicePoolRules(list []awstypes.Rule) []map[string]interface{} {
if len(list) == 0 {
return nil
}
result := make([]map[string]interface{}, 0, len(list))
for _, setting := range list {
l := map[string]interface{}{}
l["attribute"] = string(setting.Attribute)
l["operator"] = string(setting.Operator)
if setting.Value != nil {
l[names.AttrValue] = aws.ToString(setting.Value)
}
result = append(result, l)
}
return result
}
func decodeProjectARN(id, typ string, meta interface{}) (string, error) {
poolArn, err := arn.Parse(id)
if err != nil {
return "", fmt.Errorf("parsing '%s': %w", id, err)
}
poolArnResouce := poolArn.Resource
parts := strings.Split(strings.TrimPrefix(poolArnResouce, typ+":"), "/")
if len(parts) != 2 {
return "", fmt.Errorf("Unexpected format of ID (%q), expected project-id/%q-id", poolArnResouce, typ)
}
projectId := parts[0]
projectArn := arn.ARN{
AccountID: meta.(*conns.AWSClient).AccountID,
Partition: meta.(*conns.AWSClient).Partition,
Region: meta.(*conns.AWSClient).Region,
Resource: "project:" + projectId,
Service: names.DeviceFarmEndpointID,
}.String()
return projectArn, nil
} |
import mongoose from "mongoose";
import { AssetSchema } from "../app/interfaces.js";
const asset = new mongoose.Schema({
// NXID of the associated part
asset_tag: { type: String, required: true },
// ID of the previous record, nul if oldest iteration of record
prev: { type: String, default: null },
// ID of the next record, null if newest iteration of record
next: { type: String, default: null},
// Location: LA - 1, OG - 3, NY - 4
building: { type: Number, required: true },
// Asset type
asset_type: { type: String },
// Chassis type
chassis_type: { type: String},
// Manufacturer
manufacturer: { type: String },
// Model name
model: { type: String },
// Serial number
serial: { type: String },
// Has rails
rails: { type: Boolean },
// Cheater rails?
cheat: {type: Boolean},
// 1U, 2U, 3U, etc.
units: { type: Number },
// POWER SUPPLY
num_psu: { type: Number },
psu_model: { type: String },
// Node
parent: { type: String },
// Cable length
cable_type: { type: String },
num_bays: { type: Number },
bay_type: { type: String },
pallet: { type: String },
fw_rev: { type: String },
migrated: { type: Boolean },
// Status
live: { type: Boolean, default: false},
in_rack: { type: Boolean },
// Bay
bay: { type: Number },
// Physical location
power_port: { type: String },
public_port: { type: String },
private_port: { type: String },
ipmi_port: { type: String },
// Emails from migration
old_by: { type: String },
// Last updated by
by: { type: String, required: true },
sid: { type: Number },
// Pallet info chanaged
prev_pallet: { type: String },
next_pallet: { type: String },
// Parts
// Date the part was created
date_created: { type: Date },
date_updated: { type: Date },
date_replaced: { type: Date, default: null },
notes: { type: String }
});
asset.index({
'notes': 'text',
'sid': 'text',
'pallet': 'text',
'manufacturer': 'text',
'model': 'text',
'serial': 'text',
'power_port': 'text',
'public_port': 'text',
'private_port': 'text',
'ipmi_port': 'text'
});
// Add index here
export default mongoose.model<AssetSchema>("asset", asset); |
import { useState,useEffect } from 'react'
import NavBar from './components/Navbar'
import { Routes, Route } from 'react-router-dom'
import {Books, Login, Profile, Register, SingleBook} from './pages'
import './App.css'
function App() {
const [user,setUser] = useState(null);
console.log(user);
return (
<div>
<NavBar user={user}/>
<Routes>
<Route path="/books" element= {<Books />} />
<Route path="/singleBook" element={<SingleBook /> } />
<Route path="/login" element={<Login user={user} setUser= {setUser}/>} />
<Route path="/register" element={<Register user={user} setUser= {setUser} />} />
<Route path="/profile" element={<Profile user={user} />} />
</Routes>
</div>
)
}
export default App |
package hbc_loadTests.helpers
/**
* Created by aindana on 1/6/2017.
*/
import java.util.concurrent.TimeUnit
import java.util.regex.Pattern
import com.mongodb.casbah.commons.MongoDBObject
import org.mongodb.scala._
import com.mongodb.casbah.Imports._
import scala.concurrent.Await
import scala.concurrent.duration.Duration
object Helpers {
implicit class DocumentObservable[C](val observable: Observable[Document]) extends ImplicitObservable[Document] {
override val converter: (Document) => String = (doc) => doc.toJson
}
implicit class GenericObservable[C](val observable: Observable[C]) extends ImplicitObservable[C] {
override val converter: (C) => String = (doc) => doc.toString
}
trait ImplicitObservable[C] {
val observable: Observable[C]
val converter: (C) => String
def results(): Seq[C] = Await.result(observable.toFuture(), Duration(10, TimeUnit.SECONDS))
def headResult() = Await.result(observable.head(), Duration(10, TimeUnit.SECONDS))
def printResults(initial: String = ""): Unit = {
if (initial.length > 0) print(initial)
results().foreach(res => println(converter(res)))
}
def printHeadResult(initial: String = ""): Unit = println(s"${initial}${converter(headResult())}")
def listResults(): List[String] = {
val listOfString = scala.collection.mutable.ListBuffer.empty[String]
results().foreach(res => listOfString += (converter(res)))
listOfString.toList
}
}
} |
/*
* Tai-e: A Static Analysis Framework for Java
*
* Copyright (C) 2022 Tian Tan <tiantan@nju.edu.cn>
* Copyright (C) 2022 Yue Li <yueli@nju.edu.cn>
*
* This file is part of Tai-e.
*
* Tai-e is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* Tai-e is distributed in the hope that it will be useful,but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
* Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Tai-e. If not, see <https://www.gnu.org/licenses/>.
*/
package pascal.taie.analysis.graph.callgraph;
import pascal.taie.World;
import pascal.taie.ir.proginfo.MethodRef;
import pascal.taie.ir.stmt.Invoke;
import pascal.taie.ir.stmt.Stmt;
import pascal.taie.language.classes.ClassHierarchy;
import pascal.taie.language.classes.JClass;
import pascal.taie.language.classes.JMethod;
import pascal.taie.language.classes.Subsignature;
import pascal.taie.language.type.ClassType;
import polyglot.ast.Call;
import java.util.*;
import java.util.stream.Stream;
/**
* Implementation of the CHA algorithm.
*/
class CHABuilder implements CGBuilder<Invoke, JMethod> {
private ClassHierarchy hierarchy;
@Override
public CallGraph<Invoke, JMethod> build() {
hierarchy = World.get().getClassHierarchy();
return buildCallGraph(World.get().getMainMethod());
}
private CallGraph<Invoke, JMethod> buildCallGraph(JMethod entry) {
DefaultCallGraph callGraph = new DefaultCallGraph();
callGraph.addEntryMethod(entry);
Queue<JMethod> workList = new LinkedList<>();
workList.add(entry);
while (!workList.isEmpty()){
JMethod method = workList.poll();
if(callGraph.contains(method)){
continue;
}
callGraph.addReachableMethod(method);
method.getIR().getStmts().stream().
filter(stmt -> stmt instanceof Invoke).forEach(stmt -> {
Invoke callSite = (Invoke) stmt;
CallKind kind = null;
if(callSite.isInterface()) kind = CallKind.INTERFACE;
else if(callSite.isSpecial()) kind = CallKind.SPECIAL;
else if(callSite.isStatic()) kind = CallKind.STATIC;
else if(callSite.isVirtual()) kind = CallKind.VIRTUAL;
if(kind != null){
for(JMethod newMethod : resolve(callSite)){
callGraph.addEdge(new Edge<>(kind, callSite, newMethod));
workList.add(newMethod);
}
}
});
}
return callGraph;
}
/**
* Resolves call targets (callees) of a call site via CHA.
*/
private Set<JMethod> resolve(Invoke callSite) {
MethodRef methodRef = callSite.getMethodRef();
Set<JMethod> result = new HashSet<>();
if(callSite.isInterface() || callSite.isVirtual()){
JClass rootCls = methodRef.getDeclaringClass();
Queue<JClass> queue = new LinkedList<>();
queue.add(rootCls);
while(!queue.isEmpty()){
JClass cls = queue.poll();
JMethod dispatchedMethod = dispatch(cls, methodRef.getSubsignature());
if(dispatchedMethod != null){
result.add(dispatchedMethod);
}
if(cls.isInterface()){
queue.addAll(hierarchy.getDirectSubinterfacesOf(cls));
queue.addAll(hierarchy.getDirectImplementorsOf(cls));
}else{
queue.addAll(hierarchy.getDirectSubclassesOf(cls));
}
}
}else if(callSite.isSpecial()){
JMethod method = dispatch(methodRef.getDeclaringClass(), methodRef.getSubsignature());
if(method != null) {
result.add(method);
}
}else if(callSite.isStatic()){
result.add(methodRef.getDeclaringClass().getDeclaredMethod(methodRef.getSubsignature()));
}
return result;
}
/**
* Looks up the target method based on given class and method subsignature.
*
* @return the dispatched target method, or null if no satisfying method
* can be found.
*/
private JMethod dispatch(JClass jclass, Subsignature subsignature) {
JMethod method = jclass.getDeclaredMethod(subsignature);
if(method != null && !method.isAbstract()){
return method;
}else if(jclass.getSuperClass() == null){
return null;
}
return dispatch(jclass.getSuperClass(), subsignature);
}
} |
package com.day26.利用反射去获取成员变量;
import java.lang.reflect.Field;
public class test {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
//getFields() ---返回所有的公共成员变量对象的数组
//getDeclareFields()---返回所有成员变量对象的数组
//getField()------返回单个公共成员变量对象
//getDeclareField()----返回单个成员变量对象
//获取以后可以进行赋值和获取值
Class<?> kk = Class.forName("com.day26.利用反射去获取成员变量.Student");
//1
/*Field[] fields = kk.getFields();
for (Field field : fields) {
System.out.println(field);
}*/
//2
/*Field[] fields = kk.getDeclaredFields();
for (Field field : fields) {
System.out.println(field);
}*/
//3
Field gender = kk.getField("gender");
System.out.println(gender);
//4
Field age = kk.getDeclaredField("age");
System.out.println(age);
//权限修饰符
int modifiers1 = gender.getModifiers();
System.out.println(modifiers1);
int modifiers = age.getModifiers();
System.out.println(modifiers);
//获取成员变量名
String name = age.getName();
System.out.println(name);
//获取数据类型
Class<?> type = age.getType();
System.out.println(type);
//获取值
Student s=new Student("张三",23,"男");
//不能直接访问私有的--临时忽略权限修饰符
age.setAccessible(true);
Object o = age.get(s);
System.out.println(o);
//修改值
age.set(s,25);
System.out.println(s);
}
} |
package com.jewel.onlineelectoralsystem.service;
import com.jewel.onlineelectoralsystem.dto.ReqRes;
import com.jewel.onlineelectoralsystem.model.OurUsers;
import com.jewel.onlineelectoralsystem.model.RefreshToken;
import com.jewel.onlineelectoralsystem.repository.OurUserRepo;
import com.jewel.onlineelectoralsystem.repository.RefreshTokenRepo;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.HashMap;
@Service
public class AuthService {
@Autowired
private OurUserRepo ourUserRepo;
@Autowired
private JWTUtils jwtUtils;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private RefreshTokenRepo refreshTokenRepo;
public ReqRes signUp(ReqRes registrationRequest){
ReqRes resp = new ReqRes();
try{
if(ourUserRepo.findByVoterId(registrationRequest.getVoterId()).orElse(null) != null){
resp.setMessage("Already sign up");
resp.setStatusCode(409);
return resp;
}
OurUsers ourUsers = new OurUsers();
//ourUsers.setId(null);
ourUsers.setVoterId(registrationRequest.getVoterId());
ourUsers.setPassword(passwordEncoder.encode(registrationRequest.getPassword()));
ourUsers.setRole(registrationRequest.getRole());
OurUsers ourUserResult = ourUserRepo.save(ourUsers);
if(ourUserResult != null ){
resp.setOurUsers(ourUserResult);
resp.setMessage("User saved successfully");
resp.setStatusCode(200);
}
}catch (Exception e){
resp.setStatusCode(500);
resp.setError(e.getMessage());
}
return resp;
}
public ReqRes signIn(ReqRes signinRequest){
ReqRes response = new ReqRes();
try{
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(signinRequest.getVoterId(),signinRequest.getPassword()));
var user = ourUserRepo.findByVoterId(signinRequest.getVoterId()).orElseThrow(); //wrong password or email hole throw korbe
var jwt = jwtUtils.generateToken(user);
var refreshToken = jwtUtils.generateRefreshToken(new HashMap<>(),user);
response.setStatusCode(200);
response.setToken(jwt);
response.setRefreshToken(refreshToken);
response.setExpireTime("24Hr");
response.setMessage("successfully signed In");
RefreshToken existingRefreshToken = refreshTokenRepo.findByVoterId(user.getVoterId());
if(existingRefreshToken != null) {
existingRefreshToken.setRefreshToken(refreshToken);
refreshTokenRepo.save(existingRefreshToken);
}else{
refreshTokenRepo.save(new RefreshToken(refreshToken,user.getVoterId()));
}
return response;
}catch (Exception e){
response.setStatusCode(500);
response.setError(e.getMessage());
}
return response;
}
public ReqRes refreshToken(ReqRes refreshTokenRequest){ //ekta refresh token asbe
ReqRes response = new ReqRes();
try
{
String ourVoterId = jwtUtils.extractUserName(refreshTokenRequest.getRefreshToken()); //extract voterId
OurUsers users = ourUserRepo.findByVoterId(ourVoterId).orElseThrow();
if(users != null && jwtUtils.isTokenValid(refreshTokenRequest.getRefreshToken(),users)){
var jwt = jwtUtils.generateToken(users);
var refreshToken = jwtUtils.generateRefreshToken(new HashMap<>(),users);
response.setStatusCode(200);
response.setToken(jwt);
response.setRefreshToken(refreshToken);
response.setExpireTime("1 minutes");
response.setMessage("successfully refreshed token");
createSecureCookie("accessToken",jwt,JWTUtils.EXPIRATION_TIME/1000);
createSecureCookie("refreshToken",refreshToken,JWTUtils.EXPIRATION_TIME_REFRESH/1000);
//
// refreshTokenRepo.deleteByVoterId(ourVoterId);
// refreshTokenRepo.save(new RefreshToken(refreshToken,users.getVoterId()));
// return response;
}else {
response.setStatusCode(422);
response.setMessage("UnProcessed-able entity");
}
return response;
}
catch (Exception e){
response.setStatusCode(500);
response.setMessage(e.getMessage());
}
return response;
}
// Helper method for creating secure cookies
public Cookie createSecureCookie(String name, String value, long maxAgeSeconds) {
Cookie cookie = new Cookie(name, value);
cookie.setPath("/");
cookie.setHttpOnly(true); // Prevent JavaScript access
cookie.setSecure(true); // Send only over HTTPS (recommended)
cookie.setMaxAge((int) maxAgeSeconds);
return cookie;
}
} |
import bcrypt from 'bcrypt';
import db from '../models/index'
const salt = bcrypt.genSaltSync(10);
let createNewUser = async (data) => {
return new Promise (async(resolve,reject) =>{
try {
let hasPasswordFromBcrypt = await hashUserPassword(data.password)
await db.User.create({
email: data.email,
password:hasPasswordFromBcrypt,
firstName: data.FirstName,
lastName: data.LastName,
address:data.Address,
phonenumber : data.PhoneNumber,
gender:data.gender === '1' ? true : false,
roleId : data.roleId,
})
resolve('ok create new')
} catch (error) {
reject(error)
}
})
}
let hashUserPassword = (password) => {
return new Promise(async(resolve,reject)=>{
try {
var hashPassword = await bcrypt.hashSync(password,salt)
resolve(hashPassword)
} catch (error) {
reject(error)
}
})
}
let getUserInfoById = (userId) => {
return new Promise(async (resolve,reject) => {
try {
let user = db.User.findOne({
where: {id : userId}
})
if(user){
resolve(user)
}else{
resolve([])
}
} catch (error) {
reject(error)
}
})
}
let getAllUser = () => {
return new Promise(async(resolve,reject) => {
try {
let users = db.User.findAll({
row : true
})
resolve(users)
} catch (error) {
reject(error)
}
})
}
let updateUserDate = (data) =>{
return new Promise (async(resolve,reject) =>{
try {
let user = await db.User.findOne({
where : {id: data.id}
})
if(user){
user.email = data.email
user.firstName = data.FirstName
user.lastName = data.LastName
user.address = data.Address
await user.save()
let allUser = await db.User.findAll()
resolve(allUser)
}else{
resolve()
}
} catch (error) {
reject(error)
}
})
}
let deleteUserById = (id) => {
return new Promise (async(resolve,reject) => {
try {
let user = await db.User.findOne({
where: {id : id}
})
if(user) {
await user.destroy()
}
resolve()
} catch (error) {
reject(error)
}
})
}
module.exports = {
createNewUser:createNewUser,
getAllUser: getAllUser,
getUserInfoById: getUserInfoById,
updateUserDate : updateUserDate,
deleteUserById: deleteUserById,
} |
package asedinfo.com.controlador.catalogo;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import asedinfo.com.controlador.util.Constantes;
import asedinfo.com.modelo.DTO.PrefijoTelefonicoDTO;
import asedinfo.com.modelo.catalogo.Persona;
import asedinfo.com.modelo.response.ResponseGenerico;
import asedinfo.com.servicio.catalogo.PersonaServicio;
import asedinfo.com.venta.resources.EstadoEnum;
@RestController
@RequestMapping("catalogo/")
public class PersonaControlador {
@Autowired
private PersonaServicio personaServicio;
@GetMapping(value = "listarTodosPersona")
public ResponseGenerico<Persona> listarTodosPersona() {
List<Persona> listaPersona = personaServicio.listarTodosPersona();
// Respuesta
ResponseGenerico<Persona> response = new ResponseGenerico<>();
response.setListado(listaPersona);
response.setTotalRegistros((long) listaPersona.size());
response.setCodigoRespuesta(Constantes.CODIGO_RESPUESTA_OK);
response.setMensaje(Constantes.MENSAJE_OK);
return response;
}
@GetMapping(value = "listarPersonaActivo")
public ResponseGenerico<Persona> listarPersonaActivo() {
List<Persona> listaPersona = personaServicio.listarPersonaActivo(EstadoEnum.ACTIVO.getDescripcion());
// Respuesta
ResponseGenerico<Persona> response = new ResponseGenerico<>();
response.setListado(listaPersona);
response.setTotalRegistros((long) listaPersona.size());
response.setCodigoRespuesta(Constantes.CODIGO_RESPUESTA_OK);
response.setMensaje(Constantes.MENSAJE_OK);
return response;
}
@GetMapping(value = "listarPersonaPorIdentificacion/{identificacion}")
public ResponseGenerico<Persona> listarPersonaPorIdentificacion(@PathVariable("identificacion") String identificacion) {
List<Persona> listaPersona = personaServicio.listarPersonaPorIdentificacion(identificacion);
// Respuesta
ResponseGenerico<Persona> response = new ResponseGenerico<>();
response.setListado(listaPersona);
response.setTotalRegistros((long) listaPersona.size());
response.setCodigoRespuesta(Constantes.CODIGO_RESPUESTA_OK);
response.setMensaje(Constantes.MENSAJE_OK);
return response;
}
/**
* REST para obtener Persona
*
* @return Persona
*/
@GetMapping(value = "buscarPersonaPorCodigo/{codigo}")
public ResponseGenerico<Persona> buscarPersonaPorCodigo(@PathVariable("codigo") Long codigo) {
Persona persona = personaServicio.buscarPersonaPorCodigo(codigo);
// Respuesta
ResponseGenerico<Persona> response = new ResponseGenerico<>();
response.setObjeto(persona);
response.setTotalRegistros((long) (1));
response.setCodigoRespuesta(Constantes.CODIGO_RESPUESTA_OK);
response.setMensaje(Constantes.MENSAJE_OK);
return response;
}
/**
* REST para guardar o actualizar persona
*
* @return guardar
*/
@PostMapping(value = "guardarPersona")
public ResponseGenerico<Persona> guardarPersona(@RequestBody Persona persona) {
persona = personaServicio.registrar(persona);
// Respuesta
ResponseGenerico<Persona> response = new ResponseGenerico<>();
response.setObjeto(persona);
response.setCodigoRespuesta(Constantes.CODIGO_RESPUESTA_OK);
response.setMensaje(Constantes.MENSAJE_OK_CREADO);
return response;
}
/**
* Metodo para eliminar (baja lógica) un registro
*
* @return objeto response
*/
@DeleteMapping(value = "eliminarPersonaPorId/{codigo}")
public ResponseGenerico<Persona> eliminarPersona(@PathVariable("codigo") Long codigo) {
Persona persona = personaServicio.buscarPersonaPorCodigo(codigo);
persona.setEstado(EstadoEnum.INACTIVO.getDescripcion());
personaServicio.registrar(persona);
// Respuesta
ResponseGenerico<Persona> response = new ResponseGenerico<>();
response.setObjeto(persona);
response.setCodigoRespuesta(Constantes.CODIGO_RESPUESTA_OK);
response.setMensaje(Constantes.MENSAJE_OK_ELIMINADO);
return response;
}
@GetMapping(value = "listarPrefijoTelefonico")
public ResponseGenerico<PrefijoTelefonicoDTO> listarPrefijoTelefonico() {
List<PrefijoTelefonicoDTO> listaPrefijoTelefonico = personaServicio.listarPrefijoTelefonico();
// Respuesta
ResponseGenerico<PrefijoTelefonicoDTO> response = new ResponseGenerico<>();
response.setListado(listaPrefijoTelefonico);
response.setTotalRegistros((long) listaPrefijoTelefonico.size());
response.setCodigoRespuesta(Constantes.CODIGO_RESPUESTA_OK);
response.setMensaje(Constantes.MENSAJE_OK);
return response;
}
} |
/**
Given an integer array nums, move all 0's to the end of it while maintaining
the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.
Example 1:
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Example 2:
Input: nums = [0]
Output: [0]
Constraints:
1 <= nums.length <= 10⁴
-2³¹ <= nums[i] <= 2³¹ - 1
Follow up: Could you minimize the total number of operations done?
Related Topics 数组 双指针 👍 1845 👎 0
*/
package com.jianyitao.leetcode.editor.cn;
import java.util.ArrayList;
import java.util.List;
public class MoveZeroes{
public static void main(String[] args) {
Solution solution = new MoveZeroes().new Solution();
solution.moveZeroes(new int[] {0,1,0,3,12,3,5,0,7});
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public void moveZeroes(int[] nums) {
int j = 0;
for (int i = 0; i < nums.length; i++) {
if(nums[i] != 0){
nums[j++] = nums[i];
}
}
for (int k = j; k < nums.length; k++) {
nums[k] = 0;
}
System.out.println(nums);
}
}
//leetcode submit region end(Prohibit modification and deletion)
} |
import { Alert, Button, Label, TextInput } from "flowbite-react";
import { useState } from "react";
import { Link, useNavigate} from "react-router-dom";
import { Spinner } from "flowbite-react";
import OAuth from "../components/OAuth";
export default function Signup() {
const [formData, setFormData] = useState({})
const [errorMessage, setErrorMassage] = useState(null)
const [loading, setLoading] = useState(false)
const navigate = useNavigate()
const handleChange = (e) => {
setFormData({...formData, [e.target.id]:e.target.value.trim() });
}
const handleSubmit = async (e) => {
e.preventDefault()
if(!formData.username || !formData.email || !formData.password){
return setErrorMassage('Please fill out all the fields')
}
try{
setLoading(true)
setErrorMassage(null)
const res = await fetch('/api/auth/signup', {
method:'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData),
});
const data = await res.json()
if(data.success === false){
setErrorMassage(data.message)
}
setLoading(false)
if(res.ok){
navigate('/sign-in')
}
} catch(error){
setErrorMassage(error.message)
setLoading(false)
}
}
return (
<div className="min-h-screen mt-20">
<div className="flex p-3 max-w-3xl mx-auto flex-col md:flex-row md:items-center gap-5">
{/* left */}
<div className="flex-1">
<Link to='/' className="self-center whitespace-nowrap text-4xl font-bold">
<span className="px-2 py-1 bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500 rounded-lg text-white">Sahrelina's</span>
Blog
</Link>
<p className="text-sm mt-5">This is a demo project. You can sign up with your email and password or with google</p>
</div>
{/* right */}
<div className="flex-1">
<form className="flex flex-col gap-4" onSubmit={handleSubmit}>
<div>
<Label value="Your username" />
<TextInput
type="text"
placeholder="Your username"
id='username'
onChange={handleChange}/>
</div>
<div>
<Label value="Your email"/>
<TextInput
type="email"
placeholder="name@company.com"
id='email'
onChange={handleChange}/>
</div>
<div>
<Label value="Your password"/>
<TextInput
type="password"
placeholder="Your password"
id='password'
onChange={handleChange}/>
</div>
<Button gradientDuoTone='purpleToPink' type="submit" disabled={loading}>
{ loading ? (
<>
<Spinner size='sm'/>
<span className="pl-3">Loading...,</span>
</>
) : 'Sign Up'}
</Button>
<OAuth/>
</form>
<div className="flex gap-2 test-sm mt-5">
<span>Have an account?</span>
<Link to='/sign-in' className="text-blue-500">
Sign In</Link>
</div>
{errorMessage && (
<Alert className="mt-5" color='failure'>{errorMessage}</Alert>
)}
</div>
</div>
</div>
)
} |
import { FcGoogle } from 'react-icons/fc';
import { getAuth, GoogleAuthProvider, signInWithPopup } from 'firebase/auth';
import { toast } from 'react-toastify';
import { doc, serverTimestamp, setDoc, getDoc } from 'firebase/firestore';
import { db } from '../firebase';
import { useNavigate } from 'react-router';
const OAuth = () => {
const navigate = useNavigate();
async function onGoogleClick(){
try {
const auth = getAuth()
const provider = new GoogleAuthProvider()
const result = await signInWithPopup(auth, provider)
const user = result.user;
// check for the user
const docRef = doc(db, 'users', user.uid );
const docSnap = await getDoc(docRef);
if(!docSnap.exists()) {
await setDoc(docRef, {
name: user.displayName,
email: user.email,
timestamp: serverTimestamp(),
});
}
toast.success("Successful to connect.");
navigate("/");
} catch (error) {
toast.error("Could not authorize with Google")
}
}
return (
<button type='button'
onClick={onGoogleClick}
className='flex items-center
justify-center w-full bg-red-700
text-white px-7 py-3 uppercase
text-sm font-medium
hover:bg-red-800
active:bg-red-900
shadow-md hover:shadow-lg
active:shadow-lg
transition
duration-150
ease-in-out rounded'>
<FcGoogle className='text-2xl
bg-white rounded-full mr-2'
/>
Continue with Google
</button>
)
}
export default OAuth |
trainData = read.csv("cleaned-edited.csv",stringsAsFactors=FALSE, sep=",")
trainData = trainData[, c('Artist.Followers', 'Danceability', 'Energy', 'Loudness',
'Speechiness', 'Acousticness', 'Liveness', 'Tempo', 'Duration_ms',
'Valence', 'explicit', 'mode',
'instrumentalness', 'time_signature', 'Key', 'class')]
for (i in length(trainData))
{
if (trainData[i, "explicit"] == "TRUE")
{
trainData[i, "explicit"] = 1;
}
else
{
trainData[i, "explicit"] = 0;
}
}
head(trainData)
# Used from https://www.machinelearningplus.com/machine-learning/feature-selection/
library(Boruta)
# Perform Boruta search
boruta_output <- Boruta(class ~ ., data = na.omit(trainData), doTrace = 0)
# Do a tentative rough fix
roughFixMod <- TentativeRoughFix(boruta_output)
boruta_signif <- getSelectedAttributes(roughFixMod)
print(boruta_signif)
# Variable Importance Scores
imps <- attStats(roughFixMod)
imps2 = imps[imps$decision != 'Rejected', c('meanImp', 'decision')]
head(imps2[order(-imps2$meanImp), ])
# Plot variable importance
plot(boruta_output, cex.axis=.7, las=2, xlab="", main="Variable Importance") |
import {string, object, number, array} from "yup"
import { yupResolver } from "@hookform/resolvers/yup"
const schema = object().shape({
startDate: string().required('Start date is required'),
endDate: string().required('End date is required'),
routeLength: number(),
loadsNumber: number(),
shipId: number().required('Ship must be picked'),
srcPortId: number().required('Source port is required').typeError('Source port is required'),
dstPortId: number().required('Destination port is required').typeError('Destination port is required'),
workersIds: array().required('At least one worker must be on a cruise')
})
const resolver = yupResolver(schema)
export { resolver } |
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mysql = require('mysql2');
const bcrypt = require('bcrypt');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json())
const path = require('path');
// Configuração do mecanismo de visualização EJS
app.set('views', path.join(__dirname, 'frontend'));
app.set('view engine', 'ejs');
//conexão com o banco
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123456',
database: 'projeto'
});
//mensagem de conexão
db.connect(err => {
if (err) {
console.error('Erro na conexão com o banco de dados:', err);
return;
}
console.log('Conexão com o banco de dados estabelecida');
});
//ROTAS DE GET
// app.get("/", (req, res) => {
// res.sendFile(__dirname + "/frontend/LOGIN.html");;
// });
app.get("/", (req, res) => {
res.redirect("/LOGIN.html");
});
app.get("/login", (req, res) => {
res.sendFile(__dirname + "/frontend/LOGIN.html");
});
app.get("/caixa", (req, res) => {
res.sendFile(__dirname + "/frontend/statusCaixa.html");
});
app.get("/painel",(req, res) => {
res.sendFile(__dirname + "/frontend/painel.html");
});
app.get("/cadastrar",(req, res) => {
res.sendFile(__dirname + "/frontend/cadastros.html");
});
app.post("/login", async (req, res) => {
const username = req.body.usernameInput;
const password = req.body.passwordInput;
async function validateUser(username, password) {
const sql = 'SELECT * FROM usuarios WHERE username = ?';
return new Promise((resolve, reject) => {
db.query(sql, [username], async (err, results) => {
if (err) {
reject(err);
} else {
if (results.length > 0) {
const user = results[0];
console.log('Senha informada:', password);
console.log('Senha armazenada no banco de dados:', user.password);
// Comparação direta das senhas
const passwordMatch = password === user.password;
console.log('Comparação de senha:', passwordMatch);
resolve(passwordMatch ? user : null);
} else {
resolve(null);
}
}
});
});
}
try {
const user = await validateUser(username, password);
if (user) {
res.redirect('/painel.html');
} else {
res.status(401).send('Nome de usuário ou senha incorretos.');
}
} catch (error) {
console.error('Erro ao validar usuário:', error);
res.status(500).send('Erro ao processar a solicitação.');
}
});
app.get("/listar-clientes", (req, res) => {
const sql = 'SELECT * FROM clientes';
db.query(sql, (err, results) => {
if (err) {
console.error('Erro ao recuperar dados:', err);
res.send('Erro ao recuperar dados do banco de dados');
} else {
console.log('Recuperação dos dados completa:');
res.render('telaPrincipal', { clientes: results });
}
});
});
app.get("/listar-atendentes", (req, res) => {
const sql = 'SELECT * FROM Atendente';
db.query(sql, (err, results) => {
if (err) {
console.error('Erro ao recuperar dados:', err);
res.send('Erro ao recuperar dados do banco de dados');
} else {
console.log('Recuperação dos dados completa:');
res.render('atendentes', { Atendente: results });
}
});
});
app.get("/listar-motoboy", (req, res) => {
const sql = 'SELECT * FROM Motoboy';
db.query(sql, (err, results) => {
if (err) {
console.error('Erro ao recuperar dados:', err);
res.send('Erro ao recuperar dados do banco de dados');
} else {
console.log('Recuperação dos dados completa:');
res.render('motoboys', { Motoboy: results });
}
});
});
app.get("/listar-produtos", (req, res) => {
const sql = 'SELECT * FROM produto';
db.query(sql, (err, results) => {
if (err) {
console.error('Erro ao recuperar dados:', err);
res.send('Erro ao recuperar dados do banco de dados');
} else {
console.log('Recuperação dos dados completa:');
res.render('produtos', { produto: results });
}
});
});
app.get("/listar-membros", (req, res) => {
const sql = 'SELECT * FROM Membro';
db.query(sql, (err, results) => {
if (err) {
console.error('Erro ao recuperar dados:', err);
res.send('Erro ao recuperar dados do banco de dados');
} else {
console.log('Recuperação dos dados completa:');
res.render('membros', { Membro: results });
}
});
});
app.get("/listar-categorias", (req, res) => {
const sql = 'SELECT * FROM categoria';
db.query(sql, (err, results) => {
if (err) {
console.error('Erro ao recuperar dados:', err);
res.send('Erro ao recuperar dados do banco de dados');
} else {
console.log('Recuperação dos dados completa:');
res.render('categorias', { categoria: results });
}
});
});
app.get("/listar-pagamentos", (req, res) => {
const sql = 'SELECT * FROM pagamento';
db.query(sql, (err, results) => {
if (err) {
console.error('Erro ao recuperar dados:', err);
res.send('Erro ao recuperar dados do banco de dados');
} else {
console.log('Recuperação dos dados completa:');
res.render('pagamentos', { pagamento: results });
}
});
});
app.get("/listar-pedidos", (req, res) => {
const sql = `select PD.ID,
PD.Data,
CL.Nome Cliente,
ATD.Nome Atendente,
PG.Nome FormaPagamento,
PD.valor_total,
PD.status_pedido
from pedido PD
left join clientes CL
on PD.CLIENTE_ID = CL.ID
left join atendente ATD
on PD.Atendente_ID = ATD.ID
left join pagamento PG
on PD.pagamento_ID = PG.ID;`;
db.query(sql, (err, results) => {
if (err) {
console.error('Erro ao recuperar dados:', err);
res.send('Erro ao recuperar dados do banco de dados');
} else {
console.log('Recuperação dos dados completa:');
res.render('telaPedidos', { pedidos: results });
}
});
});
app.get("/api/listar-categorias", (req, res) => {
const sql = 'SELECT * FROM categoria';
db.query(sql, (err, results) => {
if (err) {
return res.send(err)
}
return res.send({ categorias: results })
});
});
app.get("/api/listar-atendentes", (req, res) => {
const sql = 'SELECT * FROM Atendente';
db.query(sql, (err, results) => {
if (err) {
return res.send(err)
}
return res.send({ Atendentes: results })
});
});
app.get("/api/listar-clientes", (req, res) => {
const sql = 'SELECT * FROM clientes';
db.query(sql, (err, results) => {
if (err) {
return res.send(err)
}
return res.send({ clientes: results })
});
});
app.get("/api/listar-pagamentos", (req, res) => {
const sql = 'SELECT * FROM pagamento';
db.query(sql, (err, results) => {
if (err) {
return res.send(err)
}
return res.send({ pagamento: results })
});
});
app.get("/api/listar-produtos", (req, res) => {
const sql = 'SELECT * FROM produto';
db.query(sql, (err, results) => {
if (err) {
return res.send(err)
}
return res.send({ produtos: results })
});
});
app.post("/api/salvar-pedido", async (req, res) => {
let insertedPedidoId = 0;
let valorTotalPedido = 0;
const { atendenteId, clienteId, itemsPedido, formaPagamentoId, valor_total } = req.body;
const insertPedido = `INSERT INTO PEDIDO
(Data, Atendente_ID, CLIENTE_ID, pagamento_ID, valor_total, status_pedido)
VALUES
(NOW(), ?, ?, ?, ?, ?)`;
const promiseInsertPedido = new Promise((resolve, reject) => {
db.query(insertPedido, [atendenteId, clienteId, formaPagamentoId, 0.00, "Aberto"], (err, results) => {
if (err) {
reject(err);
} else {
insertedPedidoId = results.insertId;
resolve();
}
});
});
const promiseInsertProdutosPedido = new Promise((resolve, reject) => {
const promises = itemsPedido.map((produtoPedido) => {
const selectValorProduto = 'SELECT valor FROM produto WHERE id = ' + produtoPedido.id;
return new Promise((resolve, reject) => {
db.query(selectValorProduto, (err, results) => {
if (err) {
reject(err);
} else {
const firstResult = results && results.length > 0 ? results[0] : null;
const valor = firstResult ? firstResult.valor : 0;
resolve(valor);
}
});
});
});
Promise.all(promises)
.then((valoresProdutos) => {
const promiseInsertProdutos = valoresProdutos.map((valorProduto, index) => {
const produtoPedido = itemsPedido[index];
const valorTotalProduto = isNaN(valorProduto) ? 0 : valorProduto * produtoPedido.quantidade;
valorTotalPedido += valorTotalProduto;
const insertProdutosPedido = `INSERT INTO PRODUTOS_PEDIDO
(QUANTIDADE, PEDIDO_ID, PRODUTO_ID, VALOR_TOTAL)
VALUES
(?, ?, ?, ?)`;
return new Promise((resolve, reject) => {
db.query(insertProdutosPedido, [produtoPedido.quantidade, insertedPedidoId, produtoPedido.id, valorTotalProduto], (err, result) => {
if (err) {
reject(err);
} else {
console.log('Dados inseridos com sucesso', result);
resolve();
}
});
});
});
return Promise.all(promiseInsertProdutos);
})
.then(() => {
const sql = 'UPDATE pedido SET valor_total = ? WHERE ID = ?;';
db.query(sql, [ valorTotalPedido, insertedPedidoId], (err, result) => {
if (err) {
console.error('Erro ao inserir dados:', err);
} else {
console.log('Dados inseridos com sucesso');
}
});
resolve();
})
.catch((err) => {
reject(err);
});
});
Promise.all([promiseInsertPedido, promiseInsertProdutosPedido])
.then(() => {
console.log("insertedPedidoId", insertedPedidoId);
res.json({
idPedido: insertedPedidoId,
valorTotalPedido
})
})
.catch((err) => {
console.error('Error:', err);
});
});
//-------------------------------------------------------------------
app.use(express.static('frontend'))
//ROTAS POST
app.post("/excluir-cliente", (req, res) => {
const clienteId = req.body.clienteId;
const sql = 'DELETE FROM clientes WHERE id = ?';
db.query(sql, [clienteId], (err, result) => {
if (err) {
console.error('Erro ao excluir cliente:', err);
res.status(500).send('Erro ao excluir cliente do banco de dados');
} else {;
console.log('Cliente excluído com sucesso');
res.status(200).send(`Cliente ${clienteId} excluído com sucesso `);
}
});
});
app.post("/excluir-atendente", (req, res) => {
const atendenteId = req.body.atendenteId;
const sql = 'DELETE FROM Atendente WHERE id = ?';
db.query(sql, [atendenteId], (err, result) => {
if (err) {
console.error('Erro ao excluir atendente:', err);
res.status(500).send('Erro ao excluir atendente do banco de dados');
} else {;
console.log('Atendente excluído com sucesso');
res.status(200).send(`Atendente ${atendenteId} excluído com sucesso `);
}
});
});
app.post("/excluir-motoboy", (req, res) => {
const motoboyId = req.body.motoboyId;
const sql = 'DELETE FROM Motoboy WHERE id = ?';
db.query(sql, [motoboyId], (err, result) => {
if (err) {
console.error('Erro ao excluir motoboy:', err);
res.status(500).send('Erro ao excluir motoboy do banco de dados');
} else {;
console.log('Motoboy excluído com sucesso');
res.status(200).send(`Motoboy ${motoboyId} excluído com sucesso `);
}
});
});
app.post("/excluir-produto", (req, res) => {
const produtoId = req.body.produtoId;
// Primeiro, exclua as entradas relacionadas em produtos_pedido
const deleteProdutosPedido = 'DELETE FROM produtos_pedido WHERE PRODUTO_ID = ?';
db.query(deleteProdutosPedido, [produtoId], (err, result) => {
if (err) {
console.error('Erro ao excluir produtos_pedido:', err);
res.status(500).send('Erro ao excluir produtos_pedido do banco de dados');
} else {
// Agora, exclua o produto da tabela produto
const deleteProduto = 'DELETE FROM produto WHERE id = ?';
db.query(deleteProduto, [produtoId], (err, result) => {
if (err) {
console.error('Erro ao excluir Produto:', err);
res.status(500).send('Erro ao excluir Produto do banco de dados');
} else {
console.log('Produto excluído com sucesso');
res.status(200).send(`Produto ${produtoId} excluído com sucesso `);
}
});
}
});
});
app.post("/excluir-membro", (req, res) => {
const membroId = req.body.membroId;
const sql = 'DELETE FROM Membro WHERE id = ?';
db.query(sql, [membroId], (err, result) => {
if (err) {
console.error('Erro ao excluir membro:', err);
res.status(500).send('Erro ao excluir membro do banco de dados');
} else {;
console.log('Membro excluído com sucesso');
res.status(200).send(`Membro ${membroId} excluído com sucesso `);
}
});
});
app.post("/excluir-categoria", (req, res) => {
const categoriaId = req.body.categoriaId;
const sql = 'DELETE FROM categoria WHERE id = ?';
db.query(sql, [categoriaId], (err, result) => {
if (err) {
console.error('Erro ao excluir categoria:', err);
res.status(500).send('Erro ao excluir categoria do banco de dados');
} else {;
console.log('Categoria excluído com sucesso');
res.status(200).send(`Categoria ${categoriaId} excluído com sucesso `);
}
});
});
app.post("/excluir-pagamento", (req, res) => {
const pagamentoId = req.body.pagamentoId;
const sql = 'DELETE FROM pagamento WHERE id = ?';
db.query(sql, [pagamentoId], (err, result) => {
if (err) {
console.error('Erro ao excluir pagamento:', err);
res.status(500).send('Erro ao excluir pagamento do banco de dados');
} else {;
console.log('Pagamento excluído com sucesso');
res.status(200).send(`Pagamento ${pagamentoId} excluído com sucesso `);
}
});
});
app.post("/processar-cadastro-cliente", (req, res) => {
const { nomeCliente, emailCliente, cpfCliente, telefoneCliente,
logradouroCliente, cidadeCliente, complementoCliente, numeroCliente,
estadoCliente, cepCliente } = req.body;
const sql = 'INSERT INTO clientes (nome, email, cpf, telefone, logradouro, cidade, complemento, numero, estado, cep) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
db.query(sql, [ nomeCliente, emailCliente, cpfCliente, telefoneCliente, logradouroCliente, cidadeCliente, complementoCliente, numeroCliente,
estadoCliente, cepCliente], (err, result) => {
if (err) {
console.error('Erro ao inserir dados:', err);
res.send('Erro ao cadastrar dados no banco de dados');
} else {
console.log('Dados inseridos com sucesso');
res.sendFile(__dirname + "/frontend/cadastros.html");
}
});
});
app.post("/editar-cadastro-cliente", (req, res) => {
const clienteId = req.body.clienteId;
const { nomeClienteEditado, emailClienteEditado, cpfClienteEditado, telefoneClienteEditado,
logradouroClienteEditado, cidadeClienteEditado, complementoClienteEditado, numeroClienteEditado,
estadoClienteEditado, cepClienteEditado } = req.body;
const sql = 'UPDATE INTO clientes (nome, email, cpf, telefone, logradouro, cidade, complemento, numero, estado, cep) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) WHERE id = ?';
db.query(sql, [ nomeClienteEditado, emailClienteEditado, cpfClienteEditado, telefoneClienteEditado, logradouroClienteEditado, cidadeClienteEditado, complementoClienteEditado, numeroClienteEditado,
estadoClienteEditado, cepClienteEditado], (err, result) => {
if (err) {
console.error('Erro ao inserir dados:', err);
res.send('Erro ao cadastrar dados no banco de dados');
} else {
console.log('Dados inseridos com sucesso');
res.sendFile(__dirname + "/frontend/cadastros.html");
}
});
});
app.post("/processar-cadastro-atendente", (req, res) => {
const { nomeAtendente, emailAtendente, obsAtendente} = req.body;
const sql = 'INSERT INTO Atendente (Nome, Email, Observacoes) VALUES (?, ?, ?)';
db.query(sql, [ nomeAtendente, emailAtendente, obsAtendente], (err, result) => {
if(err){
console.error('Erro ao inserir dados:', err);
res.send('Erro ao cadastrar dados no banco de dados');
}else{
console.log('Dados inseridos com sucesso');
res.sendFile(__dirname + "/frontend/cadastros.html");
}
});
});
app.post("/processar-cadastro-motoboy", (req, res) => {
const { nomeMotoboy, emailMotoboy, obsMotoboy} = req.body;
const sql = 'INSERT INTO Motoboy (Nome, Email, Observacoes) VALUES (?, ?, ?)';
db.query(sql, [ nomeMotoboy, emailMotoboy, obsMotoboy], (err, result) => {
if(err){
console.error('Erro ao inserir dados:', err);
res.send('Erro ao cadastrar dados no banco de dados');
}else{
console.log('Dados inseridos com sucesso');
res.sendFile(__dirname + "/frontend/cadastros.html");
}
});
});
app.post("/processar-cadastro-categoria", (req, res) => {
const { nomeCategoria, obsCategoria} = req.body;
const sql = 'INSERT INTO Categoria (Nome, Observacoes) VALUES (?, ?)';
db.query(sql, [ nomeCategoria, obsCategoria], (err, result) => {
if(err){
console.error('Erro ao inserir dados:', err);
res.send('Erro ao cadastrar dados no banco de dados');
}else{
console.log('Dados inseridos com sucesso');
res.sendFile(__dirname + "/frontend/cadastros.html");
}
});
});
app.post("/processar-cadastro-pagamento", (req, res) => {
const { nomePagamento, obsPagamento} = req.body;
const sql = 'INSERT INTO Pagamento (Nome, Observacoes) VALUES (?, ?)';
db.query(sql, [ nomePagamento, obsPagamento], (err, result) => {
if(err){
console.error('Erro ao inserir dados:', err);
res.send('Erro ao cadastrar dados no banco de dados');
}else{
console.log('Dados inseridos com sucesso');
res.sendFile(__dirname + "/frontend/cadastros.html");
}
});
});
app.post("/processar-cadastro-produto", (req, res) => {
const { nomeProduto, valorProduto, descricaoProduto, estoqueProduto, categoriaProduto, fornecedorProduto} = req.body;
const sql = 'INSERT INTO produto (nome, valor, descricao, estoque, categoria, fornecedor) VALUES (?, ?, ?, ?, ?, ?)';
db.query(sql, [ nomeProduto, valorProduto, descricaoProduto, estoqueProduto, categoriaProduto, fornecedorProduto], (err, result) => {
if(err){
console.error('Erro ao inserir dados:', err);
res.send('Erro ao cadastrar dados no banco de dados');
}else{
console.log('Dados inseridos com sucesso');
res.sendFile(__dirname + "/frontend/cadastros.html");
}
});
});
app.post("/processar-cadastro-membro", (req, res) => {
const { nomeMembro, emailMembro, obsMembro} = req.body;
const sql = 'INSERT INTO Membro (Nome, Email, Observacoes) VALUES (?, ?, ?)';
db.query(sql, [ nomeMembro, emailMembro, obsMembro], (err, result) => {
if(err){
console.error('Erro ao inserir dados:', err);
res.send('Erro ao cadastrar dados no banco de dados');
}else{
console.log('Dados inseridos com sucesso');
res.sendFile(__dirname + "/frontend/cadastros.html");
}
});
});
//MENSAGEM STATUS CONEXÃO
app.listen(8080, () => {
console.log("Servidor Iniciado na porta 8080: http://localhost:8080");
});
// ------------------------------------------------------------------ |
# Type parameters
## Type parameters for intrinsic types
We have seen type parameters (kind type parameters) for intrinsic types:
```
use iso_fortran_env
...
integer (int32) :: i32
```
This provides a way to control, parametrically, the actual data type
associated with the variable. Such parameters must be known at compile
time.
There are all so-called deferred parameters, such as the length of a
deferred length string
```
character (len = :), allocatable :: string
```
The colon indicates the length is deferred.
## Parameterised derived types
These features may be combined in a parameterised type definition, e.g.:
```
type, public :: my_array_t(kr, nlen)
integer, kind :: kr ! kind parameter
integer, nlen :: nlen ! len parameter
real (kr) :: data(nlen)
end type my_array_t
```
The type parameters must be integers and take one of two roles: a `kind`
parameter, which is used in the place of kind type parameters, and a
`len` parameter, which can be used in array bound declaration or a length
specificaition. A `kind` parameter must be a compile-time constant, but a
length parameter may be deferred until run time.
The extra components act as normal components in that they may have a
default value specified in the declaration, and may be accessed at run
time via the component selector `%` in the usual way.
For example declaration of a variable of such a type might look like:
```
! ... establish len_input ...
type (my_array_t(real32, len_input)) :: a
```
Such a parameterised type may have a dummy argument associated with an
actual argument via a dummy argument declaration, e.g.,
```
type (my_array_t(real32, nlen = *)), intent(in) :: a
```
cf.
```
character (len = *), intent(in) :: str
```
A pointer declaration of this type would use the deferred notation
with the colon:
```
type (my_array_t(real32, nlen = :)), pointer p => null()
```
Here, an (optional) keyword has been used in the parameter list. |
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "LmbrCentral_precompiled.h"
#include "LmbrCentralReflectionTest.h"
#include "Shape/EditorCylinderShapeComponent.h"
namespace LmbrCentral
{
// Serialized legacy EditorCylinderShapeComponent v1.
const char kEditorCylinderComponentVersion1[] =
R"DELIMITER(<ObjectStream version="1">
<Class name="EditorCylinderShapeComponent" field="element" version="1" type="{D5FC4745-3C75-47D9-8C10-9F89502487DE}">
<Class name="EditorComponentBase" field="BaseClass1" version="1" type="{D5346BD4-7F20-444E-B370-327ACD03D4A0}">
<Class name="AZ::Component" field="BaseClass1" type="{EDFCB2CF-F75D-43BE-B26B-F35821B29247}">
<Class name="AZ::u64" field="Id" value="2283148451428660584" type="{D6597933-47CD-4FC8-B911-63F3E2B0993A}"/>
</Class>
</Class>
<Class name="CylinderShapeConfig" field="Configuration" version="1" type="{53254779-82F1-441E-9116-81E1FACFECF4}">
<Class name="float" field="Height" value="1.5700000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
<Class name="float" field="Radius" value="0.5700000" type="{EA2C3E90-AFBE-44D4-A90D-FAAF79BAF93D}"/>
</Class>
</Class>
</ObjectStream>)DELIMITER";
class LoadEditorCylinderShapeComponentFromVersion1
: public LoadEditorComponentTest<EditorCylinderShapeComponent>
{
protected:
const char* GetSourceDataBuffer() const override { return kEditorCylinderComponentVersion1; }
};
TEST_F(LoadEditorCylinderShapeComponentFromVersion1, Application_IsRunning)
{
ASSERT_NE(GetApplication(), nullptr);
}
TEST_F(LoadEditorCylinderShapeComponentFromVersion1, Components_Load)
{
EXPECT_NE(m_object.get(), nullptr);
}
TEST_F(LoadEditorCylinderShapeComponentFromVersion1, EditorComponent_Found)
{
EXPECT_EQ(m_entity->GetComponents().size(), 2);
EXPECT_NE(m_entity->FindComponent(m_object->GetId()), nullptr);
}
TEST_F(LoadEditorCylinderShapeComponentFromVersion1, Height_MatchesSourceData)
{
float height = 0.0f;
CylinderShapeComponentRequestsBus::EventResult(
height, m_entity->GetId(), &CylinderShapeComponentRequests::GetHeight);
EXPECT_FLOAT_EQ(height, 1.57f);
}
TEST_F(LoadEditorCylinderShapeComponentFromVersion1, Radius_MatchesSourceData)
{
float radius = 0.0f;
CylinderShapeComponentRequestsBus::EventResult(
radius, m_entity->GetId(), &CylinderShapeComponentRequests::GetRadius);
EXPECT_FLOAT_EQ(radius, 0.57f);
}
} |
<%--
Document : index
Created on : Feb 8, 2023, 4:37:29 PM
Author : ADMIN
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- Tell the browser to be responsive to screen width -->
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="robots" content="noindex,nofollow" />
<title>Home</title>
<link rel="icon" type="image/png" sizes="16x16" href="assets/images/logo.png" />
<link href="assets/libs/flot/css/float-chart.css" rel="stylesheet" />
<link href="dist/css/style.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/apexcharts@3.25.0/dist/apexcharts.min.js"></script>
</head>
<body onload="drawChart()">
<fmt:setLocale value = "vi_VN"/>
<%
response.setHeader("Cache-Control", "no-cache"); //HTTP 1.1
response.setHeader("Pragma", "no-cache"); //HTTP 1.0
response.setDateHeader("Expires", 0);
%>
<div class="preloader">
<div class="lds-ripple">
<div class="lds-pos"></div>
<div class="lds-pos"></div>
</div>
</div>
<div id="main-wrapper" data-layout="vertical" data-navbarbg="skin5" data-sidebartype="full"
data-sidebar-position="absolute" data-header-position="absolute" data-boxed-layout="full">
<header class="topbar" data-navbarbg="skin5">
<nav class="navbar top-navbar navbar-expand-md navbar-dark">
<div class="navbar-header" data-logobg="skin5">
<a class="navbar-brand" href="${pageContext.request.contextPath}/admin/index">
<b class="logo-icon" style="margin: 0px;">
<img src="assets/images/logo.png" alt="homepage" class="light-logo" width="50" />
</b>
<span class="logo-text " style="margin-right: 15px">
<img src="${pageContext.request.contextPath}/images/logo_text.png" alt="homepage" class="light-logo" width="140" height="50" />
</span>
</a>
<a class="nav-toggler waves-effect waves-light d-block d-md-none" href="javascript:void(0)"><i
class="ti-menu ti-close"></i></a>
</div>
<div class="navbar-collapse collapse" id="navbarSupportedContent" data-navbarbg="skin5">
<ul class="navbar-nav float-start me-auto">
<li class="nav-item d-none d-lg-block">
<a class="nav-link sidebartoggler waves-effect waves-light" href="javascript:void(0)"
data-sidebartype="mini-sidebar"><i class="mdi mdi-menu font-24"></i></a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown"
aria-expanded="false">
<span class="d-none d-md-block">Thêm mới <i class="fa fa-angle-down"></i></span>
<span class="d-block d-md-none"><i class="fa fa-plus"></i></span>
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="${pageContext.request.contextPath}/admin/addsupplier">Thương hiệu</a></li>
<li><a class="dropdown-item" href="${pageContext.request.contextPath}/admin/addcategory">Danh mục</a></li>
<li>
<hr class="dropdown-divider" />
</li>
<li>
<a class="dropdown-item" href="${pageContext.request.contextPath}/admin/addproduct">Sản phẩm</a>
</li>
</ul>
</li>
<li class="nav-item search-box">
<a class="nav-link waves-effect waves-dark" href="javascript:void(0)"><i
class="mdi mdi-magnify fs-4"></i></a>
<form class="app-search position-absolute">
<input type="text" class="form-control" placeholder="Search & enter" />
<a class="srh-btn"><i class="mdi mdi-window-close"></i></a>
</form>
</li>
</ul>
<ul class="navbar-nav float-end">
<li class="nav-item dropdown">
<a class="
nav-link
dropdown-toggle
text-muted
waves-effect waves-dark
pro-pic
" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
<img src="data:image/jpg;base64,${sessionScope.admin.base64Image}" alt="user" class="rounded-circle" width="31" />
</a>
<ul class="dropdown-menu dropdown-menu-end user-dd animated" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="${pageContext.request.contextPath}/admin/profileadmin"><i class="mdi mdi-account me-1 ms-1"></i> Hồ sơ của
tôi</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="${pageContext.request.contextPath}/admin/changepass.jsp"><i class="mdi mdi-settings me-1 ms-1"></i> Đổi mật
khẩu</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="${pageContext.request.contextPath}/admin/logoutadmin"><i class="fa fa-power-off me-1 ms-1"></i> Đăng
xuất</a>
<div class="dropdown-divider"></div>
<div class="ps-4 p-10">
<a href="${pageContext.request.contextPath}/admin/profileadmin" class="btn btn-sm btn-success btn-rounded text-white">View Profile</a>
</div>
</ul>
</li>
</ul>
</div>
</nav>
</header>
<aside class="left-sidebar" data-sidebarbg="skin5">
<div class="scroll-sidebar">
<nav class="sidebar-nav">
<ul id="sidebarnav" class="pt-4">
<li class="sidebar-item">
<a
class="sidebar-link waves-effect waves-dark sidebar-link"
href="${pageContext.request.contextPath}/admin/index"
aria-expanded="false"
><i class="mdi mdi-view-dashboard"></i
><span class="hide-menu">Trang chủ</span></a
>
</li>
<li class="sidebar-item">
<a
class="sidebar-link waves-effect waves-dark sidebar-link"
href="${pageContext.request.contextPath}/admin/charts"
aria-expanded="false"
><i class="mdi mdi-chart-bar"></i
><span class="hide-menu">Thống kê</span></a
>
</li>
<li class="sidebar-item">
<a
class="sidebar-link waves-effect waves-dark sidebar-link"
href="${pageContext.request.contextPath}/admin/feedbacks"
aria-expanded="false"
><i class="mdi mdi-help-circle"></i
><span class="hide-menu">Feedbacks</span></a
>
</li>
<li class="sidebar-item">
<a
class="sidebar-link waves-effect waves-dark sidebar-link"
href="${pageContext.request.contextPath}/admin/orders"
aria-expanded="false"
><i class="mdi mdi-tag"></i
><span class="hide-menu">Orders</span></a
>
</li>
<li class="sidebar-item">
<a
class="sidebar-link waves-effect waves-dark sidebar-link"
href="${pageContext.request.contextPath}/admin/comments"
aria-expanded="false"
><i class="mdi mdi-comment-processing"></i
><span class="hide-menu">Reviews</span></a
>
</li>
<li class="sidebar-item">
<a
class="sidebar-link has-arrow waves-effect waves-dark"
href="javascript:void(0)"
aria-expanded="false"
><i class="mdi mdi-format-list-bulleted"></i
><span class="hide-menu">Danh sách </span></a
>
<ul aria-expanded="false" class="collapse first-level">
<li class="sidebar-item">
<a href="${pageContext.request.contextPath}/admin/tables" class="sidebar-link"
><i class="mdi mdi-table"></i
><span class="hide-menu"> Tất cả </span></a
>
</li>
<li class="sidebar-item">
<a href="${pageContext.request.contextPath}/admin/listallaccounts" class="sidebar-link"
><i class="mdi mdi-account"></i
><span class="hide-menu"> Người dùng </span></a
>
</li>
<li class="sidebar-item">
<a href="${pageContext.request.contextPath}/admin/listallproducts" class="sidebar-link"
><i class="fab fa-product-hunt"></i
><span class="hide-menu"> Sản phẩm </span></a
>
</li>
<li class="sidebar-item">
<a href="${pageContext.request.contextPath}/admin/listallcategories" class="sidebar-link"
><i class="mdi mdi-group"></i
><span class="hide-menu"> Danh mục </span></a
>
</li>
<li class="sidebar-item">
<a href="${pageContext.request.contextPath}/admin/listallshippers" class="sidebar-link"
><i class="mdi mdi-truck"></i
><span class="hide-menu"> Đơn vị vận chuyển </span></a
>
</li>
<li class="sidebar-item">
<a href="${pageContext.request.contextPath}/admin/listallsuppliers" class="sidebar-link"
><i class="mdi mdi-human-greeting"></i
><span class="hide-menu"> Thương hiệu </span></a
>
</li>
</ul>
</li>
<li class="sidebar-item">
<a
class="sidebar-link has-arrow waves-effect waves-dark"
href="javascript:void(0)"
aria-expanded="false"
><i class="mdi mdi-playlist-plus"></i
><span class="hide-menu">Thêm mới </span></a
>
<ul aria-expanded="false" class="collapse first-level">
<li class="sidebar-item">
<a href="${pageContext.request.contextPath}/admin/addproduct" class="sidebar-link"
><i class="fab fa-product-hunt"></i
><span class="hide-menu"> Sản phẩm </span></a
>
</li>
<li class="sidebar-item">
<a href="${pageContext.request.contextPath}/admin/addcategory" class="sidebar-link"
><i class="mdi mdi-group"></i
><span class="hide-menu"> Danh mục </span></a
>
</li>
<li class="sidebar-item">
<a href="${pageContext.request.contextPath}/admin/addshipper" class="sidebar-link"
><i class="mdi mdi-truck"></i
><span class="hide-menu"> Đơn vị vận chuyển </span></a
>
</li>
<li class="sidebar-item">
<a href="${pageContext.request.contextPath}/admin/addsupplier" class="sidebar-link"
><i class="mdi mdi-human-greeting"></i
><span class="hide-menu"> Thương hiệu </span></a
>
</li>
</ul>
</li>
<li class="sidebar-item">
<a
class="sidebar-link has-arrow waves-effect waves-dark"
href="javascript:void(0)"
aria-expanded="false"
><i class="mdi mdi-account-key"></i
><span class="hide-menu">Xác thực</span></a
>
<ul aria-expanded="false" class="collapse first-level">
<li class="sidebar-item">
<a href="changepass.jsp" class="sidebar-link"
><i class="mdi mdi-key-change"></i
><span class="hide-menu"> Đổi mật khẩu </span></a
>
</li>
<li class="sidebar-item">
<a href="${pageContext.request.contextPath}/admin/profileadmin" class="sidebar-link"
><i class="mdi mdi-account-card-details"></i
><span class="hide-menu"> Hồ sơ </span></a
>
</li>
</ul>
</li>
</ul>
</nav>
</div>
</aside>
<div class="page-wrapper">
<div class="page-breadcrumb">
<div class="row">
<div class="col-12 d-flex no-block align-items-center">
<h4 class="page-title">Dashboard</h4>
<div class="ms-auto text-end">
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="#">Trang chủ</a></li>
</ol>
</nav>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-body">
<div class="d-md-flex align-items-center">
<div>
<h4 class="card-title">Site Analysis</h4>
<form action="${pageContext.request.contextPath}/admin/index" method="get">
<select name="year" onchange="this.form.submit()">
<optgroup label="Year">
<option value="2023" <c:if test="${requestScope.year == 2023}">selected</c:if>>2023</option>
<option value="2022" <c:if test="${requestScope.year == 2022}">selected</c:if>>2022</option>
</select>
</form>
</div>
</div>
<div class="row">
<!-- column -->
<div class="col-lg-9">
<div class="flot-chart">
<div id="chart"></div>
</div>
</div>
<div class="col-lg-3">
<div class="row">
<div class="col-6">
<div class="bg-dark p-10 text-white text-center">
<i class="mdi mdi-account fs-3 mb-1 font-16"></i>
<h5 class="mb-0 mt-1">${requestScope.totalCustomers}</h5>
<small class="font-light">Total Users</small>
</div>
</div>
<div class="col-6">
<div class="bg-dark p-10 text-white text-center">
<i class="mdi mdi-cash fs-3 font-16"></i>
<h5 class="mb-0 mt-1"><fmt:formatNumber value = "${Math.round((requestScope.totalMoney)/1000)*1000}" type = "currency"/></h5>
<small class="font-light">Total Money</small>
</div>
</div>
<div class="col-6 mt-3">
<div class="bg-dark p-10 text-white text-center">
<i class="mdi mdi-human-greeting fs-3 mb-1 font-16"></i>
<h5 class="mb-0 mt-1">${requestScope.totalSuppliers}</h5>
<small class="font-light">Total Suppliers</small>
</div>
</div>
<div class="col-6 mt-3">
<div class="bg-dark p-10 text-white text-center">
<i class="mdi mdi-tag-multiple fs-3 mb-1 font-16"></i>
<h5 class="mb-0 mt-1">${requestScope.totalOrders}</h5>
<small class="font-light">Total Orders</small>
</div>
</div>
<div class="col-6 mt-3">
<div class="bg-dark p-10 text-white text-center">
<i class="mdi fa-product-hunt fs-3 mb-1 font-16"></i>
<h5 class="mb-0 mt-1">${requestScope.totalProducts}</h5>
<small class="font-light">Total Products</small>
</div>
</div>
<div class="col-6 mt-3">
<div class="bg-dark p-10 text-white text-center">
<i class="mdi mdi-truck fs-3 mb-1 font-16"></i>
<h5 class="mb-0 mt-1">${requestScope.totalShippers}</h5>
<small class="font-light">Total Shippers</small>
</div>
</div>
<div class="col-6 mt-3">
<div class="bg-dark p-10 text-white text-center">
<i class="mdi mdi-cart fs-3 mb-1 font-16"></i>
<h5 class="mb-0 mt-1">${requestScope.totalOrderDetails}</h5>
<small class="font-light">Total Products Sale</small>
</div>
</div>
<div class="col-6 mt-3">
<div class="bg-dark p-10 text-white text-center">
<i class="mdi mdi-help-circle fs-3 mb-1 font-16"></i>
<h5 class="mb-0 mt-1">${requestScope.totalFeedback}</h5>
<small class="font-light">Total Feedback</small>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<!-- column -->
<div class="col-lg-12">
<div class="card">
<div class="card-body">
<h4 class="card-title mb-0"><a href="${pageContext.request.contextPath}/admin/orders">Đơn hàng chưa xử lý(${requestScope.totalOrdersProcess})</a></h4>
</div>
<div class="comment-widgets scrollable">
<!-- Comment Row -->
<c:forEach items="${requestScope.getNewOrders}" var="orderNew" begin="0" end="4">
<div class="d-flex flex-row comment-row mt-0">
<div class="p-2">
<img
src="data:image/jpg;base64,${orderNew.cus.base64Image}"
alt="user"
width="50"
height="50"
class="rounded-circle"
/>
</div>
<div class="comment-text w-100">
<a href="${pageContext.request.contextPath}/admin/profile?type=customer&id=${orderNew.cus.customerID}">${orderNew.cus.customerName}</a>
<span class="mb-3 d-block">
<a href="${pageContext.request.contextPath}/admin/orderdetail?id=${orderNew.cus.customerID}&oid=${orderNew.orderID}">OrderID: ${orderNew.orderID}</a><br>
OrderDate: ${orderNew.orderDate}<br>
RequiredDate: ${orderNew.requireDate}<br>
Total Products: ${orderNew.orderDetails.size()}<br>
TotalMoney: <fmt:formatNumber value = "${Math.round((orderNew.totalMoney)/1000)*1000}" type = "currency"/><br>
</span>
<div class="comment-footer">
<span class="text-muted float-end">${orderNew.orderDate}</span>
<button
type="button"
class="btn btn-cyan btn-sm text-white"
>
<a class="text-white" href="${pageContext.request.contextPath}/admin/orderdetail?id=${orderNew.cus.customerID}&oid=${orderNew.orderID}">
Information
</a>
</button>
<button
type="button"
onclick="updateOrder(${orderNew.orderID}, 'accept')"
class="btn btn-success btn-sm text-white"
>
Accept
</button>
<button
type="button"
onclick="updateOrder(${orderNew.orderID}, 'reject')"
class="btn btn-danger btn-sm text-white"
>
Reject
</button>
</div>
</div>
</div>
</c:forEach>
</div>
</div>
<div class="card">
<div class="card-body">
<h4 class="card-title"><a href="${pageContext.request.contextPath}/admin/comments">Bình luận mới</a> </h4>
</div>
<div class="comment-widgets scrollable">
<!-- Comment Row -->
<c:forEach items="${requestScope.top5Review}" var="r">
<div class="d-flex flex-row comment-row mt-0">
<div class="p-2">
<img src="data:image/jpg;base64,${r.cus.base64Image}" alt="user" width="50" height="50" class="rounded-circle" />
</div>
<div class="comment-text w-100">
<h6 class="font-medium"><a href="${pageContext.request.contextPath}/admin/profile?type=customer&id=${r.cus.customerID}">${r.cus.customerName}</a></h6>
<span class="mb-3 d-block">(${r.rate} <i class="fas fa-star" style="color: gold;"></i>)${r.contentSend}
(<a href="${pageContext.request.contextPath}/user/item?pid=${r.pro.productID}"> ${r.pro.productName} </a>)
<c:if test="${r.status}"><i class="mdi mdi-check-circle"></i></c:if>
<c:if test="${!r.status}"><i class="mdi mdi-block-helper"></i></c:if>
</span>
<div class="comment-footer">
<span class="text-muted float-end">${r.dateRate}</span>
<form action="" method="POST" id="review" name="review">
<button type="button" onclick="changeReview('public', '${r.id}')" class=" btn btn-success btn-sm text-white <c:if test="${r.status}">disabled</c:if>">
Publish
</button>
<button type="button" onclick="changeReview('hidden', '${r.id}')" class="btn btn-danger btn-sm text-white <c:if test="${!r.status}">disabled</c:if>">
Hidden
</button>
</form>
</div>
</div>
</div>
</c:forEach>
</div>
</div>
<div class="card">
<div class="card-body">
<h5 class="card-title mb-0">Tài khoản mới</h5>
</div>
<div class="table-responsive">
<table class="table">
<thead class="thead-light">
<tr>
<th>#</th>
<th scope="col">Họ và tên</th>
<th scope="col">Email</th>
<th scope="col">Số điện thoại</th>
<th scope="col">Giới tính</th>
<th scope="col">Địa chỉ</th>
</tr>
</thead>
<tbody class="customtable">
<c:forEach items="${requestScope.newCustomers}" var="c">
<tr>
<td>${c.customerID}</td>
<td><a href="${pageContext.request.contextPath}/admin/profile?type=customer&id=${c.customerID}">${c.customerName}</a></td>
<td>${c.email}</td>
<td>${c.phone}</td>
<td><c:choose>
<c:when test="${!c.gender}">Nữ</c:when>
<c:otherwise>Nam</c:otherwise>
</c:choose></td>
<td>${c.address}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
<div class="card">
<div class="card-body">
<h5 class="card-title mb-0">Khách hàng thân thiết</h5>
</div>
<div class="table-responsive">
<table class="table">
<thead class="thead-light">
<tr>
<th>#</th>
<th scope="col">Họ và tên</th>
<th scope="col">Email</th>
<th scope="col">Số điện thoại</th>
<th scope="col">Giới tính</th>
<th scope="col">Địa chỉ</th>
<th scope="col">Status</th>
<th scope="col">Chi tiêu</th>
</tr>
</thead>
<tbody class="customtable">
<c:forEach items="${requestScope.customerVjp}" var="vjp">
<tr>
<td>${vjp.customerID}</td>
<td><a href="${pageContext.request.contextPath}/admin/profile?type=customer&id=${vjp.customerID}">${vjp.customerName}</a></td>
<td>${vjp.email}</td>
<td>${vjp.phone}</td>
<td><c:choose>
<c:when test="${!vjp.gender}">Nữ</c:when>
<c:otherwise>Nam</c:otherwise>
</c:choose></td>
<td>${vjp.address}</td>
<td><c:choose>
<c:when test="${vjp.acc.status}">Hoạt động</c:when>
<c:otherwise>Khoá</c:otherwise>
</c:choose></td>
<td><fmt:formatNumber value = "${Math.round((vjp.totalMoney)/1000)*1000}" type = "currency"/></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</div>
<footer class="footer text-center">
</footer>
</div>
</div>
<script src="assets/libs/jquery/dist/jquery.min.js"></script>
<script src="assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="assets/libs/perfect-scrollbar/dist/perfect-scrollbar.jquery.min.js"></script>
<script src="assets/extra-libs/sparkline/sparkline.js"></script>
<script src="dist/js/waves.js"></script>
<script src="dist/js/sidebarmenu.js"></script>
<!--Custom JavaScript -->
<script src="dist/js/custom.min.js"></script>
<!--This page JavaScript -->
<!-- <script src="dist/js/pages/dashboards/dashboard1.js"></script> -->
<!-- Charts js Files -->
<script src="assets/libs/flot/excanvas.js"></script>
<script src="assets/libs/flot/jquery.flot.js"></script>
<script src="assets/libs/flot/jquery.flot.pie.js"></script>
<script src="assets/libs/flot/jquery.flot.time.js"></script>
<script src="assets/libs/flot/jquery.flot.stack.js"></script>
<script src="assets/libs/flot/jquery.flot.crosshair.js"></script>
<script src="assets/libs/flot.tooltip/js/jquery.flot.tooltip.min.js"></script>
<script src="dist/js/pages/chart/chart-page-init.js"></script>
<script>
function changeReview(type, id) {
let text;
if (type === 'hidden')
text = "ẩn";
else
text = "hiển thị";
if (confirm("Bạn có chắc muốn " + text + " bình luận này?") === true) {
document.getElementById("review").action = "${pageContext.request.contextPath}/admin/updatereview?rid=" + id + "&type=" + type;
document.getElementById("review").submit();
}
}
var data1 = [];
var data2 = [];
var months = [];
<c:forEach var="item" items="${requestScope.accessByMonth}">
data1.push(${item.second});
months.push(${item.first});
</c:forEach>
<c:forEach var="item" items="${requestScope.ordersByMonth}">
data2.push(${item.second});
</c:forEach>
const monthNames = months.map((month) => {
const date = new Date(Date.UTC(2000, month - 1, 1)); // Create a Date object with the month and year
return date.toLocaleString('default', {month: 'long'}); // Get the full month name
});
function drawChart() {
var chartData = {
series: [
{
name: "Number Orders",
type: "column",
data: data2,
},
{
name: "Active Users",
type: "line",
data: data1,
},
],
xaxis: {
categories: monthNames,
},
};
// Define options for chart
var chartOptions = {
chart: {
height: 350,
type: "line",
stacked: false,
},
dataLabels: {
enabled: false,
},
colors: ["#008FFB", "#00E396"],
series: chartData.series,
xaxis: chartData.xaxis,
};
// Initialize ApexCharts object with chart data and options
var chart = new ApexCharts(document.querySelector("#chart"), chartOptions);
// Render the chart
chart.render();
}
function updateOrder(id, type, cid) {
if (confirm("Are you sure you want " + type + " order " + "have OrderID = " + id + "?")) {
window.location.href = "${pageContext.request.contextPath}/admin/updateorder?oid=" + id + "&type=" + type;
}
}
</script>
</body>
</html> |
import {
Button,
ExperimentalFormTextField,
Form,
} from "@modules/core/components";
import { FormControl } from "@mui/material";
import React from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
type ResetPasswordData = {
password: string;
repeatPassword: string;
};
export interface ResetPasswordFormProps {
onSubmit: (password: string) => void;
}
export const ResetPasswordForm: React.FC<ResetPasswordFormProps> = ({
onSubmit,
}) => {
const { t } = useTranslation();
const form = useForm<ResetPasswordData>();
return (
<Form form={form} onSubmit={({ password }) => onSubmit(password)}>
<ExperimentalFormTextField
form={form}
type="password"
equals={(value) =>
value === form.watch("repeatPassword") || t("passwords unequal")
}
name="password"
required
/>
<ExperimentalFormTextField
label={t("validate password")}
form={form}
type="password"
name="repeatPassword"
required
equals={(value) =>
value === form.watch("password") || t("passwords unequal")
}
/>
<FormControl margin="normal">
<Button testId="submit reset password" type="submit">
{t("save")}
</Button>
</FormControl>
</Form>
);
}; |
<template>
<div class="top-bar-page is-flex is-justify-content-space-between card">
<div class="page-title">
<b-button v-if="is_back" type="is-small" class="button back-btn mr-2" @click="goBack">
<b-icon icon="arrow-left"></b-icon>
</b-button>
<h1 bold>
{{ pageTitle }}
</h1>
</div>
<div class="search" v-if="!is_search">
<b-input custom-class="search-bar"
has-icon-right
icon-right-name="icon-dt-search"
v-model="search1"
placeholder="Search"></b-input>
</div>
<div class="cursor-pointer" v-if="is_reload" @click="$emit('reload')">
<b-tooltip label="Recargar">
<b-icon icon="reload"></b-icon>
</b-tooltip>
</div>
<b-loading is-full-page v-model="isLoading" :can-cancel="false"></b-loading>
</div>
</template>
<script>
import BLoading from "buefy/src/components/loading/Loading";
import {mapGetters, mapActions} from 'vuex'
export default {
name: "topBar",
components: {BLoading},
data() {
return {
search1: ''
}
},
props: {
pageTitle: {
type: String
},
search: {
type: String
},
is_search: {
type: Boolean,
default: true
},
is_reload: {
type: Boolean,
default: false
},
is_back: {
type: Boolean,
default: true
}
},
methods: {
...mapActions({
goBack: 'GO_BACK'
})
},
computed: {
...mapGetters({
isLoading: 'GET_LOADING'
})
}
}
</script>
<style scoped lang="scss">
.top-bar-page {
background-color: #FFFFFF;
height: 60px !important;
width: 100%;
padding: 10px 30px 10px 10px;
display: flex;
align-items: center;
border: none !important;
border-radius: 0 !important;
.page-title {
display: flex;
font-size: 19px;
color: #707070;
padding-left: 10px;
.back-btn {
border: none;
&:focus {
border: none;
box-shadow: none;
}
}
}
}
</style> |
import React, { Fragment, useEffect, useState } from "react";
import "./newProduct.css";
import { Table } from "antd";
import { useSelector, useDispatch } from "react-redux";
import { toast } from 'react-toastify';
import { deleteUser, getAdminProducts, getAdminUsers} from "../../../../redux/features/admin/adminProducts/adminReducer";
import CustomModal from "../../../components/CustomModal";
import { resetState } from "../../../../redux/features/products/productSlice";
import moment from "moment/moment";
const Comments = () => {
const { items } = useSelector((state) => state.admin);
const dispatch = useDispatch()
const [open, setOpen] = useState(false);
const [userId, setUserId] = useState("");
const hideModal = () => {
setOpen(false);
};
useEffect(() => {
dispatch(getAdminProducts())
dispatch(resetState())
}, []);
const columns = [
{ dataIndex: "id", title: "Product ID" },
{
dataIndex: "name",
title: "Name",
},
{
dataIndex: "ratings",
title: "Rating avg",
},
{
dataIndex: "comment",
title: "Comment",
},
{
dataIndex: "time",
title: "Time",
},
{
dataIndex: "username",
title: "User name",
},
{
dataIndex: "lastName",
title: "Last name",
}
];
const rows = [];
console.log(items)
items &&
items?.forEach((item) => {
rows.push({
id: item._id,
name: item?.name,
ratings: item?.ratings,
comment: item?.comments?.map((com) => com?.comment),
time: item?.comments?.map((tim) => moment(tim?.createdAt).format('dd-mm-yyyy')),
username: item?.comments?.map((name) => name?.user?.name),
lastName: item?.comments?.map((name) => name?.user?.lastName)
});
});
const deleteUserHandler = (id) => {
dispatch(deleteUser(id));
setOpen(false);
setTimeout(() => {
dispatch(getAdminUsers());
}, 100);
toast('User deleted')
};
console.log(items)
return (
<Fragment>
<div className="flex w-full pr-10 mt-10">
<div className="w-full">
<h1 className="mb-4 text-2xl">Comments</h1>
<Table columns={columns} dataSource={rows} />
</div>
<CustomModal
hideModal={hideModal}
open={open}
performAction={() => {
deleteUserHandler(userId);
}}
title="Are you sure you want to delete this user?"
/>
</div>
</Fragment>
);
};
export default Comments; |
import axios from 'axios';
import React, { useState } from 'react';
import { AUTH_API } from '../../config/api';
import { useAuthContext } from '../../contexts/AuthContext';
import { ROLES } from '../../constants';
const LoginPage = () => {
const { setUser, setToken, setRole } = useAuthContext();
const [formData, setFormData] = useState({
username: '',
password: '',
});
const handleSubmit = async (event) => {
event.preventDefault();
try {
const res = await axios.post(AUTH_API + 'auth/login', formData);
console.log(res);
setUser(res.data.data);
setToken(res.data.data.token);
setRole(ROLES.USER);
localStorage.setItem('token', res.data.data.token);
localStorage.setItem('role', ROLES.USER);
} catch (err) {
console.log(err);
}
};
const handleChangeInput = ({ target: { value, name } }) =>
setFormData((prev) => ({ ...prev, [name]: value }));
return (
<form onSubmit={handleSubmit}>
<label htmlFor='username'>User Name</label>
<input
type='text'
id='username'
name='username'
onChange={handleChangeInput}
value={formData.username}
/>
<label htmlFor='password'>Password</label>
<input
type='password'
id='password'
name='password'
onChange={handleChangeInput}
value={formData.password}
/>
<button type='submit'>Login</button>
</form>
);
};
export default LoginPage; |
import numpy as np
import unittest
class Game:
def __init__(self, grid_size=10):
self.grid = np.zeros((grid_size, grid_size), dtype=int)
self.players = ['X', 'O']
self.current_player = 0
self.game_state = 'in progress'
def play(self):
print('Welcome to Pong!')
print(f'Grid size: {self.grid.shape[0]}x{self.grid.shape[1]}')
while self.game_state == 'in progress':
column = self.get_player_input()
if column is None:
continue
self.place_piece(column)
self.check_win()
self.switch_player()
self.display_grid()
if self.game_state == 'won':
print(f'Player {self.players[self.current_player]} wins!')
elif self.game_state == 'draw':
print('Draw!')
def get_player_input(self):
while True:
try:
column = int(input(f'Player {self.players[self.current_player]}, choose a column (0-{self.grid.shape[1]-1}) or "q" to quit: '))
if column < 0 or column >= self.grid.shape[1]:
print('Invalid column')
continue
elif column == 'q':
print('Exiting game...')
exit()
break
except ValueError:
print('Invalid input')
return column
def place_piece(self, column):
try:
for i in range(self.grid.shape[0]-1, -1, -1):
if self.grid[i, column] == 0:
self.grid[i, column] = self.players[self.current_player]
break
except IndexError:
print('Invalid column')
def check_win(self):
# Horizontal checks
for i in range(self.grid.shape[0]):
if np.all(self.grid[i, :] == self.players[self.current_player]):
self.game_state = 'won'
return
# Vertical checks
for j in range(self.grid.shape[1]):
if np.all(self.grid[:, j] == self.players[self.current_player]):
self.game_state = 'won'
return
# Diagonal checks
for i in range(self.grid.shape[0]-2):
for j in range(self.grid.shape[1]-2):
if np.all(self.grid[i+k, j+k] == self.players[self.current_player] for k in range(3)):
self.game_state = 'won'
return
for i in range(2, self.grid.shape[0]):
for j in range(self.grid.shape[1]-2):
if np.all(self.grid[i-k, j+k] == self.players[self.current_player] for k in range(3)):
self.game_state = 'won'
return
# Draw check
if np.all(self.grid != 0):
self.game_state = 'draw'
def switch_player(self):
self.current_player = (self.current_player + 1) % len(self.players)
def display_grid(self):
print(self.grid)
class GameTest(unittest.TestCase):
def test_place_piece(self):
game = Game()
game.place_piece(0)
self.assertEqual(game.grid[9, 0], 'X')
if __name__ == '__main__':
grid_size = int(input('Enter the grid size (e.g., 10): '))
game = Game(grid_size)
game.play() |
require 'spec_helper'
describe 'postgresql::server::plpython', :type => :class do
let :facts do
{
:osfamily => 'RedHat',
:operatingsystem => 'CentOS',
:operatingsystemrelease => '6.0',
:concat_basedir => tmpfilename('plpython'),
:kernel => 'Linux',
:id => 'root',
:path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
:selinux => true,
}
end
let :pre_condition do
"class { 'postgresql::server': }"
end
describe 'on RedHat with no parameters' do
it { is_expected.to contain_class("postgresql::server::plpython") }
it 'should create package' do
is_expected.to contain_package('postgresql-plpython').with({
:ensure => 'present',
:tag => 'postgresql',
})
end
end
describe 'with parameters' do
let :params do
{
:package_ensure => 'absent',
:package_name => 'mypackage',
}
end
it { is_expected.to contain_class("postgresql::server::plpython") }
it 'should create package with correct params' do
is_expected.to contain_package('postgresql-plpython').with({
:ensure => 'absent',
:name => 'mypackage',
:tag => 'postgresql',
})
end
end
end |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>socket</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/socket.io@4.1.2/client-dist/socket.io.min.js"></script>
<div id="app">
<div class="border">
<div class="list">
<p v-for="item in list">{{item}}</p>
</div>
<div class="bar">
<input type="text" v-model="message" placeholder="请输入消息"/>
<button @click="sendMessage">发送</button>
</div>
</div>
</div>
<script>
var socket = io();
var app = new Vue({
el: "#app",
data: {
list: ["你好!"],
message: "",
},
mounted() {
socket.on("chat message", (msg) => {
this.list.push(msg);
});
},
methods: {
sendMessage: function () {
socket.emit("chat message", this.message);
this.message = "";
},
},
});
</script>
<style>
.border {
padding: 16px;
box-sizing: border-box;
border: 1px solid black;
height: calc(100vh - 16px);
display: flex;
flex-direction: column;
justify-content: space-between;
}
.list {
overflow: auto;
}
.bar {
display: flex;
}
.bar input {
flex: 1;
}
</style>
</body>
</html> |
#
# (C) Tenable Network Security, Inc.
#
# The descriptive text and package checks in this plugin were
# extracted from Red Hat Security Advisory RHSA-2012:0387 and
# Oracle Linux Security Advisory ELSA-2012-0387 respectively.
#
if (NASL_LEVEL < 3000) exit(0);
include("compat.inc");
if (description)
{
script_id(68495);
script_version("$Revision: 1.4 $");
script_cvs_date("$Date: 2015/12/01 17:07:15 $");
script_cve_id("CVE-2012-0451", "CVE-2012-0455", "CVE-2012-0456", "CVE-2012-0457", "CVE-2012-0458", "CVE-2012-0459", "CVE-2012-0460", "CVE-2012-0461", "CVE-2012-0462", "CVE-2012-0464");
script_bugtraq_id(52456, 52457, 52458, 52459, 52460, 52461, 52463, 52464, 52465, 52467);
script_osvdb_id(80011, 80012, 80013, 80014, 80015, 80016, 80017, 80018, 80019, 80020);
script_xref(name:"RHSA", value:"2012:0387");
script_name(english:"Oracle Linux 5 / 6 : firefox (ELSA-2012-0387)");
script_summary(english:"Checks rpm output for the updated packages");
script_set_attribute(
attribute:"synopsis",
value:"The remote Oracle Linux host is missing one or more security updates."
);
script_set_attribute(
attribute:"description",
value:
"From Red Hat Security Advisory 2012:0387 :
Updated firefox packages that fix multiple security issues and three
bugs are now available for Red Hat Enterprise Linux 5 and 6.
The Red Hat Security Response Team has rated this update as having
critical security impact. Common Vulnerability Scoring System (CVSS)
base scores, which give detailed severity ratings, are available for
each vulnerability from the CVE links in the References section.
Mozilla Firefox is an open source web browser.
Several flaws were found in the processing of malformed web content. A
web page containing malicious content could cause Firefox to crash or,
potentially, execute arbitrary code with the privileges of the user
running Firefox. (CVE-2012-0461, CVE-2012-0462, CVE-2012-0464)
Two flaws were found in the way Firefox parsed certain Scalable Vector
Graphics (SVG) image files. A web page containing a malicious SVG
image file could cause an information leak, or cause Firefox to crash
or, potentially, execute arbitrary code with the privileges of the
user running Firefox. (CVE-2012-0456, CVE-2012-0457)
A flaw could allow a malicious site to bypass intended restrictions,
possibly leading to a cross-site scripting (XSS) attack if a user were
tricked into dropping a 'javascript:' link onto a frame.
(CVE-2012-0455)
It was found that the home page could be set to a 'javascript:' link.
If a user were tricked into setting such a home page by dragging a
link to the home button, it could cause Firefox to repeatedly crash,
eventually leading to arbitrary code execution with the privileges of
the user running Firefox. (CVE-2012-0458)
A flaw was found in the way Firefox parsed certain web content
containing 'cssText'. A web page containing malicious content could
cause Firefox to crash or, potentially, execute arbitrary code with
the privileges of the user running Firefox. (CVE-2012-0459)
It was found that by using the DOM fullscreen API, untrusted content
could bypass the mozRequestFullscreen security protections. A web page
containing malicious web content could exploit this API flaw to cause
user interface spoofing. (CVE-2012-0460)
A flaw was found in the way Firefox handled pages with multiple
Content Security Policy (CSP) headers. This could lead to a cross-site
scripting attack if used in conjunction with a website that has a
header injection flaw. (CVE-2012-0451)
For technical details regarding these flaws, refer to the Mozilla
security advisories for Firefox 10.0.3 ESR. You can find a link to the
Mozilla advisories in the References section of this erratum.
This update also fixes the following bugs :
* When using the Traditional Chinese locale (zh-TW), a segmentation
fault sometimes occurred when closing Firefox. (BZ#729632)
* Inputting any text in the Web Console (Tools -> Web Developer -> Web
Console) caused Firefox to crash. (BZ#784048)
* The java-1.6.0-ibm-plugin and java-1.6.0-sun-plugin packages require
the '/usr/lib/mozilla/plugins/' directory on 32-bit systems, and the
'/usr/lib64/mozilla/plugins/' directory on 64-bit systems. These
directories are created by the xulrunner package; however, they were
missing from the xulrunner package provided by the RHEA-2012:0327
update. Therefore, upgrading to RHEA-2012:0327 removed those
directories, causing dependency errors when attempting to install the
java-1.6.0-ibm-plugin or java-1.6.0-sun-plugin package. With this
update, xulrunner once again creates the plugins directory. This issue
did not affect users of Red Hat Enterprise Linux 6. (BZ#799042)
All Firefox users should upgrade to these updated packages, which
contain Firefox version 10.0.3 ESR, which corrects these issues. After
installing the update, Firefox must be restarted for the changes to
take effect."
);
script_set_attribute(
attribute:"see_also",
value:"https://oss.oracle.com/pipermail/el-errata/2012-March/002699.html"
);
script_set_attribute(
attribute:"see_also",
value:"https://oss.oracle.com/pipermail/el-errata/2012-March/002701.html"
);
script_set_attribute(
attribute:"solution",
value:"Update the affected firefox packages."
);
script_set_cvss_base_vector("CVSS2#AV:N/AC:M/Au:N/C:C/I:C/A:C");
script_set_cvss_temporal_vector("CVSS2#E:ND/RL:OF/RC:C");
script_set_attribute(attribute:"exploitability_ease", value:"No known exploits are available");
script_set_attribute(attribute:"exploit_available", value:"false");
script_set_attribute(attribute:"plugin_type", value:"local");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:oracle:linux:firefox");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:oracle:linux:xulrunner");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:oracle:linux:xulrunner-devel");
script_set_attribute(attribute:"cpe", value:"cpe:/o:oracle:linux:5");
script_set_attribute(attribute:"cpe", value:"cpe:/o:oracle:linux:6");
script_set_attribute(attribute:"patch_publication_date", value:"2012/03/15");
script_set_attribute(attribute:"plugin_publication_date", value:"2013/07/12");
script_end_attributes();
script_category(ACT_GATHER_INFO);
script_copyright(english:"This script is Copyright (C) 2013-2015 Tenable Network Security, Inc.");
script_family(english:"Oracle Linux Local Security Checks");
script_dependencies("ssh_get_info.nasl");
script_require_keys("Host/local_checks_enabled", "Host/OracleLinux", "Host/RedHat/release", "Host/RedHat/rpm-list");
exit(0);
}
include("audit.inc");
include("global_settings.inc");
include("rpm.inc");
if (!get_kb_item("Host/local_checks_enabled")) audit(AUDIT_LOCAL_CHECKS_NOT_ENABLED);
if (!get_kb_item("Host/OracleLinux")) audit(AUDIT_OS_NOT, "Oracle Linux");
release = get_kb_item("Host/RedHat/release");
if (isnull(release) || !eregmatch(pattern: "Oracle (?:Linux Server|Enterprise Linux)", string:release)) audit(AUDIT_OS_NOT, "Oracle Linux");
os_ver = eregmatch(pattern: "Oracle (?:Linux Server|Enterprise Linux) .*release ([0-9]+(\.[0-9]+)?)", string:release);
if (isnull(os_ver)) audit(AUDIT_UNKNOWN_APP_VER, "Oracle Linux");
os_ver = os_ver[1];
if (! ereg(pattern:"^(5|6)([^0-9]|$)", string:os_ver)) audit(AUDIT_OS_NOT, "Oracle Linux 5 / 6", "Oracle Linux " + os_ver);
if (!get_kb_item("Host/RedHat/rpm-list")) audit(AUDIT_PACKAGE_LIST_MISSING);
cpu = get_kb_item("Host/cpu");
if (isnull(cpu)) audit(AUDIT_UNKNOWN_ARCH);
if ("x86_64" >!< cpu && "ia64" >!< cpu && cpu !~ "^i[3-6]86$") audit(AUDIT_LOCAL_CHECKS_NOT_IMPLEMENTED, "Oracle Linux", cpu);
flag = 0;
if (rpm_check(release:"EL5", reference:"firefox-10.0.3-1.0.1.el5_8")) flag++;
if (rpm_check(release:"EL5", reference:"xulrunner-10.0.3-1.0.1.el5_8")) flag++;
if (rpm_check(release:"EL5", reference:"xulrunner-devel-10.0.3-1.0.1.el5_8")) flag++;
if (rpm_check(release:"EL6", reference:"firefox-10.0.3-1.0.1.el6_2")) flag++;
if (rpm_check(release:"EL6", reference:"xulrunner-10.0.3-1.0.1.el6_2")) flag++;
if (rpm_check(release:"EL6", reference:"xulrunner-devel-10.0.3-1.0.1.el6_2")) flag++;
if (flag)
{
if (report_verbosity > 0) security_hole(port:0, extra:rpm_report_get());
else security_hole(0);
exit(0);
}
else
{
tested = pkg_tests_get();
if (tested) audit(AUDIT_PACKAGE_NOT_AFFECTED, tested);
else audit(AUDIT_PACKAGE_NOT_INSTALLED, "firefox / xulrunner / xulrunner-devel");
} |
package com.example.demo.jwt;
import com.example.demo.error.ErrorJwtCode;
import com.example.demo.service.jwtservice.UserDetailsServiceImpl;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.json.simple.JSONObject;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
@RequiredArgsConstructor
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtTokenProvider jwtTokenProvider;
private final UserDetailsServiceImpl userDetailsServiceImpl;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String path = request.getRequestURI();
String method = request.getMethod();
if (path.startsWith("/swagger-ui") || path.startsWith("/v3/api-docs") || path.startsWith("/swagger-resources")
|| path.startsWith("/auth")
|| (method.equals(HttpMethod.GET.name()) && path.startsWith("/board"))
|| path.contains("/userinfo/character/info")) {
filterChain.doFilter(request,response);
return;
}
// 헤더에서 Token을 따옴
String accessToken = jwtTokenProvider.resolveAccessToken(request);
ErrorJwtCode errorCode;
if (accessToken == null || accessToken.trim().isEmpty()) {
errorCode = ErrorJwtCode.EMPTY_TOKEN;
setResponse(response,errorCode);
return; // 위의 링크에 걸리지 않고 토큰이 없는 경우 엠티처리
}
try {
if (accessToken != null && jwtTokenProvider.validateToken(accessToken)) {
// Get the username from the access token
log.info("jwt필터진입");
String email = jwtTokenProvider.getUserEmailFromAccessToken(accessToken);
// Load the user details
UserDetails userDetails = userDetailsServiceImpl.loadUserByUsername(email);
// Create an authentication object
Authentication authentication =
new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
// Set the authentication object in the security context
SecurityContextHolder.getContext().setAuthentication(authentication);
}
} catch (MalformedJwtException e) {
log.info("103 error");
errorCode = ErrorJwtCode.INVALID_TOKEN;
setResponse(response, errorCode);
return;
} catch (ExpiredJwtException e) {
log.info("101 error");
errorCode = ErrorJwtCode.EXPIRED_AT;
setResponse(response, errorCode);
return;
} catch (UnsupportedJwtException e) {
log.info("105 error");
errorCode = ErrorJwtCode.INVALID_TOKEN;
setResponse(response, errorCode);
return;
} catch (IllegalArgumentException e) {
log.info("104 error");
errorCode = ErrorJwtCode.EMPTY_TOKEN;
setResponse(response, errorCode);
return;
} catch (SignatureException e) {
log.info("106 error");
errorCode = ErrorJwtCode.INVALID_TOKEN;
setResponse(response, errorCode);
return;
} catch (RuntimeException e) {
log.info("4006 error");
errorCode = ErrorJwtCode.JWT_COMPLEX_ERROR;
setResponse(response, errorCode);
return;
}
filterChain.doFilter(request, response);
}
private void setResponse(HttpServletResponse response, ErrorJwtCode errorCode) throws IOException {
JSONObject json = new JSONObject();
response.setContentType("application/json;charset=UTF-8");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
json.put("code", errorCode.getCode());
json.put("message", errorCode.getMessage());
response.getWriter().print(json);
response.getWriter().flush();
}
} |
import { createSlice } from '@reduxjs/toolkit';
interface UserComment {
id: number;
name: string;
surname: string;
job: string;
comment: string;
avatar: string;
}
interface UserQuestion {
id: number;
question: string;
answer: string;
}
interface ServiceType {
id: number;
title: string;
description: string;
}
interface UsersState {
usersComments: Array<UserComment>;
usersQuestions: Array<UserQuestion>;
services: Array<ServiceType>;
}
export const initialState: UsersState = {
usersComments: [
{
id: 1,
name: 'Name',
surname: 'Surname',
job: 'Job',
comment: 'Some text awdwadwdawd awdawdadad awdwadawd awdawdawd lorem',
avatar:
'https://images.unsplash.com/photo-1633332755192-727a05c4013d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8dXNlcnxlbnwwfHwwfHw%3D&w=1000&q=80',
},
{
id: 2,
name: 'Name',
surname: 'Surname',
job: 'Job',
comment: 'Some text awdwadwdawd awdawdadad awdwadawd awdawdawd lorem',
avatar: 'https://www.statxo.com/wp-content/uploads/2018/06/pexels-photo-555790.png',
},
{
id: 3,
name: 'Name',
surname: 'Surname',
job: 'Job',
comment: 'Some text awdwadwdawd awdawdadad awdwadawd awdawdawd lorem',
avatar:
'https://media.istockphoto.com/photos/portrait-of-handsome-smiling-young-man-with-crossed-arms-picture-id1200677760?k=20&m=1200677760&s=612x612&w=0&h=JCqytPoHb6bQqU9bq6gsWT2EX1G5chlW5aNK81Kh4Lg=',
},
{
id: 4,
name: 'Name',
surname: 'Surname',
job: 'Job',
comment: 'Some text awdwadwdawd awdawdadad awdwadawd awdawdawd lorem',
avatar: 'https://img.freepik.com/free-photo/man-saying-ok_1149-1714.jpg?size=626&ext=jpg',
},
{
id: 5,
name: 'Name',
surname: 'Surname',
job: 'Job',
comment: 'Some text awdwadwdawd awdawdadad awdwadawd awdawdawd lorem',
avatar: 'https://www.itweek.ru/etc/kyocera-svistunov-1.jpg',
},
],
usersQuestions: [
{
id: 1,
question: 'When is outsorcing a good option?',
answer:
' Lorem ipsum dolor sit amet consectetur adipisicing elit. Molestias excepturi error facere ad quo inventore accusantium magnam aliquam ab qui! Exercitationem fuga corporis placeat praesentium tempore, necessitatibus amet consequuntur ipsa.',
},
{
id: 2,
question: 'How long does it take to start a project?',
answer:
' Lorem ipsum dolor sit amet consectetur adipisicing elit. Molestias excepturi error facere ad quo inventore accusantium magnam aliquam ab qui! Exercitationem fuga corporis placeat praesentium tempore, necessitatibus amet consequuntur ipsa.',
},
{
id: 3,
question: 'How does communication progress look like?',
answer:
' Lorem ipsum dolor sit amet consectetur adipisicing elit. Molestias excepturi error facere ad quo inventore accusantium magnam aliquam ab qui! Exercitationem fuga corporis placeat praesentium tempore, necessitatibus amet consequuntur ipsa.',
},
{
id: 4,
question: 'How do you make sure my intellectual property status secure?',
answer:
' Lorem ipsum dolor sit amet consectetur adipisicing elit. Molestias excepturi error facere ad quo inventore accusantium magnam aliquam ab qui! Exercitationem fuga corporis placeat praesentium tempore, necessitatibus amet consequuntur ipsa.',
},
{
id: 5,
question: 'Can i add your specialists to my existing team?',
answer:
' Lorem ipsum dolor sit amet consectetur adipisicing elit. Molestias excepturi error facere ad quo inventore accusantium magnam aliquam ab qui! Exercitationem fuga corporis placeat praesentium tempore, necessitatibus amet consequuntur ipsa.',
},
],
services: [
{ id: 1, title: 'Full dedication', description: 'Text text text text' },
{ id: 2, title: 'Quick start', description: 'Text text text text' },
{ id: 3, title: 'Simple scalability', description: 'Text text text text' },
{ id: 4, title: 'Hassle free administration', description: 'Text text text text' },
],
};
export const mainSlice = createSlice({
name: 'main',
initialState,
reducers: {},
});
export default mainSlice.reducer; |
//
// TradesViewController.swift
// genesisvision-ios
//
// Created by George on 11/04/2018.
// Copyright © 2018 Genesis Vision. All rights reserved.
//
import UIKit
class TradesViewController: BaseViewControllerWithTableView {
// MARK: - View Model
var viewModel: TradesViewModelProtocol!
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
// MARK: - Private methods
private func setupTableConfiguration() {
tableView.configure(with: .defaultConfiguration)
tableView.allowsSelection = false
tableView.delegate = viewModel.dataSource
tableView.dataSource = viewModel.dataSource
tableView.registerNibs(for: viewModel.cellModelsForRegistration)
tableView.registerHeaderNib(for: viewModel.viewModelsForRegistration)
setupPullToRefresh(scrollView: tableView)
}
private func setup() {
bottomViewType = viewModel.isOpenTrades ? .none : .dateRange
noDataTitle = viewModel.noDataText()
setupTableConfiguration()
setupNavigationBar()
}
private func reloadData() {
DispatchQueue.main.async {
self.refreshControl?.endRefreshing()
self.tableView?.reloadDataSmoothly()
}
}
override func fetch() {
viewModel.refresh { [weak self] (result) in
self?.hideAll()
switch result {
case .success:
break
case .failure(let errorType):
ErrorHandler.handleError(with: errorType, viewController: self)
}
}
}
override func pullToRefresh() {
super.pullToRefresh()
fetch()
}
override func updateData(from dateFrom: Date?, to dateTo: Date?, dateRangeType: DateRangeType? = nil) {
viewModel.dateFrom = dateFrom
viewModel.dateTo = dateTo
dateRangeModel = FilterDateRangeModel(dateRangeType: dateRangeType ?? .month, dateFrom: dateFrom, dateTo: dateTo)
showProgressHUD()
fetch()
}
}
extension TradesViewController: ReloadDataProtocol {
func didReloadData() {
reloadData()
tabmanBarItems?.forEach({ $0.badgeValue = "\(viewModel.totalCount)" })
}
} |
import {
Body,
Controller,
Get,
NotFoundException,
Param,
Post,
Query,
SerializeOptions,
} from '@nestjs/common'
import {
ApiCreatedResponse,
ApiOkResponse,
ApiParam,
ApiTags,
} from '@nestjs/swagger'
import {
LoanServicingEvent,
Transaction,
TransactionResolution,
SummarisedTransaction,
} from 'loan-servicing-common'
import {
AddWithdrawalToDrawingDtoClass,
DrawingDtoClass,
NewDrawingRequestDtoClass,
RevertWithdrawalDtoClass,
} from 'models/dtos/drawing'
import { UntypedEventClass } from 'models/dtos/event'
import TransactionEntity from 'models/entities/TransactionEntity'
import { plainToInstance } from 'class-transformer'
import {
ManualRepaymentStrategyOptionsDtoClass,
RegularRepaymentStrategyOptionsDtoClass,
} from 'models/dtos/drawingConfiguration'
import {
AddFixedDrawingAccrualDtoClass,
AddMarketDrawingAccrualDtoClass,
RecordDrawingAccrualPaymentDtoClass,
} from 'models/dtos/drawingAccrual'
import { RecordDrawingRepaymentDtoClass } from 'models/dtos/drawingRepayment'
import EventService from 'modules/event/event.service'
import DrawingService from './drawing.service'
import DrawingTransactionService from './drawing.transactions.service'
@ApiTags('Drawing')
@Controller('/facility/:facilityId/drawing')
@ApiParam({ name: 'facilityId', required: true, type: 'string' })
class DrawingController {
constructor(
private drawingService: DrawingService,
private transactionService: DrawingTransactionService,
private eventService: EventService,
) {}
@Get(':drawingId')
@ApiOkResponse({ type: DrawingDtoClass })
async getDrawing(
@Param('drawingId') drawingStreamId: string,
@Query('rebuild') rebuild?: boolean,
): Promise<DrawingDtoClass> {
const drawing = await this.drawingService.getDrawing(
drawingStreamId,
rebuild,
)
if (drawing === null) {
throw new NotFoundException()
}
return plainToInstance(DrawingDtoClass, drawing, {
enableCircularCheck: true,
})
}
@Get(':drawingId/events')
@ApiOkResponse({ type: UntypedEventClass })
async getDrawingEvents(
@Param('drawingId') drawingStreamId: string,
): Promise<LoanServicingEvent[]> {
const facilityEvents =
await this.drawingService.getDrawingEvents(drawingStreamId)
if (facilityEvents === null) {
throw new NotFoundException()
}
return facilityEvents.filter((e) => e.isApproved)
}
@Get(':drawingId/events/unapproved')
@ApiOkResponse({ type: UntypedEventClass })
async getUnapprovedDrawingEvents(
@Param('drawingId') drawingStreamId: string,
): Promise<LoanServicingEvent[]> {
const facilityEvents =
await this.drawingService.getDrawingEvents(drawingStreamId)
if (facilityEvents === null) {
throw new NotFoundException()
}
return facilityEvents.filter((e) => !e.isApproved)
}
@Get(':drawingId/transactions')
@ApiOkResponse({ type: TransactionEntity })
async getDrawingTransactions(
@Param('drawingId') drawingStreamId: string,
@Query('interestResolution')
interestResolution: TransactionResolution = 'daily',
): Promise<Transaction[] | SummarisedTransaction[]> {
const facilityEvents =
interestResolution === 'daily'
? await this.transactionService.getDailyTransactions(drawingStreamId)
: await this.transactionService.getMonthlyTransactions(drawingStreamId)
if (facilityEvents === null) {
throw new NotFoundException()
}
return facilityEvents
}
@Get()
@ApiOkResponse({ type: DrawingDtoClass })
async getAllDrawing(): Promise<DrawingDtoClass[] | null> {
const allEvents = await this.drawingService.getAllDrawings()
if (allEvents === null) {
throw new NotFoundException()
}
return plainToInstance(DrawingDtoClass, allEvents, {
enableCircularCheck: true,
})
}
@Post('')
@ApiCreatedResponse({ type: DrawingDtoClass })
@SerializeOptions({ enableCircularCheck: true })
async newDrawing(
@Body() body: NewDrawingRequestDtoClass,
@Param('facilityId') facilityId: string,
@Query('facilityVersion') facilityVersion: number,
): Promise<DrawingDtoClass> {
const newDrawing = await this.drawingService.createNewDrawing(
facilityId,
facilityVersion,
body,
)
return plainToInstance(DrawingDtoClass, newDrawing, {
enableCircularCheck: true,
})
}
@Post(':drawingId/withdrawal')
@ApiOkResponse({ type: DrawingDtoClass })
async withdrawFromDrawing(
@Param('facilityId') facilityId: string,
@Param('drawingId') drawingId: string,
@Query('version') version: number,
@Body() body: AddWithdrawalToDrawingDtoClass,
): Promise<DrawingDtoClass> {
const updatedDrawing = await this.drawingService.withdrawFromDrawing(
facilityId,
drawingId,
Number(version),
body,
)
return plainToInstance(DrawingDtoClass, updatedDrawing, {
enableCircularCheck: true,
})
}
@Post(':drawingId/withdrawal/revert')
@ApiOkResponse({ type: DrawingDtoClass })
async revertWithdrawal(
@Param('facilityId') facilityId: string,
@Param('drawingId') drawingId: string,
@Body() body: RevertWithdrawalDtoClass,
@Query('version') version: number,
): Promise<DrawingDtoClass> {
const updatedDrawing = await this.drawingService.revertWithdrawal(
facilityId,
drawingId,
Number(version),
body,
)
return plainToInstance(DrawingDtoClass, updatedDrawing, {
enableCircularCheck: true,
})
}
@Post(':drawingId/repayments/regular')
@ApiOkResponse({ type: DrawingDtoClass })
async setRegularRepaymentsOnDrawing(
@Param('facilityId') facilityId: string,
@Param('drawingId') drawingId: string,
@Query('version') version: number,
@Body() body: RegularRepaymentStrategyOptionsDtoClass,
): Promise<DrawingDtoClass> {
const updatedDrawing = await this.drawingService.setRepayments(
facilityId,
drawingId,
Number(version),
body,
)
return plainToInstance(DrawingDtoClass, updatedDrawing, {
enableCircularCheck: true,
})
}
@Post(':drawingId/repayments/manual')
@ApiOkResponse({ type: DrawingDtoClass })
async setManualRepaymentsOnDrawing(
@Param('facilityId') facilityId: string,
@Param('drawingId') drawingId: string,
@Query('version') version: number,
@Body() body: ManualRepaymentStrategyOptionsDtoClass,
): Promise<DrawingDtoClass> {
const updatedDrawing = await this.drawingService.setRepayments(
facilityId,
drawingId,
Number(version),
body,
)
return plainToInstance(DrawingDtoClass, updatedDrawing, {
enableCircularCheck: true,
})
}
@Post(':drawingId/accrual/fixed')
@ApiOkResponse({ type: DrawingDtoClass })
async addFixedAccrualDrawing(
@Param('facilityId') facilityId: string,
@Param('drawingId') drawingId: string,
@Query('version') version: number,
@Body() body: AddFixedDrawingAccrualDtoClass,
): Promise<DrawingDtoClass> {
const updatedDrawing = await this.drawingService.addDrawingAccrual(
facilityId,
drawingId,
Number(version),
{ ...body, name: 'FixedDrawingAccrual' },
)
return plainToInstance(DrawingDtoClass, updatedDrawing, {
enableCircularCheck: true,
})
}
@Post(':drawingId/accrual/market')
@ApiOkResponse({ type: DrawingDtoClass })
async addMarketAccrualDrawing(
@Param('facilityId') facilityId: string,
@Param('drawingId') drawingId: string,
@Query('version') version: number,
@Body() body: AddMarketDrawingAccrualDtoClass,
): Promise<DrawingDtoClass> {
const updatedDrawing = await this.drawingService.addDrawingAccrual(
facilityId,
drawingId,
Number(version),
{ ...body, name: 'MarketDrawingAccrual' },
)
return plainToInstance(DrawingDtoClass, updatedDrawing, {
enableCircularCheck: true,
})
}
@Post(':drawingId/repaymentReceived')
@ApiOkResponse({ type: DrawingDtoClass })
async markRepaymentAsReceived(
@Param('facilityId') facilityId: string,
@Param('drawingId') drawingId: string,
@Query('version') version: number,
@Body() recordRepaymentDto: RecordDrawingRepaymentDtoClass,
): Promise<DrawingDtoClass> {
const updatedDrawing = await this.drawingService.setRepaymentAsReceived(
facilityId,
drawingId,
Number(version),
recordRepaymentDto,
)
return plainToInstance(DrawingDtoClass, updatedDrawing, {
enableCircularCheck: true,
})
}
@Post(':drawingId/repaymentReceived/approveEvent')
@ApiOkResponse({ type: RecordDrawingRepaymentDtoClass })
async approveReceivedRepayment(
@Query('id') eventId: number,
): Promise<RecordDrawingRepaymentDtoClass> {
const updatedDrawing = await this.eventService.approveEvent(eventId)
return plainToInstance(RecordDrawingRepaymentDtoClass, updatedDrawing, {
enableCircularCheck: true,
})
}
@Post(':drawingId/accuralPaymentReceived')
@ApiOkResponse({ type: DrawingDtoClass })
async processAccrualPayment(
@Param('facilityId') facilityId: string,
@Param('drawingId') drawingId: string,
@Query('version') version: number,
@Body() recordRepaymentDto: RecordDrawingAccrualPaymentDtoClass,
): Promise<DrawingDtoClass> {
const updatedDrawing = await this.drawingService.receiveAccrualPayment(
facilityId,
drawingId,
Number(version),
recordRepaymentDto,
)
return plainToInstance(DrawingDtoClass, updatedDrawing, {
enableCircularCheck: true,
})
}
@Post(':drawingId/approveEvent')
@ApiOkResponse({ type: RecordDrawingAccrualPaymentDtoClass })
async approveDrawingEvent(@Query('id') eventId: number): Promise<void> {
await this.eventService.approveEvent(eventId)
}
}
export default DrawingController |
"use client"
import { useForm } from "react-hook-form"
import { useRouter } from "next/navigation"
import { z } from "zod"
import { zodResolver } from "@hookform/resolvers/zod"
import Image from "next/image"
import { Button, Input } from "@nextui-org/react";
import { useState } from "react"
import { Spinner } from "@/app/componentes/ui/Spinner";
import { EyeSlashFilledIcon } from "@/app/componentes/ui/icons/EyeSlashFilledIcon"
import { EyeFilledIcon } from "@/app/componentes/ui/icons/EyeFilledIcon"
import endpoints from "@/lib/endpoints"
import Link from "next/link"
const passSchema = z.object({
contrasenaNueva: z.string()
.min(8, "La contraseña debe tener al menos 8 caracteres.")
.regex(/^(?=.*[A-Z])(?=.*\d).+/, "La contraseña debe tener al menos una mayúscula y un número."),
contrasenaRepetida: z.string()
}).refine(data => data.contrasenaRepetida === data.contrasenaNueva, {
message: "Las contraseñas deben coincidir",
path: ["contrasenaRepetida"]
});
type PasswordForm = z.infer<typeof passSchema> & { erroresExternos?: string };
const ResetPassword = ({ params }: { params: { token: string, idUsuario: string } }) => {
const router = useRouter();
const {
register,
handleSubmit,
formState: {
errors,
isSubmitting
},
reset,
getValues,
setError
} = useForm<PasswordForm>({
resolver: zodResolver(passSchema)
});
const onSubmit = async (data: PasswordForm) => {
try {
const res = await fetch(process.env.NEXT_PUBLIC_BACKEND_URL + endpoints.changePassword(params.idUsuario), {
method: 'PUT',
body: JSON.stringify({
token: params.token,
contrasena: data.contrasenaNueva
}),
headers: {
'Content-Type': 'application/json',
}
});
if (res.status === 401) {
setError("erroresExternos", { message: "Error: su sesión ha expirado, será redirigido a la página principal." });
await new Promise((resolve) => setTimeout(resolve, 4000));
router.replace('/');
return;
}
if (!res.ok) {
setError("erroresExternos", { message: "La contraseña seleccionada es inválida" });
return;
}
setPasswordHasChanged(!passwordHasChanged);
} catch (err) {
setError("erroresExternos", { message: "Hubo un problema. Por favor, intente nuevamente." });
}
}
const [isPasswordVisible, setIsPasswordVisible] = useState(false);
const [isRepetidaVisible, setIsRepetidaVisible] = useState(false);
const [passwordHasChanged, setPasswordHasChanged] = useState(false);
return (
<div className="flex h-[100dvh] md:h-screen items-center bg-white text-black light">
<aside className="hidden sm:flex justify-center flex-[2] h-full bg-white">
<Image src="/bienvenido.png" alt="Bienvenido a FlipBoard" width={500} height={500} className="object-contain" />
</aside>
<main className="flex-[1] px-8 md:px-10 flex justify-center lg:items-center overflow-y-auto overflow-x-hidden h-full">
<section className="flex flex-col items-center gap-3 p-8 border-2 border-gray-700 shadow-md dark:shadow-gray-700 rounded h-fit my-5">
<Image src="/flipboard-icon.png" alt="FlipBoard" width={100} height={100} />
<h1 className="text-xl">Reestablecer contraseña</h1>
{!passwordHasChanged ?
<>
<p className=" text-base text-center max-w-xs">Complete los siguientes campos para cambiar su contraseña</p>
<form action="" className="flex flex-col gap-3 w-full max-w-[250px]" onSubmit={handleSubmit(onSubmit)}>
<Input
variant="bordered"
type={isPasswordVisible ? "text" : "password"}
label="Nueva contraseña"
placeholder="********"
isRequired
isInvalid={!!errors.contrasenaNueva}
errorMessage={errors.contrasenaNueva?.message}
{...register("contrasenaNueva")}
endContent={
<button className="focus:outline-none" type="button" onClick={() => setIsPasswordVisible(!isPasswordVisible)} tabIndex={99}>
{isPasswordVisible ? (
<EyeSlashFilledIcon className="text-2xl text-default-400 pointer-events-none" />
) : (
<EyeFilledIcon className="text-2xl text-default-400 pointer-events-none" />
)}
</button>
}
/>
<Input
variant="bordered"
type={isRepetidaVisible ? "text" : "password"}
label="Confirmar contraseña"
placeholder="********"
isRequired
isInvalid={!!errors.contrasenaRepetida} // !! -> convierte a booleano la existencia del error en la valdadacion del input
errorMessage={errors.contrasenaRepetida?.message} // se isInvalid es true, se muestra el mensaje de error
{...register("contrasenaRepetida")}
endContent={
<button className="focus:outline-none" type="button" onClick={() => setIsRepetidaVisible(!isRepetidaVisible)} tabIndex={99}>
{isRepetidaVisible ? (
<EyeSlashFilledIcon className="text-2xl text-default-400 pointer-events-none" />
) : (
<EyeFilledIcon className="text-2xl text-default-400 pointer-events-none" />
)}
</button>
}
/>
<input type="text" className="hidden" {...register("erroresExternos")} />
{errors.erroresExternos &&
<p className="text-red-500 text-sm">{`${errors.erroresExternos.message}`}</p>
}
<Button
className="my-3 bg-blue-500 text-white rounded-md disabled:cursor-not-allowed"
isLoading={isSubmitting}
type="submit"
spinner={Spinner}
>
Confirmar
</Button>
</form>
</>
:
<>
<p className="text-green-500 text-sm">Su contraseña ha sido cambiada exitosamente.</p>
<Link className="my-3 text-blue-500 px-3 py-1" href="/" replace>
Regresar a iniciar sesión
</Link>
</>
}
</section>
</main>
</div>
)
}
export default ResetPassword; |
use super::init::{get_home_dir, init_pipeline};
use serde::Deserialize;
use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf}; // Add this line to bring the Read trait into scope
use std::process::Command;
#[derive(Debug, Deserialize)]
struct Config {
editor: String,
}
pub fn config_decode(log: bool) -> String {
let home_dir = get_home_dir();
let foio_dir = format!("{}/.foio", home_dir);
let foio_path = Path::new(&foio_dir);
if !foio_path.exists() {
init_pipeline(log);
}
let config_path = foio_path.join("config.json"); // Use Path::join to construct the file path
let mut file: fs::File = match fs::File::open(&config_path) {
Ok(file) => file,
Err(_) => {
panic!("Failed to open the config file.");
}
};
let mut config_content: String = String::new();
if let Err(_) = file.read_to_string(&mut config_content) {
panic!("Failed to read the config file.");
}
let config: Config = match serde_json::from_str(&config_content) {
Ok(config) => config,
Err(_) => {
panic!("Failed to deserialize the config file.");
}
};
return config.editor;
}
pub fn generate_foio_script(log: bool) -> String {
let script = r#"#!/bin/bash
if [ $# -eq 0 ]; then
echo "No arguments provided. Usage: $0 <your_argument>"
exit 1
fi
fileType="$1"
cd ~
cd .foio
if [ "$fileType" = "page" ]; then
file="page.md"
elif [ "$fileType" = "calendar" ]; then
file="calendar.md"
else
file="pages/$fileType.md"
fi
"#;
let editor = config_decode(log);
let file_script = format!(
r#"
if [ -e "$file" ]; then
{} "$file"
else
echo "File $file does not exist."
fi
"#,
editor
);
let combined_script = script.to_string() + &file_script;
return combined_script;
}
pub fn write_foio_script(log: bool) {
let home_dir = get_home_dir();
let foioscript = generate_foio_script(log);
let foio_dir = format!("{}/.foio", home_dir);
let foioscript_path = PathBuf::from(foio_dir).join("foioscript.sh");
if foioscript_path.exists() {
if let Err(err) = fs::write(&foioscript_path, "") {
panic!("Error truncating page.md: {:?}", err);
} else {
if log {
println!("Truncated foioscript.sh at: {:?}", foioscript_path);
}
}
if let Err(err) = fs::write(&foioscript_path, foioscript) {
panic!("Error writing the foioscript.sh {:?}", err);
} else {
if log {
println!("Created the foioscript.sh file");
}
}
} else {
// create page.md
match fs::File::create(&foioscript_path) {
Ok(_) => {
if log {
println!("created page.md at: {:?}", foioscript_path);
}
if let Err(err) = fs::write(&foioscript_path, foioscript) {
panic!("Error writing the foioscript.sh {:?}", err);
} else {
if log {
println!("Created the foioscript.sh file");
}
}
}
Err(err) => {
panic!("Error creating page.md: {:?}", err);
}
}
}
}
pub fn change_permission_to_foio_script(log: bool) {
let home_dir = get_home_dir();
let foioscript_path = format!("{}/.foio/foioscript.sh", home_dir);
let status = Command::new("chmod")
.arg("+x")
.arg(foioscript_path)
.status()
.expect("Failed to execute the chmod command");
if status.success() {
if log {
println!("Permissions changed successfully");
}
} else {
if log {
println!("Failed to change permissions");
}
}
}
pub fn setup_pipeline(log: bool) {
write_foio_script(log);
change_permission_to_foio_script(log);
} |
import { ObjectId } from 'mongoose'
import { InferGetStaticPropsType } from 'next'
import { useRouter } from 'next/router'
import type { Portfolio } from '../types'
import Layout from '@components/Layout'
import { getPortfolios } from '@helpers/getPortfolios'
import { getImageBinaryData } from '@helpers/getImageBinaryData'
import PortfolioContainer from '@components/portfolio/Portfolio'
import styles from '@styles/home.module.scss'
import db from '@config/db'
interface Image {
_id: ObjectId
image_preview_url?: string
}
type Props = InferGetStaticPropsType<typeof getServerSideProps>
const Home = ({ portfolioList }: Props) => {
const Router = useRouter()
const onClickhandler = (_id: ObjectId) => {
Router.push(`/works/${_id}/detail`)
}
return (
<Layout>
<div className={styles.section_portfolio_list}>
{portfolioList.map((portfolio) => (
<div
onClick={() => onClickhandler(portfolio._id)}
key={String(portfolio._id)}
className={styles.portfolio_wrapper_root}
>
<PortfolioContainer
_id={portfolio._id}
image_preview_url={portfolio.image_preview_url}
username={portfolio.username}
work_name={portfolio.work_name}
review_avg={portfolio.review_avg}
/>
</div>
))}
</div>
</Layout>
)
}
export const getServerSideProps = async () => {
await db.connect()
const portfolioDocuments = await getPortfolios()
const mapResult = portfolioDocuments.map((work: Portfolio) => {
return getImageBinaryData(work.image.name, work._id)
})
const getImageUrl = async () => {
const imageObj = await Promise.all(mapResult)
return imageObj as Image[]
}
const imageUrlArray = await getImageUrl()
const portfolioList = portfolioDocuments.map((portfolio: Portfolio) => {
const imageObj = imageUrlArray.find((image: Image) => {
if (portfolio._id === image._id) return image
})
if (!imageObj) {
return {
...portfolio,
image_preview_url: undefined
} as Portfolio & Image
}
return {
...portfolio,
image_preview_url: imageObj.image_preview_url
} as Portfolio & Image
})
await db.disconnect()
return {
props: {
portfolioList
}
}
}
export default Home |
""" Flask Factory
"""
import os
from flask import Flask
def create_app(test_config=None):
# Create and config the app
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SESSION_TYPE='filesystem',
SECURITY_KEY='dev',
DATABASE=os.path.join(app.instance_path, 'flask.sqlite'),
)
app.config['SECRET_KEY'] = b'_5#y2L"F4Q8z\n\xec]/'
# app.secret_key or app.security_key maybe not
#
app.config['SESSION_TYPE'] = 'filesystem'
if test_config is None:
# load the instance config, if it exists, when not testing
app.config.from_pyfile('config.py', silent=True)
else:
app.config.from_mapping(test_config)
try:
os.makedirs(app.instance_path)
except OSError:
pass
# 注册DB
from . import db
db.init_app(app)
# 注册 Blueprint
from . import auth
app.register_blueprint(auth.bp)
# Import blog blueprint
from . import blog
app.register_blueprint(blog.bp)
app.add_url_rule('/', endpoint='index')
# The 'Hello World !' Page
@app.route('/hello')
def hello():
return 'Hello, World!'
return app |
package main
import (
"bytes"
"errors"
"fmt"
"github.com/gen2brain/beeep"
"github.com/getlantern/systray"
"github.com/skratchdot/open-golang/open"
"log"
"os/exec"
"regexp"
"sopre-tray/icon"
"strings"
"time"
)
var serviceArr = [9]string{
"VCM_AP_60_QKNOWLEDGEBASESERVER",
"VCM_AP_60_QDBODBC_IS",
"VCM_AP_60_QSERVER",
"VCM_AP_60_QTCE",
"VCM_AP_60_QTCE_EDITOR",
"VCM_EP_60_QDBODBC_IS",
"VCM_EP_60_QSERVER",
"VCM_EP_60_QTCE",
"VCM_EP_60_QTCE_EDITOR",
}
type ServicesRegistry struct {
Services []Service
}
type Service struct {
ServiceName string
DisplayName string
Running bool
Group string
MenuItem *systray.MenuItem
}
var serviceRegistry ServicesRegistry
func main() {
systray.Run(onReady, onExit)
}
func onReady() {
systray.SetIcon(icon.Data)
systray.SetTitle("Sopre Windows Services")
systray.SetTooltip("Start/Stop Sopre Services")
mAll := systray.AddMenuItem("All Services", "")
mAllStart := mAll.AddSubMenuItem("Start", "")
mAllStop := mAll.AddSubMenuItem("Stop", "")
mGroup := systray.AddMenuItem("Groups", "")
mAPAll := mGroup.AddSubMenuItem("Start All AP Services", "")
mEPAll := mGroup.AddSubMenuItem("Start All EP Services", "")
systray.AddSeparator()
checkServices()
//Separator
systray.AddSeparator()
mConfluence := systray.AddMenuItem("Open Confluence", "")
//Testentry //Todo remove after, is not used
mTest := systray.AddMenuItem("Test", "")
mQuit := systray.AddMenuItem("Quit", "Quit the whole app")
go func() {
for _, v := range serviceRegistry.Services {
<-v.MenuItem.ClickedCh
fmt.Println("Clicked on ", v.DisplayName)
toggleService(v.ServiceName)
}
}()
go func() {
for {
select {
case <-mAllStart.ClickedCh:
fmt.Println("Start all SOPRE Services")
case <-mAllStop.ClickedCh:
fmt.Println("Stop all SOPRE Services")
case <-mAPAll.ClickedCh:
fmt.Println("Start all AP Services")
case <-mEPAll.ClickedCh:
fmt.Println("Start all EP Services")
case <-mConfluence.ClickedCh:
_ = open.Run("https://confluence.sbb.ch/x/TYAGZw")
case <-mTest.ClickedCh:
fmt.Println("Checking Services")
sendNotification("Test", "Running Services Check")
checkServices()
case <-mQuit.ClickedCh:
systray.Quit()
return
}
}
}()
}
func onExit() {
// clean up here
}
func checkServices() {
var sRegistry []Service
for _, v := range serviceArr {
displayName, serviceName, running, groupName := checkService(v)
log.Println("Checking Service: ", displayName, " [", serviceName, "] Running: ", running, " Group: ", groupName)
service := Service{
DisplayName: displayName,
ServiceName: serviceName,
Running: running,
Group: groupName,
MenuItem: systray.AddMenuItem(displayName, ""),
}
sRegistry = append(sRegistry, service)
}
serviceRegistry.Services = nil
serviceRegistry.Services = sRegistry
}
func checkService(servicename string) (string, string, bool, string) {
cmd := exec.Command("C:\\Windows\\System32\\sc.exe", "query", servicename)
var outb, errb bytes.Buffer
cmd.Stdout = &outb
cmd.Stderr = &errb
err := cmd.Run()
if err != nil {
log.Fatal(err)
}
displayName, groupName := getDisplayName(servicename)
serviceName, running := extractServiceNameAndState(outb.String())
return displayName, serviceName, running, groupName
}
func getDisplayName(servicename string) (string, string) {
cmd := exec.Command("C:\\Windows\\System32\\sc.exe", "getdisplayname", servicename)
var outb, errb bytes.Buffer
cmd.Stdout = &outb
cmd.Stderr = &errb
err := cmd.Run()
if err != nil {
log.Fatal(err)
}
return extractDisplayNameAndGroup(outb.String())
}
func extractDisplayNameAndGroup(out string) (string, string) {
cut := strings.Fields(out)
re2 := regexp.MustCompile(`_`)
input2 := re2.ReplaceAllString(strings.Join(cut[5:6], ""), " ")
cut2 := strings.Fields(input2)
displayName := strings.Join(cut2[3:], " ")
regroup := regexp.MustCompile(`AP|EP`)
group := regroup.FindAllString(displayName, 1)
groupString := strings.Join(group, "")
return displayName, groupString
}
func extractServiceNameAndState(out string) (string, bool) {
restate := regexp.MustCompile(".*STATE.*:.[0-9]")
state := restate.FindAllString(out, -1)
stateString := strings.Join(state, "")
stateString = strings.Replace(stateString, " ", "", -1)
stateString = strings.Replace(stateString, "STATE:", "", 1)
running := checkRunning(stateString)
reservice := regexp.MustCompile("SERVICE_NAME.*:.[_A-Z0-9]*")
service := reservice.FindAllString(out, -1)
serviceString := strings.Join(service, "")
serviceString = strings.Replace(serviceString, " ", "", -1)
serviceString = strings.Replace(serviceString, "SERVICE_NAME:", "", 1)
return serviceString, running
}
func checkRunning(running string) bool {
if running != "1" {
return true
}
return false
}
func getStateForService(serviceName string) (bool, error) {
for _, v := range serviceRegistry.Services {
if v.ServiceName == serviceName {
return v.Running, nil
}
}
return false, errors.New(fmt.Sprintf("Cannot find service for %s", serviceName))
}
func getDisplayNameForService(serviceName string) (string, error) {
for _, v := range serviceRegistry.Services {
if v.ServiceName == serviceName {
return v.DisplayName, nil
}
}
return "", errors.New(fmt.Sprintf("Cannot find service for %s", serviceName))
}
func toggleService(serviceName string) {
state, err := getStateForService(serviceName)
if err != nil {
log.Println(err)
}
if state {
stopService(serviceName)
} else {
startService(serviceName)
}
}
func startService(serviceName string) {
cmd := exec.Command("C:\\Windows\\System32\\net.exe", "start", serviceName)
err := cmd.Start()
if err != nil {
fmt.Println("About to fail")
log.Fatal(err)
}
for true {
_, _, state, _ := checkService(serviceName)
fmt.Println(state)
if state {
break
}
_ = updateServiceState(serviceName, state)
time.Sleep(2 * time.Second)
}
displayName, _ := getDisplayNameForService(serviceName)
sendNotification("Service Started", fmt.Sprintf("Succesfully started %s", displayName))
}
func stopService(serviceName string) {
cmd := exec.Command("C:\\Windows\\System32\\sc.exe", "stop", serviceName)
err := cmd.Run()
if err != nil {
log.Fatal(err)
}
for true {
_, _, state, _ := checkService(serviceName)
fmt.Println(state)
if !state {
break
}
_ = updateServiceState(serviceName, state)
time.Sleep(2 * time.Second)
}
displayName, _ := getDisplayNameForService(serviceName)
sendNotification("Stopping Service", fmt.Sprintf("Stopping %s", displayName))
}
func updateServiceState(serviceName string, running bool) error {
for _, v := range serviceRegistry.Services {
if v.ServiceName == serviceName {
v.Running = running
return nil
}
}
return errors.New(fmt.Sprintf("Cannot find service for %s", serviceName))
}
func sendNotification(title string, text string) {
err := beeep.Notify(title, text, "icon/icon.png")
if err != nil {
panic(err)
}
} |
#ifndef PJC_CLION_C09_H
#define PJC_CLION_C09_H
#include <iostream>
#include <ostream>
#include <string>
#include <vector>
//ZADANIE 1
template <typename E>
class MyStack {
public:
class Node {
public:
E data;
Node* next;
Node(const E& d): data(d), next(nullptr) {}
};
private:
Node* head;
public:
MyStack(): head(nullptr) {};
void push(const E& d) {
Node* newNode = new Node(d);
newNode->next = head;
head = newNode;
}
E pop() {
E data = head->data;
Node *temp = head->next;
delete head;
head = temp;
return data;
}
bool isEmpty() const {
return head == nullptr;
}
virtual ~MyStack() {
while (!isEmpty()) {
pop();
}
}
};
//ZADANIE 2
class Resistor {
double R;
public:
Resistor();
Resistor(double r);
double r() const;
void r(double r);
friend std::ostream& operator<<(std::ostream&, const Resistor&);
};
//ZADANIE 3
class Person {
static size_t ID;
std::string name;
size_t id;
std::vector<const Person*> friends;
public:
Person(std::string name);
void makeFriends(Person& p);
void listOfFriends() const;
std::vector<const Person*> friendsOfFriends() const;
std::string info() const;
};
#endif //PJC_CLION_C09_H |
import { Fragment, useState} from 'react'
import { Dialog, Transition } from '@headlessui/react'
import {
AcademicCapIcon,
Bars3Icon,
BellIcon,
ChartPieIcon,
Cog6ToothIcon,
FolderIcon,
HomeIcon,
XMarkIcon,
} from '@heroicons/react/24/outline'
import { MagnifyingGlassIcon } from '@heroicons/react/20/solid'
import { SignInButton, UserButton, useUser } from "@clerk/nextjs";
import { useRouter } from 'next/router';
import Image from 'next/image'
interface DashboardLayoutProps {
children: React.ReactNode
}
function classNames(...classes: (string | boolean | undefined)[]): string {
return classes.filter(Boolean).join(' ')
}
export default function DashboardLayout({ children }: DashboardLayoutProps) {
const [sidebarOpen, setSidebarOpen] = useState(false)
const user = useUser();
const router = useRouter();
const navigation = [
{ name: 'Dashboard', href: '/dashboard', icon: HomeIcon, current: router.pathname === '/dashboard' },
{ name: 'Order-flow', href: '/dashboard/order-flow', icon: AcademicCapIcon, current: router.pathname === '/dashboard/order-flow' },
{ name: 'Statistics', href: '/dashboard/statistics', icon: ChartPieIcon, current: router.pathname === '/dashboard/statistics' },
{ name: 'Research', href: '/dashboard/research', icon: FolderIcon, current: router.pathname === '/dashboard/research' },
];
const teams = [
{ id: 1, name: 'Documentation', href: '#', initial: 'H', current: false },
{ id: 2, name: 'API', href: '#', initial: 'T', current: false },
]
const settingsNavigation = [
{ name: 'Settings', href: '/dashboard/settings', icon: Cog6ToothIcon, current: router.pathname === '/dashboard/settings' },
]
return (
<>
{}
<div>
<Transition.Root show={sidebarOpen} as={Fragment}>
<Dialog as="div" className="relative z-50 lg:hidden" onClose={setSidebarOpen}>
<Transition.Child
as={Fragment}
enter="transition-opacity ease-linear duration-300"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="transition-opacity ease-linear duration-300"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-gray-900/80" />
</Transition.Child>
<div className="fixed inset-0 flex">
<Transition.Child
as={Fragment}
enter="transition ease-in-out duration-300 transform"
enterFrom="-translate-x-full"
enterTo="translate-x-0"
leave="transition ease-in-out duration-300 transform"
leaveFrom="translate-x-0"
leaveTo="-translate-x-full"
>
<Dialog.Panel className="relative mr-16 flex w-full max-w-xs flex-1">
<Transition.Child
as={Fragment}
enter="ease-in-out duration-300"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in-out duration-300"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="absolute left-full top-0 flex w-16 justify-center pt-5">
<button type="button" className="-m-2.5 p-2.5" onClick={() => setSidebarOpen(false)}>
<span className="sr-only">Close sidebar</span>
<XMarkIcon className="h-6 w-6 text-white" aria-hidden="true" />
</button>
</div>
</Transition.Child>
{/* Sidebar component, swap this element with another sidebar if you like */}
<div className="flex grow flex-col gap-y-5 overflow-y-auto bg-white px-6 pb-4">
<div className="flex h-16 shrink-0 items-center">
<Image
className="h-8 w-auto"
width={32}
height={32}
src="https://tailwindui.com/img/logos/mark.svg?color=indigo&shade=600"
alt="Your Company"
/>
</div>
<nav className="flex flex-1 flex-col">
<ul role="list" className="flex flex-1 flex-col gap-y-7">
<li>
<ul role="list" className="-mx-2 space-y-1">
{navigation.map((item) => (
<li key={item.name}>
<a
href={item.href}
className={classNames(
item.current
? 'bg-gray-50 text-indigo-600'
: 'text-gray-700 hover:text-indigo-600 hover:bg-gray-50',
'group flex gap-x-3 rounded-md p-2 text-sm leading-6 font-semibold'
)}
>
<item.icon
className={classNames(
item.current ? 'text-indigo-600' : 'text-gray-400 group-hover:text-indigo-600',
'h-6 w-6 shrink-0'
)}
aria-hidden="true"
/>
{item.name}
</a>
</li>
))}
</ul>
</li>
<li>
<div className="text-xs font-semibold leading-6 text-gray-400">Other</div>
<ul role="list" className="-mx-2 mt-2 space-y-1">
{teams.map((team) => (
<li key={team.name}>
<a
href={team.href}
className={classNames(
team.current
? 'bg-gray-50 text-indigo-600'
: 'text-gray-700 hover:text-indigo-600 hover:bg-gray-50',
'group flex gap-x-3 rounded-md p-2 text-sm leading-6 font-semibold'
)}
>
<span
className={classNames(
team.current
? 'text-indigo-600 border-indigo-600'
: 'text-gray-400 border-gray-200 group-hover:border-indigo-600 group-hover:text-indigo-600',
'flex h-6 w-6 shrink-0 items-center justify-center rounded-lg border text-[0.625rem] font-medium bg-white'
)}
>
{team.initial}
</span>
<span className="truncate">{team.name}</span>
</a>
</li>
))}
</ul>
</li>
<li className="mt-auto">
<ul role="list" className="-mx-2 space-y-1">
{settingsNavigation.map((item) => (
<li key={item.name}>
<a
href={item.href}
className={classNames(
item.current
? 'bg-gray-50 text-indigo-600'
: 'text-gray-700 hover:text-indigo-600 hover:bg-gray-50',
'group flex gap-x-3 rounded-md p-2 text-sm leading-6 font-semibold'
)}
>
<item.icon
className={classNames(
item.current ? 'text-indigo-600' : 'text-gray-400 group-hover:text-indigo-600',
'h-6 w-6 shrink-0'
)}
aria-hidden="true"
/>
{item.name}
</a>
</li>
))}
</ul>
</li>
</ul>
</nav>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</Dialog>
</Transition.Root>
{/* Static sidebar for desktop */}
<div className="hidden lg:fixed lg:inset-y-0 lg:z-50 lg:flex lg:w-56 lg:flex-col">
{/* Sidebar component, swap this element with another sidebar if you like */}
<div className="flex grow flex-col gap-y-5 overflow-y-auto border-r border-gray-200 bg-white px-6 pb-4">
<div className="flex h-16 shrink-0 items-center">
<Image
className="h-8 w-auto"
width={32}
height={32}
src="https://tailwindui.com/img/logos/mark.svg?color=indigo&shade=600"
alt="Your Company"
/>
</div>
<nav className="flex flex-1 flex-col">
<ul role="list" className="flex flex-1 flex-col gap-y-7">
<li>
<ul role="list" className="-mx-2 space-y-1">
{navigation.map((item) => (
<li key={item.name}>
<a
href={item.href}
className={classNames(
item.current
? 'bg-gray-50 text-indigo-600'
: 'text-gray-700 hover:text-indigo-600 hover:bg-gray-50',
'group flex gap-x-3 rounded-md p-2 text-sm leading-6 font-semibold'
)}
>
<item.icon
className={classNames(
item.current ? 'text-indigo-600' : 'text-gray-400 group-hover:text-indigo-600',
'h-6 w-6 shrink-0'
)}
aria-hidden="true"
/>
{item.name}
</a>
</li>
))}
</ul>
</li>
<li>
<div className="text-xs font-semibold leading-6 text-gray-400">Other</div>
<ul role="list" className="-mx-2 mt-2 space-y-1">
{teams.map((team) => (
<li key={team.name}>
<a
href={team.href}
className={classNames(
team.current
? 'bg-gray-50 text-indigo-600'
: 'text-gray-700 hover:text-indigo-600 hover:bg-gray-50',
'group flex gap-x-3 rounded-md p-2 text-sm leading-6 font-semibold'
)}
>
<span
className={classNames(
team.current
? 'text-indigo-600 border-indigo-600'
: 'text-gray-400 border-gray-200 group-hover:border-indigo-600 group-hover:text-indigo-600',
'flex h-6 w-6 shrink-0 items-center justify-center rounded-lg border text-[0.625rem] font-medium bg-white'
)}
>
{team.initial}
</span>
<span className="truncate">{team.name}</span>
</a>
</li>
))}
</ul>
</li>
<li className="mt-auto">
<ul role="list" className="-mx-2 space-y-1">
{settingsNavigation.map((item) => (
<li key={item.name}>
<a
href={item.href}
className={classNames(
item.current
? 'bg-gray-50 text-indigo-600'
: 'text-gray-700 hover:text-indigo-600 hover:bg-gray-50',
'group flex gap-x-3 rounded-md p-2 text-sm leading-6 font-semibold'
)}
>
<item.icon
className={classNames(
item.current ? 'text-indigo-600' : 'text-gray-400 group-hover:text-indigo-600',
'h-6 w-6 shrink-0'
)}
aria-hidden="true"
/>
{item.name}
</a>
</li>
))}
</ul>
</li>
</ul>
</nav>
</div>
</div>
<div className="lg:pl-56">
<div className="sticky top-0 z-40 flex h-14 shrink-0 items-center gap-x-4 border-b border-gray-200 bg-white px-4 shadow-sm sm:gap-x-6 sm:px-6 lg:px-8">
<button type="button" className="-m-2.5 p-2.5 text-gray-700 lg:hidden" onClick={() => setSidebarOpen(true)}>
<span className="sr-only">Open sidebar</span>
<Bars3Icon className="h-6 w-6" aria-hidden="true" />
</button>
{/* Separator */}
<div className="h-6 w-px bg-gray-200 lg:hidden" aria-hidden="true" />
<div className="flex flex-1 gap-x-4 self-stretch lg:gap-x-6">
<form className="relative flex flex-1" action="#" method="GET">
<label htmlFor="search-field" className="sr-only">
Search
</label>
<MagnifyingGlassIcon
className="pointer-events-none absolute inset-y-0 left-0 h-full w-5 text-gray-400"
aria-hidden="true"
/>
<input
id="search-field"
className="block h-full w-full border-0 py-0 pl-8 pr-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm"
placeholder="Search..."
type="search"
name="search"
/>
</form>
<div className="flex items-center gap-x-4 lg:gap-x-8">
<button type="button" className="-m-2.5 p-2.5 text-gray-400 hover:text-gray-500">
<span className="sr-only">View notifications</span>
<BellIcon className="h-6 w-6" aria-hidden="true" />
</button>
{/* Separator */}
<div className="hidden lg:block lg:h-6 lg:w-px lg:bg-gray-200" aria-hidden="true" />
{/* Profile dropdown */}
<div>
{!user.isSignedIn && (
<SignInButton mode="modal">
<button
type="button"
className="rounded-md bg-indigo-600 px-2.5 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
>
Sign In
</button>
</SignInButton>
)}
{!!user.isSignedIn && <UserButton />}
</div>
</div>
</div>
</div>
<main className="py-10">
<div className="px-4 sm:px-6 lg:px-8">{children}</div>
</main>
</div>
</div>
</>
)
} |
/*
Copyright 2022 The Flux 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
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package summarize
import (
"context"
corev1 "k8s.io/api/core/v1"
kuberecorder "k8s.io/client-go/tools/record"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
eventv1 "github.com/fluxcd/pkg/apis/event/v1beta1"
"github.com/fluxcd/pkg/apis/meta"
serror "github.com/fluxcd/source-controller/internal/error"
"github.com/fluxcd/source-controller/internal/object"
"github.com/fluxcd/source-controller/internal/reconcile"
)
// ResultProcessor processes the results of reconciliation (the object, result
// and error). Any errors during processing need not result in the
// reconciliation failure. The errors can be recorded as logs and events.
type ResultProcessor func(context.Context, kuberecorder.EventRecorder, client.Object, reconcile.Result, error)
// RecordContextualError is a ResultProcessor that records the contextual errors
// based on their types.
// An event is recorded for the errors that are returned to the runtime. The
// runtime handles the logging of the error.
// An event is recorded and an error is logged for errors that are known to be
// swallowed, not returned to the runtime.
func RecordContextualError(ctx context.Context, recorder kuberecorder.EventRecorder, obj client.Object, _ reconcile.Result, err error) {
switch e := err.(type) {
case *serror.Event:
recorder.Eventf(obj, corev1.EventTypeWarning, e.Reason, e.Error())
case *serror.Waiting:
// Waiting errors are not returned to the runtime. Log it explicitly.
ctrl.LoggerFrom(ctx).Info("reconciliation waiting", "reason", e.Err, "duration", e.RequeueAfter)
recorder.Event(obj, corev1.EventTypeNormal, e.Reason, e.Error())
case *serror.Stalling:
// Stalling errors are not returned to the runtime. Log it explicitly.
ctrl.LoggerFrom(ctx).Error(e, "reconciliation stalled")
recorder.Eventf(obj, corev1.EventTypeWarning, e.Reason, e.Error())
}
}
// RecordReconcileReq is a ResultProcessor that checks the reconcile
// annotation value and sets it in the object status as
// status.lastHandledReconcileAt.
func RecordReconcileReq(ctx context.Context, recorder kuberecorder.EventRecorder, obj client.Object, _ reconcile.Result, _ error) {
if v, ok := meta.ReconcileAnnotationValue(obj.GetAnnotations()); ok {
object.SetStatusLastHandledReconcileAt(obj, v)
}
}
// ErrorActionHandler is a ResultProcessor that handles all the actions
// configured in the given error. Logging and event recording are the handled
// actions at present. As more configurations are added to serror.Config, more
// action handlers can be added here.
func ErrorActionHandler(ctx context.Context, recorder kuberecorder.EventRecorder, obj client.Object, _ reconcile.Result, err error) {
switch e := err.(type) {
case *serror.Generic:
if e.Log {
logError(ctx, e.Config.Event, e, e.Error())
}
recordEvent(recorder, obj, e.Config.Event, e.Config.Notification, err, e.Reason)
case *serror.Waiting:
if e.Log {
logError(ctx, e.Config.Event, e, "reconciliation waiting", "reason", e.Err, "duration", e.RequeueAfter)
}
recordEvent(recorder, obj, e.Config.Event, e.Config.Notification, err, e.Reason)
case *serror.Stalling:
if e.Log {
logError(ctx, e.Config.Event, e, "reconciliation stalled")
}
recordEvent(recorder, obj, e.Config.Event, e.Config.Notification, err, e.Reason)
}
}
// logError logs error based on the passed error configurations.
func logError(ctx context.Context, eventType string, err error, msg string, keysAndValues ...interface{}) {
switch eventType {
case corev1.EventTypeNormal, serror.EventTypeNone:
ctrl.LoggerFrom(ctx).Info(msg, keysAndValues...)
case corev1.EventTypeWarning:
ctrl.LoggerFrom(ctx).Error(err, msg, keysAndValues...)
}
}
// recordEvent records events based on the passed error configurations.
func recordEvent(recorder kuberecorder.EventRecorder, obj client.Object, eventType string, notification bool, err error, reason string) {
if eventType == serror.EventTypeNone {
return
}
switch eventType {
case corev1.EventTypeNormal:
if notification {
// K8s native event and notification-controller event.
recorder.Eventf(obj, corev1.EventTypeNormal, reason, err.Error())
} else {
// K8s native event only.
recorder.Eventf(obj, eventv1.EventTypeTrace, reason, err.Error())
}
case corev1.EventTypeWarning:
// TODO: Due to the current implementation of the event recorder, all
// the K8s warning events are also sent as notification controller
// notifications. Once the recorder becomes capable of separating the
// two, conditionally record events.
recorder.Eventf(obj, corev1.EventTypeWarning, reason, err.Error())
}
} |
/****************************************************************************
Copyright (c) 2013 cocos2d-x.org
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
https://axmolengine.github.io/
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.
****************************************************************************/
#ifndef __AssetsManagerEx__
#define __AssetsManagerEx__
#include <string>
#include <unordered_map>
#include <vector>
#include "base/EventDispatcher.h"
#include "platform/FileUtils.h"
#include "network/Downloader.h"
#include "EventAssetsManagerEx.h"
#include "Manifest.h"
#include "extensions/ExtensionMacros.h"
#include "extensions/ExtensionExport.h"
#include "rapidjson/document-wrapper.h"
struct zlib_filefunc_def_s;
NS_AX_EXT_BEGIN
/**
* @brief This class is used to auto update resources, such as pictures or scripts.
*/
class AX_EX_DLL AssetsManagerEx : public Ref
{
public:
//! Update states
enum class State
{
UNCHECKED,
PREDOWNLOAD_VERSION,
DOWNLOADING_VERSION,
VERSION_LOADED,
PREDOWNLOAD_MANIFEST,
DOWNLOADING_MANIFEST,
MANIFEST_LOADED,
NEED_UPDATE,
UPDATING,
UNZIPPING,
UP_TO_DATE,
FAIL_TO_UPDATE
};
const static std::string VERSION_ID;
const static std::string MANIFEST_ID;
/** @brief Create function for creating a new AssetsManagerEx
@param manifestUrl The url for the local manifest file
@param storagePath The storage path for downloaded assets
@warning The cached manifest in your storage path have higher priority and will be searched first,
only if it doesn't exist, AssetsManagerEx will use the given manifestUrl.
*/
static AssetsManagerEx* create(std::string_view manifestUrl, std::string_view storagePath);
/** @brief Check out if there is a new version of manifest.
* You may use this method before updating, then let user determine whether
* he wants to update resources.
*/
void checkUpdate();
/** @brief Update with the current local manifest.
*/
void update();
/** @brief Reupdate all failed assets under the current AssetsManagerEx context
*/
void downloadFailedAssets();
/** @brief Gets the current update state.
*/
State getState() const;
/** @brief Gets storage path.
*/
std::string_view getStoragePath() const;
/** @brief Function for retrieving the local manifest object
*/
const Manifest* getLocalManifest() const;
/** @brief Function for retrieving the remote manifest object
*/
const Manifest* getRemoteManifest() const;
/** @brief Function for retrieving the max concurrent task count
*/
const int getMaxConcurrentTask() const { return _maxConcurrentTask; };
/** @brief Function for setting the max concurrent task count
*/
void setMaxConcurrentTask(const int max) { _maxConcurrentTask = max; };
/** @brief Set the handle function for comparing manifests versions
* @param handle The compare function
*/
void setVersionCompareHandle(const std::function<int(std::string_view versionA, std::string_view versionB)>& handle)
{
_versionCompareHandle = handle;
};
/** @brief Set the verification function for checking whether downloaded asset is correct, e.g. using md5
* verification
* @param callback The verify callback function
*/
void setVerifyCallback(const std::function<bool(std::string_view path, Manifest::Asset asset)>& callback)
{
_verifyCallback = callback;
};
AssetsManagerEx(std::string_view manifestUrl, std::string_view storagePath);
virtual ~AssetsManagerEx();
protected:
std::string_view basename(std::string_view path) const;
std::string get(std::string_view key) const;
void initManifests(std::string_view manifestUrl);
void loadLocalManifest(std::string_view manifestUrl);
void prepareLocalManifest();
void setStoragePath(std::string_view storagePath);
void adjustPath(std::string& path);
void dispatchUpdateEvent(EventAssetsManagerEx::EventCode code,
std::string_view message = "",
std::string_view assetId = "",
int curle_code = 0,
int curlm_code = 0);
void downloadVersion();
void parseVersion();
void downloadManifest();
void parseManifest();
void startUpdate();
void updateSucceed();
bool decompress(std::string_view filename);
void decompressDownloadedZip(std::string_view customId, std::string_view storagePath);
/** @brief Update a list of assets under the current AssetsManagerEx context
*/
void updateAssets(const DownloadUnits& assets);
/** @brief Retrieve all failed assets during the last update
*/
const DownloadUnits& getFailedAssets() const;
/** @brief Function for destroying the downloaded version file and manifest file
*/
void destroyDownloadedVersion();
/** @brief Download items in queue with max concurrency setting
*/
void queueDowload();
void fileError(std::string_view identifier,
std::string_view errorStr,
int errorCode = 0,
int errorCodeInternal = 0);
void fileSuccess(std::string_view customId, std::string_view storagePath);
/** @brief Call back function for error handling,
the error will then be reported to user's listener registed in addUpdateEventListener
@param error The error object contains ErrorCode, message, asset url, asset key
@warning AssetsManagerEx internal use only
* @js NA
* @lua NA
*/
virtual void onError(const network::DownloadTask& task,
int errorCode,
int errorCodeInternal,
std::string_view errorStr);
/** @brief Call back function for recording downloading percent of the current asset,
the progression will then be reported to user's listener registed in addUpdateProgressEventListener
@param total Total size to download for this asset
@param downloaded Total size already downloaded for this asset
@param url The url of this asset
@param customId The key of this asset
@warning AssetsManagerEx internal use only
* @js NA
* @lua NA
*/
virtual void onProgress(double total, double downloaded, std::string_view url, std::string_view customId);
/** @brief Call back function for success of the current asset
the success event will then be send to user's listener registed in addUpdateEventListener
@param srcUrl The url of this asset
@param customId The key of this asset
@warning AssetsManagerEx internal use only
* @js NA
* @lua NA
*/
virtual void onSuccess(std::string_view srcUrl, std::string_view storagePath, std::string_view customId);
private:
void batchDownload();
// Called when one DownloadUnits finished
void onDownloadUnitsFinished();
void fillZipFunctionOverrides(zlib_filefunc_def_s& zipFunctionOverrides);
//! The event of the current AssetsManagerEx in event dispatcher
std::string _eventName;
//! Reference to the global event dispatcher
EventDispatcher* _eventDispatcher;
//! Reference to the global file utils
FileUtils* _fileUtils;
//! State of update
State _updateState = State::UNCHECKED;
//! Downloader
std::shared_ptr<network::Downloader> _downloader;
//! The reference to the local assets
const hlookup::string_map<Manifest::Asset>* _assets = nullptr;
//! The path to store successfully downloaded version.
std::string _storagePath;
//! The path to store downloading version.
std::string _tempStoragePath;
//! The local path of cached temporary version file
std::string _tempVersionPath;
//! The local path of cached manifest file
std::string _cacheManifestPath;
//! The local path of cached temporary manifest file
std::string _tempManifestPath;
//! The path of local manifest file
std::string _manifestUrl;
//! Local manifest
Manifest* _localManifest = nullptr;
//! Local temporary manifest for download resuming
Manifest* _tempManifest = nullptr;
//! Remote manifest
Manifest* _remoteManifest = nullptr;
//! Whether user have requested to update
enum class UpdateEntry : char
{
NONE,
CHECK_UPDATE,
DO_UPDATE
};
UpdateEntry _updateEntry = UpdateEntry::NONE;
//! All assets unit to download
DownloadUnits _downloadUnits;
//! All failed units
DownloadUnits _failedUnits;
//! Download queue
std::vector<std::string> _queue;
//! Max concurrent task count for downloading
int _maxConcurrentTask = 32;
//! Current concurrent task count
int _currConcurrentTask = 0;
//! Download percent
float _percent = 0.f;
//! Download percent by file
float _percentByFile = 0.f;
//! Indicate whether the total size should be enabled
int _totalEnabled;
//! Indicate the number of file whose total size have been collected
int _sizeCollected;
//! Total file size need to be downloaded (sum of all file)
double _totalSize;
//! Downloaded size for each file
hlookup::string_map<double> _downloadedSize;
//! Total number of assets to download
int _totalToDownload = 0;
//! Total number of assets still waiting to be downloaded
int _totalWaitToDownload = 0;
//! Next target percent for saving the manifest file
float _nextSavePoint = 0.f;
//! Handle function to compare versions between different manifests
std::function<int(std::string_view versionA, std::string_view versionB)> _versionCompareHandle = nullptr;
//! Callback function to verify the downloaded assets
std::function<bool(std::string_view path, Manifest::Asset asset)> _verifyCallback = nullptr;
//! Marker for whether the assets manager is inited
bool _inited = false;
};
NS_AX_EXT_END
#endif /* defined(__AssetsManagerEx__) */ |
function [J, grad] = costFunction(theta, X, y)
%COSTFUNCTION Compute cost and gradient for logistic regression
% J = COSTFUNCTION(theta, X, y) computes the cost of using theta as the
% parameter for logistic regression and the gradient of the cost
% w.r.t. to the parameters.
% Initialize some useful values
m = length(y); % number of training examples
% You need to return the following variables correctly
J = 0;
grad = zeros(size(theta));
% Instructions: Compute the cost of a particular choice of theta.
% You should set J to the cost.
% Compute the partial derivatives and set grad to the partial
% derivatives of the cost w.r.t. each parameter in theta
%
% Note: grad should have the same dimensions as theta
%
% logistic regression hypothesis
hyp = sigmoid(X * theta);
% cost summation terms
term1 = (-y' * log(hyp));
term2 = (-(1-y)' * log(1 - hyp));
% cost function
J = (term1 + term2) / m;
% cost gradient terms
diff = (hyp - y);
% gradient calc
grad = (diff' * X) / m;
end |
var EditableTable = function () {
return {
//main function to initiate the module
init: function () {
function restoreRow(oTable, nRow) {
var aData = oTable.fnGetData(nRow);
var jqTds = $('>td', nRow);
for (var i = 0, iLen = jqTds.length; i < iLen; i++) {
oTable.fnUpdate(aData[i], nRow, i, false);
}
oTable.fnDraw();
}
function editRow(oTable, nRow) {
var aData = oTable.fnGetData(nRow);
var jqTds = $('>td', nRow);
var jqTdsLength = jqTds.length;
for(var index = 0; index < jqTdsLength - 2; index ++) {
jqTds[index].innerHTML = '<input type="text" class="form-control small" value="' + aData[index] + '">';
}
jqTds[jqTdsLength - 2].innerHTML = '<a class="edit orange-color" href="">Confirmar</a>';
jqTds[jqTdsLength - 1].innerHTML = '<a class="cancel orange-color" href="">Cancelar</a>';
}
function saveRow(oTable, nRow) {
var jqInputs = $('input:visible', nRow);
var jqInputsLength = jqInputs.length;
for(var index = 0; index < jqInputsLength; index ++) {
oTable.fnUpdate(jqInputs[index].value, nRow, index, false);
}
oTable.fnUpdate('<a class="edit orange-color" href="">Editar</a>', nRow, jqInputsLength, false);
oTable.fnUpdate('<a class="delete orange-color" href="">Deletar</a>', nRow, jqInputsLength + 1, false);
oTable.fnDraw();
}
function cancelEditRow(oTable, nRow) {
var jqInputs = $('input:visible', nRow);
var jqInputsLength = jqInputs.length;
for(var index = 0; index < jqInputsLength; index ++) {
var $input = $(jqInputs[index]);
if($input.attr('type') == 'password') {
oTable.fnUpdate($input, nRow, index, false);
}
else {
oTable.fnUpdate(jqInputs[index].value, nRow, index, false);
}
}
oTable.fnUpdate('<a class="edit orange-color" href="">Editar</a>', nRow, jqInputsLength, false);
oTable.fnUpdate('<a class="delete orange-color" href="">Deletar</a>', nRow, jqInputsLength + 1, false);
oTable.fnDraw();
}
var oTable = $('#editable-sample').dataTable({
"aLengthMenu": [
[5, 15, 20, -1],
[5, 15, 20, "Todos"] // change per page values here
],
// set the initial value
"iDisplayLength": 5,
"sDom": "<'row'<'col-lg-6'l><'col-lg-6'f>r>t<'row'<'col-lg-6'i><'col-lg-6'p>>",
"sPaginationType": "bootstrap",
"oLanguage": {
"sLengthMenu": "_MENU_ registros por página",
"oPaginate": {
"sPrevious": "Anterior",
"sNext": "Próximo"
}
},
"aoColumnDefs": [{
'bSortable': false,
'aTargets': [0]
}
]
});
jQuery('#editable-sample_wrapper .dataTables_filter input').addClass("form-control medium"); // modify table search input
jQuery('#editable-sample_wrapper .dataTables_length select').addClass("form-control xsmall"); // modify table per page dropdown
var nEditing = null;
$(document).on('click', '#editable-sample_new', function(e){
e.preventDefault();
var dataLength = $('th').length - 2;
var array = [];
for(var index = 0; index < dataLength; index++)
array.push('');
array.push('<a class="cancel orange-color" data-mode="new" href="">Cancelar</a>');
var aiNew = oTable.fnAddData(array);
var nRow = oTable.fnGetNodes(aiNew[0]);
editRow(oTable, nRow);
nEditing = nRow;
});
$(document).on('click', '#editable-sample a.delete', function(e){
e.preventDefault();
var nRow = $(this).parents('tr')[0];
oTable.fnDeleteRow(nRow);
});
$(document).on('click', '#editable-sample a.cancel', function(e){
e.preventDefault();
if ($(this).attr("data-mode") == "new") {
var nRow = $(this).parents('tr')[0];
oTable.fnDeleteRow(nRow);
} else {
restoreRow(oTable, nEditing);
nEditing = null;
}
});
$(document).on('click', '#editable-sample a.edit', function(e){
e.preventDefault();
/* Get the row as a parent of the link that was clicked on */
var nRow = $(this).parents('tr')[0];
if (nEditing !== null && nEditing != nRow && this.innerHTML != "Confirmar") {
/* Currently editing - but not this row - restore the old before continuing to edit mode */
restoreRow(oTable, nEditing);
editRow(oTable, nRow);
nEditing = nRow;
} else if (nEditing == nRow && this.innerHTML == "Confirmar") {
/* Editing this row and want to save it */
saveRow(oTable, nEditing);
nEditing = null;
} else {
/* No edit in progress - let's start one */
editRow(oTable, nRow);
nEditing = nRow;
}
});
}
};
}(); |
import { Injectable } from '@angular/core';
import { BodyPart } from '../enums/BodyPart.enum';
import { Measurement } from '../models/measurement.model';
@Injectable({
providedIn: 'root'
})
export class ChartService {
constructor() { }
bodyParts = Object.assign({},BodyPart);
getTranslatedBodypart(bodyPart:string) {
const requiredBodyPart = bodyPart?.substring(0,1).toUpperCase() + bodyPart?.substring(1,bodyPart.length);
return this.bodyParts[requiredBodyPart];
}
filterMeasurements(measurements:Measurement[],bodyPart:string) {
const measurementSeries:any[][] = [];
const prop = bodyPart.toLowerCase().toString();
switch (prop) {
case 'arms':
const leftArms = this.extractMeasurement('leftArm',measurements);
const rightArms = this.extractMeasurement('rightArm',measurements);
measurementSeries.push(leftArms,rightArms);
break;
case 'forearms':
const leftForearms = this.extractMeasurement('leftForearm',measurements);
const rightForearms = this.extractMeasurement('rightForearm',measurements);
measurementSeries.push(leftForearms,rightForearms);
break;
case 'thighs':
const leftThighs = this.extractMeasurement('leftThigh',measurements);
const rightThighs = this.extractMeasurement('rightThigh',measurements);
measurementSeries.push(leftThighs,rightThighs);
break;
case 'calves':
const leftCalves = this.extractMeasurement('leftCalf',measurements);
const rightCalves = this.extractMeasurement('rightCalf',measurements);
measurementSeries.push(leftCalves,rightCalves);
break;
default:
const otherMeasurements = this.extractMeasurement(prop,measurements);
measurementSeries.push(otherMeasurements);
break;
}
return measurementSeries.filter(arr => arr.length > 0);
}
private extractMeasurement(bodyPart:string,measurements:any[]) {
return measurements
.map(m => {
if(m[bodyPart] && m[bodyPart] !== null){
return {
name:bodyPart,
value:m[bodyPart],
dateOfMeasurement:m.dateOfMeasurement,
}
}
return null;
})
.filter(m => m!== null);
}
getChartOptions(data:any):Highcharts.Options {
return {
title: {
text: '',
},
subtitle: {
text: '',
},
yAxis: {
title: {
text: '',
},
},
xAxis: {
visible: false,
},
plotOptions: {
series: {
label: {
connectorAllowed: false,
},
},
},
colors:['#8bbc21', '#f28f43'],
series: [
...data.measurements.map(m=> {
return {
name: this.getTranslatedBodypart(m[0].name.toLowerCase()),
type: 'line',
data: m.map((v) => {
return {
y: v.value,
desc: v.dateOfMeasurement,
};
}),
showInLegend: false,
}
})
],
tooltip: {
formatter: function () {
//@ts-ignore
var s ='<b>' + this.point.desc + ' ' + '/' + ' ' + `${this.series?.name}: ` + this.point.y + '</b>';
return s;
},
style:{
fontSize:'13px',
height:50,
color:'white'
},
backgroundColor:'midnightblue'
},
credits: {
enabled: false,
},
chart: {},
responsive: {
rules: [
{
condition: {
maxWidth: 500,
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom',
},
},
},
],
},
};
}
} |
# ValloxMV Binding
This binding is designed to connect to the web interface of Vallox MV series of ventilation unit.
It has been tested so far only with Vallox 350 MV and 510 MV.
## Supported Things
There is one thing (valloxmv) supporting the connection via the web interface of the Vallox MV. There is NO support of former modbus connected devices.
## Discovery
This binding does not support any discovery, IP address has to be provided.
## Thing Configuration
The Thing needs the information at which IP the web interface could be reached and how often the values should be updated.
Minimum update interval is limited to 15 sec in order to avoid polling again before results have been evaluated.
| Config | Description | Type | Default |
| :-------------------- |:------------------------------------------------------|:-----:|:-------:|
| ip | IP address of web interface |string | n/a |
| updateinterval | Interval in seconds in which the interface is polled |int | 60 |
## Channels
Overview of provided channels
| Channel ID | Vallox Name | Description | Read/Write | Values |
| :------------------------- | :--------------------------- |:-----------------------------------|:-:|:----------------------:|
| onoff | A_CYC_MODE | On off switch |rw| On/Off |
| state | _several_ | Current state of ventilation unit |rw| 1=FIREPLACE, 2=AWAY, 3=ATHOME, 4=BOOST |
| fanspeed | A_CYC_FAN_SPEED | Fan speed |r| 0 - 100 (%) |
| fanspeedextract | A_CYC_EXTR_FAN_SPEED | Fan speed of extracting fan |r| 1/min |
| fanspeedsupply | A_CYC_SUPP_FAN_SPEED | Fan speed of supplying fan |r| 1/min |
| tempinside | A_CYC_TEMP_EXTRACT_AIR | Extracted air temp |r| Number (°C) |
| tempoutside | A_CYC_TEMP_OUTDOOR_AIR | Outside air temp |r| Number (°C) |
| tempexhaust | A_CYC_TEMP_EXHAUST_AIR | Exhausted air temp |r| Number (°C) |
| tempincomingbeforeheating | A_CYC_TEMP_SUPPLY_CELL_AIR | Incoming air temp (pre heating) |r| Number (°C) |
| tempincoming | A_CYC_TEMP_SUPPLY_AIR | Incoming air temp |r| Number (°C) |
| humidity | A_CYC_RH_VALUE | Extracted air humidity |r| 0 - 100 (%) |
| cellstate | A_CYC_CELL_STATE | Current cell state |r| 0=heat recovery, 1=cool recovery, 2=bypass, 3=defrosting |
| uptimeyears | A_CYC_TOTAL_UP_TIME_YEARS | Total uptime years |r| Y |
| uptimehours | A_CYC_TOTAL_UP_TIME_HOURS | Total uptime hours |r| h |
| uptimehourscurrent | A_CYC_CURRENT_UP_TIME_HOURS | Total uptime hours |r| h |
## Full Example
### Things file ###
```
Thing valloxmv:valloxmv:lueftung [ip="192.168.1.3", updateinterval=60]
```
### Items file ###
```
Number State "Current state: [%d]" {channel="valloxmv:valloxmv:lueftung:state"}
Number FanSpeed "Fanspeed [%d %%]" {channel="valloxmv:valloxmv:lueftung:fanspeed"}
Number Temp_TempInside "Temp inside [%.1f °C]" <temperature> {channel="valloxmv:valloxmv:lueftung:tempinside"}
Number Temp_TempOutside "Temp outside [%.1f °C]" <temperature> {channel="valloxmv:valloxmv:lueftung:tempoutside"}
Number Temp_TempExhaust "Temp outgoing [%.1f °C]" <temperature> {channel="valloxmv:valloxmv:lueftung:tempexhaust"}
Number Temp_TempIncoming "Temp incoming [%.1f °C]" <temperature> {channel="valloxmv:valloxmv:lueftung:tempincoming"}
Number Humidity "Humidity [%d %%]" {channel="valloxmv:valloxmv:lueftung:humidity"}
``` |
import { useCallback, useEffect, useMemo, useState } from 'react';
import Head from 'next/head';
import { subDays, subHours } from 'date-fns';
import ArrowDownOnSquareIcon from '@heroicons/react/24/solid/ArrowDownOnSquareIcon';
import ArrowUpOnSquareIcon from '@heroicons/react/24/solid/ArrowUpOnSquareIcon';
import PlusIcon from '@heroicons/react/24/solid/PlusIcon';
import { Box, Button, Container, Stack, SvgIcon, Typography } from '@mui/material';
import { useSelection } from 'src/hooks/use-selection';
import { Layout as DashboardLayout } from 'src/layouts/dashboard/layout';
import { AccountsTable } from 'src/sections/accounts/accounts-table';
import { AccountsSearch } from 'src/sections/accounts/accounts-search';
import { applyPagination } from 'src/utils/apply-pagination';
const now = new Date();
//
const data = [
{
id: '5e86809283e28b96d2d38537',
address: {
city: 'Pasig',
country: 'Philippines',
state: 'NCR',
street: 'Ewan'
},
avatar: '/assets/avatars/avatar-mark-galvez.png',
createdAt: subDays(subHours(now, 11), 2).getTime(),
email: 'markgalvez@gmail.com',
role: 'Marketing',
name: 'Mark Galvez',
phone: '099999999999'
},
{
id: '5e887ac47eed253091be10cb',
address: {
city: 'Manila',
country: 'Philippines',
state: 'NCR',
street: 'Sampaloc, Manila'
},
avatar: '/assets/avatars/avatar-luis-lucero.png',
createdAt: subDays(subHours(now, 7), 1).getTime(),
email: 'luislucero@gmail.com',
role: 'Towing Provider',
name: 'Luis Lucero',
phone: '099999999789'
},
{
id: '5e887b209c28ac3dd97f6db5',
address: {
city: 'Manila',
country: 'Philippines',
state: 'NCR',
street: 'Sampaloc, Manila'
},
avatar: '/assets/avatars/avatar-andrei-nicholas.png',
createdAt: subDays(subHours(now, 1), 2).getTime(),
email: 'andreinicholas@gmail.com',
role: 'Customer',
name: 'Andrei Nicholas',
phone: '099999456789'
},
];
// const useAccountData = () => {
// const [data, setData] = useState([]);
//
// useEffect(() => {
// // Fetch data from the Django API endpoint
// fetch('http://127.0.0.1:8000/api/accounts/')
// .then((response) => response.json())
// .then((responseData) => {
// setData(responseData);
// })
// .catch((error) => {
// console.log('Error:', error);
// });
// }, []); // Empty dependency array to fetch data only once when the component mounts
//
// return data;
// };
//
// const data = useAccountData();
const useAccounts = (page, rowsPerPage) => {
return useMemo(
() => {
return applyPagination(data, page, rowsPerPage);
},
[page, rowsPerPage]
);
};
const useAccountsIds = (accounts) => {
return useMemo(
() => {
return accounts.map((accounts) => accounts.id);
},
[accounts]
);
};
const Page = () => {
const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(5);
const accounts = useAccounts(page, rowsPerPage);
const accountsIds = useAccountsIds(accounts);
const accountsSelection = useSelection(accountsIds);
const handlePageChange = useCallback(
(event, value) => {
setPage(value);
},
[]
);
const handleRowsPerPageChange = useCallback(
(event) => {
setRowsPerPage(event.target.value);
},
[]
);
return (
<>
<Head>
<title>
Accounts | AutoAxis
</title>
</Head>
<Box
component="main"
sx={{
flexGrow: 1,
py: 8
}}
>
<Container maxWidth="xl">
<Stack spacing={3}>
<Stack
direction="row"
justifyContent="space-between"
spacing={4}
>
<Stack spacing={1}>
<Typography variant="h4">
Accounts
</Typography>
<Stack
alignItems="center"
direction="row"
spacing={1}
>
<Button
color="inherit"
startIcon={(
<SvgIcon fontSize="small">
<ArrowUpOnSquareIcon />
</SvgIcon>
)}
>
Import
</Button>
<Button
color="inherit"
startIcon={(
<SvgIcon fontSize="small">
<ArrowDownOnSquareIcon />
</SvgIcon>
)}
>
Export
</Button>
</Stack>
</Stack>
<div>
<Button
startIcon={(
<SvgIcon fontSize="small">
<PlusIcon />
</SvgIcon>
)}
variant="contained"
>
Add
</Button>
</div>
</Stack>
<AccountsSearch />
<AccountsTable
count={data.length}
items={accounts}
onDeselectAll={accountsSelection.handleDeselectAll}
onDeselectOne={accountsSelection.handleDeselectOne}
onPageChange={handlePageChange}
onRowsPerPageChange={handleRowsPerPageChange}
onSelectAll={accountsSelection.handleSelectAll}
onSelectOne={accountsSelection.handleSelectOne}
page={page}
rowsPerPage={rowsPerPage}
selected={accountsSelection.selected}
/>
</Stack>
</Container>
</Box>
</>
);
};
Page.getLayout = (page) => (
<DashboardLayout>
{page}
</DashboardLayout>
);
export default Page; |
<template>
<div class="ps-product ps-product--wide" v-if="list">
<div class="ps-product__thumbnail">
<a :href="`${baseUrl}/${product.slug}`" :title="product.name">
<img loading="lazy" :alt="product.name" :src="product.image || product.product_image" :data-src="product.image || product.product_image"
:onerror="`this.src='${this.$root.baseUrl}/vendor/webkul/ui/assets/images/product/large-product-placeholder.png'`" />
</a>
<span class="ps-product__badge new" v-if="product.new">{{ product.new }}</span>
</div>
<div class="ps-product__container">
<div class="ps-product__content w-60">
<a :href="`${baseUrl}/${product.slug}`" :title="product.name" class="ps-product__title">{{product.name}}</a>
<p class="ps-product__vendor">Sold by: {{ product.brand }}</p>
<div class="ps-product__rating" v-if="product.totalReviews && product.totalReviews > 0">
<star-ratings :ratings="product.avgRating"></star-ratings>
<span><a :href="`${$root.baseUrl}/reviews/${product.slug}`">
{{ __('products.reviews-count', {'totalReviews': product.totalReviews}) }}
</a></span>
</div>
<div class="ps-product__rating" v-else>
<span v-text="product.firstReviewText"></span>
</div>
<div class="ps-product__desc"><span>Description:</span> {{ product.shortDescription }}</div>
</div>
<div class="ps-product__shopping">
<p class="ps-product__price text-center" v-html="product.priceHTML"></p>
<vnode-injector :nodes="getDynamicHTML(product.addToCartHtml)"></vnode-injector>
<ul class="ps-product__actions justify-content-around">
<li>
<vnode-injector :nodes="getDynamicHTML(product.ulHtml)"></vnode-injector>
</li>
<li v-if="!isMobile()">
<product-quick-view-btn :quick-view-details="product"></product-quick-view-btn>
</li>
</ul>
</div>
</div>
</div>
<div :class="col && col=='true' ? 'col-lg-4 col-6' : ''" v-else>
<div class="ps-product">
<div class="ps-product__thumbnail">
<a :href="`${baseUrl}/${product.slug}`" :title="product.name">
<img loading="lazy" :alt="product.name" :src="product.image || product.product_image" :data-src="product.image || product.product_image"
:onerror="`this.src='${this.$root.baseUrl}/vendor/webkul/ui/assets/images/product/large-product-placeholder.png'`" />
</a>
<span class="ps-product__badge new" v-if="product.new">{{ product.new }}</span>
<ul class="ps-product__actions justify-content-around">
<li>
<vnode-injector :nodes="getDynamicHTML(product.ulHtml)"></vnode-injector>
</li>
<li v-if="!isMobile()">
<product-quick-view-btn :quick-view-details="product"></product-quick-view-btn>
</li>
</ul>
</div>
<div class="ps-product__container">
<!-- <a :title="product.name" :href="`${baseUrl}/${product.slug}`" class="ps-product__vendor">{{ product.brand }}</a> -->
<div class="ps-product__vendor">{{ product.brand }}</div>
<div class="ps-product__content">
<a :href="`${baseUrl}/${product.slug}`" class="ps-product__title">{{product.name}}</a>
<div class="ps-product__rating" v-if="product.totalReviews && product.totalReviews > 0">
<star-ratings :ratings="product.avgRating"></star-ratings>
<span><a :href="`${$root.baseUrl}/reviews/${product.slug}`">
{{ __('products.reviews-count', {'totalReviews': product.totalReviews}) }}
</a></span>
</div>
<div class="ps-product__rating" v-else>
<span v-text="product.firstReviewText"></span>
</div>
<p class="ps-product__price" v-html="product.priceHTML"></p>
<vnode-injector :nodes="getDynamicHTML(product.addToCartHtml)"></vnode-injector>
</div>
<!-- <div class="ps-product__content hover">
<a :href="`${baseUrl}/${product.slug}`" class="ps-product__title">{{product.name}}</a>
<p class="ps-product__price" v-html="product.price"></p>
<vnode-injector :nodes="getDynamicHTML(product.addToCartHtml)"></vnode-injector>
</div> -->
</div>
</div>
</div>
</template>
<script type="text/javascript">
export default {
props: [
'list',
'product',
'col',
],
data: function () {
return {
'addToCart': 0,
'addToCartHtml': '',
}
},
methods: {
'isMobile': function () {
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
return true;
} else {
return false;
}
}
}
}
</script> |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Trisecting an Angle</title>
<style>
.cen{text-align: center;}
.alignright{text-align: right;}
</style>
</head>
<body>
<h1>Trisecting an Angle</h1>
<h6 class="cen">Ishita Srivastava<br />B.Sc. (H) Mathematics, 2nd Year</h6>
<p>Angle trisection, as the name signifies, refers to dividing a given angle into three equal parts.
Though this seems quite simple, here is a very trivial point, which seeks to ask: “Is it always possible
to trisect any randomly chosen angle using a compass and an unmarked straight-edge only?” This has
been a classical problem of ancient Greek mathematics and art of construction. This article aims to
provide a basic insight into the concept of angular trisection.</p>
<p>It has already been proven geometrically by Pierre Wantzel in the \({19}^{th}\) century that it is not
possible to trisect every angle. However, this, in no way, intends to say that no angle, whatsoever, can
be trisected using a compass and an unmarked ruler. If we consider a compass-constructible angle \(\theta\),
then an angle of measure \(3\theta\) can be trisected trivially by a compass. In fact, certain angles that are not
constructible, can still be trisected with ease. For instance, given an angle \(\frac{6 \pi }{11} \[\approx {98.18}^{\cric}\]\)
, on trisection yields an angle of \(\frac{2 \pi }{11}\). This angle cannot be constructed by a compass, but four such angles can be
combined to form \(\frac{24 \pi}{11}\), which is a \(2 \pi \) radian circle, leaving an extra angle measuring \(\frac{2 \pi }{11}\)
, which is equal to one-third of the original angle, and thus, its trisection. However, this method cannot be applied to
all angles since all angles might not always follow a similar calculation. Angles as simple as \(\frac{ \pi }{6}\)
6 cannot be
trisected using this method, and hence are not ‘trisectible’ using a compass-straight edge combination.
In addition to this, the trisection of this, which is \(\frac{ \pi }{18}\) radians or \({20}^{\cric}\) is not compass-constructible.
After the preceding discussion, it has become clearly evident that we need a different process
for trisecting angles. Apart from using highly advanced geometrical equipments or its electronic
counterparts, there is a simpler way of achieving this seemingly difficult task. This is done by using
Japanese Origami paper folding technique.</p>
<p>Origami[‘Ori’: folding, ‘kami/gami’: paper] <i>It is the art of paper folding, which is often associated
with Japanese culture. The goal is to transform a flat sheet of square paper into a finished sculpture
through folding and sculpting techniques. A few Origami folds can be combined in a number of ways
to make intricate designs. The best known model is the Japanese paper crane.</i></p>
<p>
Follow these basic steps in order to trisect an angle:<br />
<i>Step 0:</i> Take a piece of square sheet and create an arbitrary angle by folding the paper such that the
edge of the paper acts as the base of the angle and the crease created by the fold (which meets the
base edge at the bottom left corner) acts as the arm of the angle. Mark this as \(\theta\). Unfold it and proceed.<br />
<i>Step 1:</i> Fold the paper into half horizontally, and call this crease \({L}_{1}\). Unfold it.<br />
<i>Step 2:</i> Then, fold the lower edge upto L1 and call this second crease as \({L}_{2}\).<br />
<i>Step 3:</i> Mark the lower left point of the paper (that is, the point where angle \( \theta \) originates) as O
and the left end of crease \({L}_{1}\) as A.<br />
<i>Step 4:</i> Fold the paper such that point O matches (or lies on) the lower crease, that is, \({L}_{2}\) and the point
A matches the crease which defines the angle \(\theta\). Press the paper at this step to create another crease \({L}_{3}\).<br />
<i>Step 5:</i> Mark the point on \({L}_{2}\) where point O matches the crease, during the creation of \({L}_{3}\) as B.<br />
<i>Step 6:</i> Unfold the paper and locate the point where \({L}_{3}\) intersects \({L}_{2}\). Mark this point as C.<br />
<i>Step 7:</i> Now, fold the paper so as to form two new creases; one which connects O and B, and the other
which connects O and C. Call them \({L}_{4}\) and \({L}_{5}\) respectively.<br />
<i>Step 8:</i> The newly formed creases \({L}_{4}\) and \({L}_{5}\) are the ones which trisect the angle \(\theta\).<br />
</p>
<p>Thus, we see that trisecting an arbitrary angle, which is not always possible using a compass and
a straight-edge only, can easily be done through this simple paper folding technique.</p>
<p>Now, the careful and curious reader must have a very genuine question in mind, and without
answering it, this article would be incomplete. You must have pondered upon ‘the secret super powers’
of Origami. Putting the question into simpler words, “What does Origami do to the paper, which a
compass and a straight-edge are unable to, that allows trisecting an angle with such ease?” This
property is owed to the methods that Origami provides for finding the solutions (or roots) not just
of quadratic, but of cubic equations as well. The answer to this question lies in the fact that\({L}_{3}\) is
a shared tangent of two parabolas (as mentioned earlier), combined with the methods of Origami for
finding roots of quadratic and cubic equations. This is what makes an angle ‘trisectible’ using the
techniques of Origami.</p>
<!-- MathJax Start -->
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<!-- MathJax Over-->
</body>
</html> |
import { useContext } from "react";
import { Wrapper, Unlocked, Title } from "./HTMLFundamentals";
import ThemeContext from "../../contexts/ColorTheme";
import { ContentWrapper, InfoWrapper } from "./ReactFetch";
import { List } from "./TheDomPartTwo";
import styled from "styled-components";
const NodePromises = ({ nodePromisesRef, isMobile }) => {
const { theme } = useContext(ThemeContext);
return (
<Wrapper id="section-23" ref={nodePromisesRef}>
<Title theme={theme} $showgame={"false"}>
Node.js Promises
</Title>
<InfoWrapper theme={theme} style={{ width: "90%", padding: "0.5rem" }}>
<div
style={{
display: "flex",
justifyContent: "space-between",
alignContent: "flex-start",
width: "100%",
}}
>
{!isMobile && (
<ContentWrapper
style={{ wordWrap: "break-all", width: "28%" }}
$isMobile={!isMobile.toString()}
>
<List theme={theme} $isReactEffects={"true"}>
<Unlocked
theme={theme}
style={{ fontWeight: "bold", fontSize: "1.5rem" }}
>
Exercise 1
</Unlocked>
<li>
Use request (request-promise) to call
'https://journeyedu.herokuapp.com/hello' and use .then to
parse the response
</li>
<li>
Use the same API and the same technique but add a language
parameter{" "}
</li>
</List>
</ContentWrapper>
)}
<ContentWrapper $isMobile={!isMobile.toString()}>
<List $isReactEffects={"true"}>
{isMobile && (
<>
<li>
Use request (request-promise) to call
'https://journeyedu.herokuapp.com/hello'.
</li>
</>
)}
{!isMobile && (
<Unlocked
theme={theme}
style={{ fontWeight: "bold", fontSize: "1.5rem" }}
>
Exercise 2
</Unlocked>
)}
<li>
Make a call "http://api.open-notify.org/iss-now.json" to get the
ISS's current position and parse the result
{!isMobile && (
<>
<br />
{JSON.stringify({ lat: 51.0, lng: 45.0 })}
</>
)}
</li>
<li>
Use opencage-api-client; get your api key and call this api
which returns the position (lat, lng), when given an address
</li>
<li>
Do the same thing but in reverse; function returns address when
given the position
</li>
<li>
{!isMobile && (
<Unlocked theme={theme}>
Put all of it together! <br />{" "}
</Unlocked>
)}
Make a function that accepts an address and returns the distance
of the ISS from that address
</li>
</List>
</ContentWrapper>
</div>
</InfoWrapper>
<Acheivement theme={theme}>
<Unlocked theme={theme}>Acheivement Unlocked!</Unlocked>
<br />
Patience, I Promise.
</Acheivement>
</Wrapper>
);
};
export const Acheivement = styled.p`
line-height: 1.5;
font-size: 1.5rem;
color: black;
margin: 0;
margin-top: 3%;
padding: 1.5% 1.5%;
border-left: 3px solid #50196f;
border-top: 3px solid #50196f;
border-top-left-radius: 20px;
${({ theme }) => theme === "dark" && `color: white;border-color: #a742bc`};
font-weight: 700;
@media (max-width: 800px) {
left: 0;
max-width: 80%;
padding: 3vh 0 0 0;
border-left: none;
border-top-left-radius: 0;
text-align: center;
margin-top: 0;
font-size: 18px;
}
@media (max-height: 800px) {
display: none;
}
@media (min-height: 1000px) {
display: flex;
}
`;
export default NodePromises; |
package org.the_chance.honeymart.ui.base
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import org.the_chance.honeymart.domain.util.AdminException
import org.the_chance.honeymart.domain.util.CartException
import org.the_chance.honeymart.domain.util.CategoryException
import org.the_chance.honeymart.domain.util.CouponException
import org.the_chance.honeymart.domain.util.ErrorHandler
import org.the_chance.honeymart.domain.util.GeneralException
import org.the_chance.honeymart.domain.util.ImageException
import org.the_chance.honeymart.domain.util.MarketException
import org.the_chance.honeymart.domain.util.NetworkException
import org.the_chance.honeymart.domain.util.OrderException
import org.the_chance.honeymart.domain.util.OwnerException
import org.the_chance.honeymart.domain.util.ProductException
import org.the_chance.honeymart.domain.util.TokenException
import org.the_chance.honeymart.domain.util.UserException
import org.the_chance.honeymart.domain.util.handelAdminException
import org.the_chance.honeymart.domain.util.handelCartException
import org.the_chance.honeymart.domain.util.handelCategoryException
import org.the_chance.honeymart.domain.util.handelCouponException
import org.the_chance.honeymart.domain.util.handelGeneralException
import org.the_chance.honeymart.domain.util.handelImageException
import org.the_chance.honeymart.domain.util.handelMarketException
import org.the_chance.honeymart.domain.util.handelNetworkException
import org.the_chance.honeymart.domain.util.handelOrderException
import org.the_chance.honeymart.domain.util.handelOwnerException
import org.the_chance.honeymart.domain.util.handelProductException
import org.the_chance.honeymart.domain.util.handelTokenException
import org.the_chance.honeymart.domain.util.handelUserException
import java.io.IOException
abstract class BaseViewModel<T, E>(initialState: T) : ViewModel() {
abstract val TAG: String
protected open fun log(message: String) {
Log.e(TAG, message)
}
protected val _state = MutableStateFlow(initialState)
val state = _state.asStateFlow()
protected val _effect = MutableSharedFlow<E>()
val effect = _effect.asSharedFlow()
private var job: Job? = null
protected fun <T> tryToExecute(
function: suspend () -> T,
onSuccess: (T) -> Unit,
onError: (t: ErrorHandler) -> Unit,
dispatcher: CoroutineDispatcher = Dispatchers.IO,
) {
viewModelScope.launch(dispatcher) {
handleException(
onError
) {
val result = function()
log("tryToExecute: $result ")
onSuccess(result)
}
}
}
private suspend fun <T> handleException(
onError: (t: ErrorHandler) -> Unit,
action: suspend () -> T
) {
try {
action()
} catch (exception: Exception) {
log("tryToExecute error: $exception")
when (exception) {
is UserException -> handelUserException(exception, onError)
is OwnerException -> handelOwnerException(exception, onError)
is AdminException -> handelAdminException(exception, onError)
is MarketException -> handelMarketException(exception, onError)
is CategoryException -> handelCategoryException(exception, onError)
is ProductException -> handelProductException(exception, onError)
is OrderException -> handelOrderException(exception, onError)
is CartException -> handelCartException(exception, onError)
is ImageException -> handelImageException(exception, onError)
is CouponException -> handelCouponException(exception, onError)
is GeneralException -> handelGeneralException(exception, onError)
is TokenException -> handelTokenException(exception, onError)
is NetworkException -> handelNetworkException(exception, onError)
is IOException -> onError(ErrorHandler.NoConnection)
else -> onError(ErrorHandler.InvalidData)
}
}
}
protected fun <T : BaseUiEffect> effectActionExecutor(
_effect: MutableSharedFlow<T>,
effect: T,
) {
viewModelScope.launch {
_effect.emit(effect)
}
}
} |
import React, { useRef, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { Col, Form, FormGroup } from 'reactstrap'
import '../shared/search-bar.css'
import Alert from '../shared/Alert'
import { BASE_URL } from '../utils/config'
const SearchBar = ({pos}) => {
const autoCompleteRef = useRef();
const fromRef = useRef('')
const toRef = useRef('')
const todayRef = useRef(new Date())
const passengersRef = useRef(0)
const navigate = useNavigate()
const Today = new Date().toISOString().slice(0, 10);
const options = {
fields: ["address_components", "geometry", "icon", "name"],
types: ['(cities)']
};
useEffect(() => {
autoCompleteRef.current = new window.google.maps.places.Autocomplete(
fromRef.current,
options
);
}, []);
useEffect(() => {
autoCompleteRef.current = new window.google.maps.places.Autocomplete(
toRef.current,
options
);
}, []);
const searchHandler = async () => {
const from = fromRef.current.value;
const to = toRef.current.value;
const today = todayRef.current.value;
const passengers = passengersRef.current.value
if (from === '' || to === '' || today === '' || passengers === '') {
return false;
}
const res = await fetch(`${BASE_URL}/search/results?from=${from}&to=${to}&date=${today}&passengers=${passengers}`)
const result = await res.json()
console.log(result.success)
if(!result.success){
navigate('/searchresults',{state:false})
}else{
const {data} = result
navigate(`/searchresults`, { state: data})
}
}
return <Col lg="12">
<div className={`${pos} search__bar`}>
<Form className='d-flex align-items-center gap-4 forms'>
<FormGroup className='d-flex gap-3 form__group form__group-fast m-0'>
<span><i className='ri-map-pin-line'></i></span>
<input type="text" className=' border-none rounded-full' placeholder='Where do you leave?' ref={fromRef} />
</FormGroup>
<FormGroup className='d-flex gap-3 form__group form__group-fast m-0'>
<span><i className='ri-map-pin-time-line'></i></span>
<input type="text" className=' border-none rounded-full' placeholder='Where do you want to go' ref={toRef} />
</FormGroup>
<FormGroup className='d-flex gap-3 form__group form__group-last m-0'>
<span><i className='ri-calendar-line'></i></span>
<input type="date" className=' border-none rounded-full' placeholder={Today} ref={todayRef} />
</FormGroup>
<FormGroup className='d-flex gap-3 form__group form__group-last m-0'>
<span><i className='ri-group-line'></i></span>
<input type="number" className=' border-none rounded-full' placeholder='0' ref={passengersRef} />
</FormGroup>
<FormGroup className='d-flex gap-3 form__group form__group-last m-0'>
<span className='search__icon' type='submit' onClick={searchHandler}>
<i className='ri-search-line'></i>
</span>
</FormGroup>
</Form>
</div>
</Col>
}
export default SearchBar |
import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
import { Subject } from 'rxjs';
import { AlertService } from 'src/app/services/alert.service';
import { UserService } from 'src/app/services/user.service';
import { DataTableDirective } from 'angular-datatables';
@Component({
selector: 'app-user-list',
templateUrl: './user-list.component.html',
styleUrls: ['./user-list.component.scss']
})
export class UserListComponent implements OnInit, AfterViewInit {
@ViewChild(DataTableDirective)
dtElement: DataTableDirective;
users: [];
dtOptions: DataTables.Settings = {};
dtTrigger: Subject<any> = new Subject<any>();
constructor(
private alertService: AlertService,
private userService: UserService
) { }
ngOnInit() {
this.dtOptions = {
order: [],
pagingType: 'full_numbers',
pageLength: 50,
columnDefs: [{ "orderable": false, "targets": 0 }]
};
this.getUsers();
}
ngAfterViewInit(): void {
this.dtTrigger.next();
}
ngOnDestroy(): void {
// Do not forget to unsubscribe the event
this.dtTrigger.unsubscribe();
}
getUsers() {
this.userService.getAll()
.subscribe((data) => {
this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
// Destroy the table first
dtInstance.destroy();
this.users = data;
this.dtTrigger.next();
});
},
(error) => {
this.alertService.error(error);
})
}
} |
"""
Rozwiązanie zadania umieść w jednym pliku:
Napisz funkcję o nagłówku
def odwroc(napis):
która zwraca napis zapisany od końca.
Zdefiniuj funkcję o nagłówku
def wycinek(napis, pocz, kon):
która zwraca nowy napis utworzony ze znaków napisu danego, poczynając od znaku o indeksie pocz, a kończąc na znaku o indeksie kon.
wycinek('kotlet', 0, 2) == 'kot'
wycinek('kolacja', 1, 3) == 'ola'
Zdefiniuj funkcję o nagłówku
def szyfruj(napis, klucz):
która dla danego napisu zwróci ten sam napis zaszyfrowany prostym szyfrem odwracającym — klucz określa długość odwracanych fragmentów. Przykłady:
szyfruj("Aladyn", 2) --> "lAdany"
szyfruj("Aladyn", 3) --> "alAnyd"
szyfruj("Aladyn", 4) --> "dalAny"
szyfruj("Aladyn", 5) --> "ydalAn"
Wskazówka: skorzystaj z funkcji wycinek oraz odwroc (obie zdefiniowane wcześniej).
Zdefiniuj funkcję o nagłówku
def deszyfruj(napis, klucz):
która odwraca powyższy proces.
"""
def odwroc(napis):
return napis[::-1]
def wycinek(napis, pocz, kon):
return napis[pocz:kon + 1]
def wycinek_v2(napis, kon):
return napis[:kon]
def szyfruj(napis, klucz):
return odwroc(wycinek_v2(napis, klucz)) + napis[klucz:]
def deszyfruj(napis, klucz):
return szyfruj(napis, klucz)
print(wycinek("kotlet", 0, 2))
print(wycinek("kolacja", 1, 3))
print("----------------")
print(wycinek_v2("Aladyn", 2))
print("----------------")
print(szyfruj("Aladyn", 2))
print(szyfruj("Aladyn", 3))
print(szyfruj("Aladyn", 4))
print(szyfruj("Aladyn", 5))
print("----------------")
print(deszyfruj("lAadyn", 2))
print(deszyfruj("ydalAn", 5)) |
import re, os
from importlib import resources
from traceback import format_exc as traceback_format_exc
from .ecuapass_utils import Utils
from ecuapassdocs.info.resourceloader import ResourceLoader
#--------------------------------------------------------------------
# Class for extracting different values from document texts
#--------------------------------------------------------------------
class Extractor:
#-------------------------------------------------------------------
#-- Get location info: ciudad, pais, fecha -------------------------
#-- Boxes: Recepcion, Embarque, Entrega ----------------------------
#-------------------------------------------------------------------
def extractLocationDate (text, resourcesPath, fieldType=None):
location = {"ciudad":"||LOW", "pais":"||LOW", "fecha":"||LOW"}
try:
text = text.replace ("\n", " ")
# Fecha
fecha = Extractor.getDate (text, resourcesPath)
location ["fecha"] = fecha if fecha else "||LOW"
# Pais
text, location = Extractor.removeSubjectCiudadPais (text, location, resourcesPath, fieldType)
except:
Utils.printException (f"Obteniendo datos de la localización: '{fieldType}' en el texto", text)
return (location)
#-----------------------------------------------------------
#-- Get subject (remitente, destinatario, declarante,..) info
#-- Info: nombre, dir, pais, ciudad, id, idNro
#-----------------------------------------------------------
def getSubjectInfoFromText (text, resourcesPath, subjectType):
subject = {"nombre":None, "direccion":None, "pais": None,
"ciudad":None, "tipoId":None, "numeroId": None}
try:
lines = text.split ("\n")
if len (lines) == 3:
nameDirLines = lines [0:2]
idPaisLine = lines [2]
elif len (lines) == 4:
nameDirLines = lines [0:3]
idPaisLine = lines [3]
elif len (lines) < 3:
print (f">>> Alerta: Pocas líneas de texto para extraer información de empresa.")
return subject
text, subject = Extractor.removeSubjectId (idPaisLine, subject, subjectType)
text, subject = Extractor.removeSubjectCiudadPais (text, subject, resourcesPath, subjectType)
text, subject = Extractor.removeSubjectCiudadPais (text, subject, resourcesPath, subjectType)
nameDirText = "\n".join (nameDirLines)
text, subject = Extractor.removeSubjectNombreDireccion
(nameDirText, subject, subjectType)
subject ["numeroId"] = Utils.convertToEcuapassId (subject ["numeroId"])
except:
Utils.printException (f"Obteniendo datos del sujeto: '{subjectType}' en el texto: '{text}'")
print (subject)
return (subject)
#-- Extracts and replaces IdType and IdNumber from text-------
def getReplaceSubjectId (text, subject, replaceString, type):
try:
if not any (x in text.upper() for x in ["NIT", "RUC", "OTROS"]):
return (text, subject)
reNumber = r'\d+(?:[.,]*\d*)+' # RE for extracting a float number
reId = rf"(RUC|NIT|OTROS)[\s.:]+({reNumber}(?:-\d)?)\s*"
result = re.search (reId, text, flags=re.S)
subject ["tipoId"] = result.group (1) if result else None
subject ["numeroId"] = result.group (2).replace (".", "") if result else None
text = re.sub (reId, replaceString, text, flags=re.S).strip()
except:
Utils.printException (f"Obteniendo informacion de ID de '{type}'")
return (text, subject)
#-- Extracts and removes IdType and IdNumber from text-------
def removeSubjectId (text, subject, type):
text, subject = Extractor.getReplaceSubjectId (text, subject, "", type)
return (text, subject)
#------------------------------------------------------------------
#-- Get ciudad + pais using data from ecuapass
#------------------------------------------------------------------
def extractCiudadPais (text, resourcesPath):
info = {"ciudad":None, "pais":None}
try:
rePais = ".*?(ECUADOR|COLOMBIA|PERU)"
pais = Extractor.getValueRE (rePais, text, re.I)
info ["pais"] = pais
if (pais):
cities = Extractor.getSubjectCitiesString (pais, resourcesPath)
reLocation = f"(?P<ciudad>{cities}).*(?P<pais>{pais})[.\s]*"
result = re.search (reLocation, text, flags=re.I)
info ["ciudad"] = result.group ("ciudad") if result != None else None
else:
print (">>>>>> Extracting 'ciudad' from:", text)
reCiudad = r"\b(\w+(?:\s+\w+)*)\b"
info ["ciudad"] = Extractor.getValueRE (reCiudad, text, re.I)
except:
Utils.printException (f"Obteniendo ciudad-pais de '{text}'", text)
return (info)
#-- Get ciudad + pais using data from ecuapass ------------------
def removeSubjectCiudadPais (text, subject, resourcesPath, type):
text = text.upper ()
try:
rePais = ".*?(ECUADOR|COLOMBIA|PERU)"
pais = Extractor.getValueRE (rePais, text, re.I)
subject ["pais"] = pais
cities = Extractor.getSubjectCitiesString (pais, resourcesPath)
reLocation = f"(?P<ciudad>{cities})[\s\-,\s]+(?P<pais>{pais})[.\s]*"
result = re.search (reLocation, text, flags=re.I)
if (result == None):
printx (f"Ciudad desconocida en texto: '{text}' de '{type}'")
else:
#if (type in ["06_Recepcion", "07_Embarque", "08_Entrega", "19_Emision"]):
subject ["ciudad"] = result.group ("ciudad") if result else None
text = text.replace (result.group (0), "")
except:
Utils.printException (f"Obteniendo ciudad-pais de '{type}'", text)
return (text.strip(), subject)
#-- Extracts and remove Nombre and Direccion---------------------
def removeSubjectNombreDireccion (text, subject, type):
try:
textLines = text.split ("\n")
subject ["nombre"] = textLines [0].strip()
if len (textLines) == 2:
subject ["direccion"] = textLines [1].strip()
else:
subject ["direccion"] = " ".join (textLines[1:]) + "||LOW"
#printx ("EXCEPCION: Información sujeto con muchas líneas")
#printx ("\tTEXT:", textLines)
except:
Utils.printException (f"Obteniendo nombre-direccion de '{type}'")
return (text, subject)
#-- Extracts and remove Nombre and Direccion---------------------
#-- Check if name or dir is expanded in more than one line ------
def removeSubjectNombreDireccion (text, subject, type):
try:
lines = text.split ("\n")
if len (lines) == 2:
subject ["nombre"] = lines [0].strip()
subject ["direccion"] = lines [1].strip()
elif len (lines) == 3:
if len (lines [0]) > len (lines [1]):
subject ["nombre"] = lines [0].strip () + " " + lines [1].strip () + "||LOW"
subject ["direccion"] = lines [2].strip () + "||LOW"
else:
subject ["nombre"] = lines [0].strip () + "||LOW"
subject ["direccion"] = lines [1].strip () + " " + lines [2].strip () + "||LOW"
except:
Utils.printException (f"Obteniendo nombre-direccion de '{type}'")
return (text, subject)
#-----------------------------------------------------------
# Using "search" extracts first group from regular expresion.
# Using "findall" extracts last item from regular expresion.
#-----------------------------------------------------------
def getValueRE (RE, text, flags=re.I, function="search"):
if text != None:
if function == "search":
result = re.search (RE, text, flags=flags)
return result.group(1) if result else None
elif function == "findall":
resultList = re.findall (RE, text, flags=flags)
return resultList [-1] if resultList else None
return None
#-- Extract all type of number (int, float..) -------------------
def getNumber (text):
reNumber = r'\d+(?:[.,]?\d*)+' # RE for extracting a float number
number = Utils.getValueRE (reNumber, text, function="findall")
return (number)
def getRemoveNumber (text):
number = Extractor.getNumber (text)
if number != None:
text.replace (number, "")
return text, number
#-- Get "numero documento" with possible prefix "No."------------
def getNumeroDocumento (text):
# Cases SILOGISTICA and others
# Examples: ["N° PO-CO-0011-21-338781-23", "No.019387", "CO003627"]
reNumber = r'(?:N.*?)?\b([A-Za-z0-9-]+)\b'
# NTA, BYZA, SYTSA
#reNumber = r'([A-Za-z]+\d+)'
number = Extractor.getValueRE (reNumber, text)
return number
#-- Get MRN number from text with pattern "MRN:XXXX"
def getMRN (text):
reMRN = r"\bMRN\b\s*[:]?\s*\b(\w*)\b"
MRN = Utils.getValueRE (reMRN, text)
return MRN
def getLastString (text):
string = None
try:
reStrings = r'([a-zA-Z0-9-]+)'
results = re.findall (reStrings, text)
if len (results) > 1:
string = results [-1] if results else None
except Exception as e:
Utils.printException (f"Extrayendo última cadena desde el texto: '{text}'", e)
return string
def getFirstString (text):
string = None
try:
reStrings = r'([a-zA-Z0-9-]+)'
results = re.findall (reStrings, text)
string = results [0] if results else None
except Exception as e:
Utils.printException (f"Extrayendo última cadena desde el texto: '{text}'", e)
return string
#------------------------------------------------------------------
# Extracts last word from a string with 1 or more words|numbers
#------------------------------------------------------------------
def getLastWord (text):
word = None
try:
# RE for extracting all words as a list (using findall)
reWords = r'\b[A-Za-z]+(?:/\w+)?\b'
results = re.findall (reWords, text)
word = results [-1] if results else None
except Exception as e:
Utils.printException (f"Extrayendo última palabra desde el texto: '{text}'", e)
return word
#------------------------------------------------------------------
# Extracts last int number from a string with 1 or more numbers
#------------------------------------------------------------------
def getLastNumber (text):
number = None
try:
reNumbers = r'\b\d+\b' # RE for extracting all numeric values as a list (using findall)
number = re.findall (reNumbers, text)[-1]
except:
Utils.printException ("Extrayendo último número desde el texto: ", text)
return number
#------------------------------------------------------------------
# Extract conductor's name (full)
#------------------------------------------------------------------
def extractNames (text):
names = None
try:
reNames = r'\b[A-Z][A-Za-z\s]+\b'
names = re.search (reNames, text).group(0).strip()
except:
Utils.printException ("Extrayendo nombres desde el texto: ", text)
return names
#------------------------------------------------------------------
# Get pais from nacionality
#------------------------------------------------------------------
def getPaisFromSubstring (text):
pais = None
try:
if "COL" in text.upper():
pais = "COLOMBIA"
elif "ECU" in text.upper():
pais = "ECUADOR"
elif "PER" in text.upper():
pais = "PERU"
except:
Utils.printException ("Obtenidendo pais desde nacionalidad en el texto:", text)
return pais
#------------------------------------------------------------------
# Extract pais
#------------------------------------------------------------------
def getPais (text, resourcesPath):
pais = None
try:
rePaises = Extractor.getDataString ("paises.txt", resourcesPath)
pais = Extractor.getValueRE (f"({rePaises})", text, re.I)
except:
Utils.printException (f"Obteniendo pais desde texto '{text}'")
return pais
#-- Get ciudad given pais else return stripped string ------------
def getCiudad (text, pais, resourcesPath):
if (pais): # if pais get ciudades from pais and search them in text
reCities = Extractor.getSubjectCitiesString (pais, resourcesPath)
result = re.findall (reCities, text)
else: # if no pais, get the substring without trailing spaces
reCiudad = r"\b(\w+(?:\s+\w+)*)\b"
ciudad = re.findall (reCiudad, text)
ciudad = result[-1] if result [-1] else None
return ciudad
#------------------------------------------------------------------
# Extract 'placa' and 'pais'
#------------------------------------------------------------------
def getPlacaPais (text):
result = {"placa":None, "pais":None}
if (text is None or "N/A" in text or "XX" in text):
return result
try:
rePlacaPais = r"(\w+)\W+(\w+)"
res = re.search (rePlacaPais, text)
result ["placa"] = res.group (1)
result ["pais"] = res.group (2)
except:
Utils.printException ("Extrayendo placa pais desde el texto:", text)
return result
#------------------------------------------------------------------
# Get 'embalaje' from text with number + embalaje: NNN WWWWW
#------------------------------------------------------------------
def getTipoEmbalaje (text, resourcesPath):
Utils.printx (f">>> Extrayendo embalaje desde el texto: '{text}'")
try:
reNumber = r'\d+(?:[.,]*\d*)+' # RE for extracting a float number
reEmbalaje = rf"{reNumber}\s+(\b(\w+)\b)" # String after number
embalaje = Extractor.getValueRE (reEmbalaje, text)
if "PALLETS" in embalaje:
return "152" # "[152] PALETAS"
elif "SACOS" in embalaje.upper ():
return "104" # "[104] SACO"
elif "CAJAS" in embalaje.upper ():
return "035" # "[035] CAJA"
else:
return embalaje.strip () + "||LOW"
except:
Utils.printx (f">>> EXCEPCION: Problemas extrayendo embalaje desde texto: '{text}'")
return None
#------------------------------------------------------------------
#-- Extract numerical or text date from text ----------------------
#------------------------------------------------------------------
def getDate (text, resourcesPath):
numericalDate = "||LOW"
try:
# Load months from data file
monthsString = Extractor.getDataString ("meses.txt", resourcesPath)
monthsList = monthsString.split ("|")
# Search for numerical or text date
reDay = r'(?P<day>\d{1,2})'
reMonthNum = r'(?P<month>\d{1,2})'
reMonthTxt = rf'(?P<month>{monthsString})'
reYear = r'(?P<year>\d[.]?\d{3})'
reWordSep = r'\s+(?:DE|DEL)\s+'
reSep = r'(-|/)'
reDate0 = rf'\b{reDay}\s*[-]\s*{reMonthNum}\s*[-]\s*{reYear}\b' # 31-12-2023
reDate1 = rf'\b{reMonthTxt}\s+{reDay}{reWordSep}{reYear}\b' # Junio 20 del 2023
reDate2 = rf'\b{reMonthTxt}\s+{reDay}{reSep}{reYear}\b' # Junio 20/2023
reDate3 = rf'\b{reDay}{reWordSep}{reMonthTxt}{reWordSep}{reYear}\b' # 20 de Junio del 2023
reDate4 = rf'\b{reYear}{reSep}{reMonthNum}{reSep}{reDay}\b' # 2023/12/31
reDate5 = rf'\b{reYear}{reSep}{reMonthTxt}{reSep}{reDay}\b' # 2023/DICIEMBRE/31
reDateOptions = [reDate0, reDate1, reDate2, reDate3, reDate4, reDate5]
# Evaluate all reDates and select the one with results
results = [re.search (x, text, re.I) for (i, x) in enumerate (reDateOptions)]
if results [0]:
result = results [0]
month = result.group('month')
elif results [1] or results [2]:
result = results [1] if results [1] else results [2]
month = monthsList.index (result.group('month').upper()) + 1
elif results [3]:
result = results [3]
month = result.group('month')
elif results [4]:
result = results [4]
month = result.group('month')
elif results [5]:
result = results [5]
month = monthsList.index (result.group('month').upper()) + 1
else:
printx (f"No existe fecha en texto '{text}'")
return None
year = result.group ('year').replace (".", "")
numericalDate = f"{result.group('day')}-{month}-{year}"
except Exception as e:
Utils.printException (f"Obteniendo fecha de texto: '{text}'", e)
return numericalDate
#-------------------------------------------------------------------
#-- Load cities from DB and create a piped string of cites ---------
#-------------------------------------------------------------------
def getSubjectCitiesString (pais, resourcesPath):
if (pais=="COLOMBIA"):
citiesString = Extractor.getDataString ("ciudades_colombia.txt", resourcesPath)
elif (pais=="ECUADOR"):
citiesString = Extractor.getDataString ("ciudades_ecuador.txt", resourcesPath)
elif (pais=="PERU"):
citiesString = Extractor.getDataString ("ciudades_peru.txt", resourcesPath)
else:
return None
return citiesString
#-------------------------------------------------------------------
#-- Get ECUAPASS data items as dic taking resources from package no path
#-------------------------------------------------------------------
def old_getDataDic (dataPath):
dirList = dataPath.split (os.path.sep)
resourceName = dirList [-1]
resourcePackage = dirList [-2]
dataDic = {}
dataLines = ResourceLoader.loadText (resourcePackage, resourceName)
for line in dataLines [1:]:
res = re.search (r"\[(.+)\]\s+(.+)", line)
dataDic [res.group(1)] = res.group(2)
return (dataDic)
def getDataDic (dataFilename, resourcesPath, From="values"):
dataPath = os.path.join (resourcesPath, dataFilename)
dirList = dataPath.split (os.path.sep)
resourceName = dirList [-1]
resourcePackage = dirList [-2]
dataDic = {}
dataLines = ResourceLoader.loadText (resourcePackage, resourceName)
for line in dataLines [1:]:
res = re.search (r"\[(.+)\]\s+(.+)", line)
dataDic [res.group(1)] = res.group(2)
return (dataDic)
#-------------------------------------------------------------------
#-- Return a piped string of ECUPASS data used in regular expression
#-- From join "values" or join "keys"
#-------------------------------------------------------------------
def getDataString (dataFilename, resourcesPath, From="values"):
dataPath = os.path.join (resourcesPath, dataFilename)
dataDic = Extractor.getDataDic (dataFilename, resourcesPath)
dataString = None
if From=="values":
#dataString = "|".join (map (re.escape, dataDic.values())) #e.g. 'New York' to 'New\\ York'
dataString = "|".join (dataDic.values()) #e.g. 'New York' to 'New\\ York'
else:
dataString = "|".join (dataDic.keys())
return (dataString)
#-------------------------------------------------------------------
# Global utility functions
#-------------------------------------------------------------------
def printx (*args, flush=True, end="\n", plain=False):
print ("SERVER:", *args, flush=flush, end=end) |
zookeeper原生API注册Watcher需要反复注册,即Watcher触发之后就需要重新进行注册。
另外,客户端断开之后重新连接到服务器也是需要一段时间。这就导致了zookeeper客户端不能够接收全部的zookeeper事件。
zookeeper保证的是数据的最终一致性。因此,对于此问题需要特别注意,在不要对zookeeper事件进行强依赖。
zookeeper机制的特点
zookeeper的getData(),getChildren()和exists()方法都可以注册watcher监听。而监听有以下几个特性:
一次性触发(one-time trigger)
当数据改变的时候,那么一个Watch事件会产生并且被发送到客户端中。但是客户端只会收到一次这样的通知,如果以后这个数据再次发生改变的时候,
之前设置Watch的客户端将不会再次收到改变的通知,因为Watch机制规定了它是一个一次性的触发器。
当设置监视的数据发生改变时,该监视事件会被发送到客户端,例如,如果客户端调用了 getData(“/znode1”, true) 并且稍后 /znode1 节点上的数
据发生了改变或者被删除了,客户端将会获取到 /znode1 发生变化的监视事件,而如果 /znode1 再一次发生了变化,除非客户端再次对 /znode1 设置
监视,否则客户端不会收到事件通知。
发送给客户端(Sent to the client)
这个表明了Watch的通知事件是从服务器发送给客户端的,是异步的,这就表明不同的客户端收到的Watch的时间可能不同,但是ZooKeeper有保证:当一个
客户端在看到Watch事件之前是不会看到结点数据的变化的。例如:A=3,此时在上面设置了一次Watch,如果A突然变成4了,那么客户端会先收到Watch事
件的通知,然后才会看到A=4。
Zookeeper 客户端和服务端是通过 Socket 进行通信的,由于网络存在故障,所以监视事件很有可能不会成功地到达客户端,监视事件是异步发送至监视
者的,Zookeeper 本身提供了保序性(ordering guarantee):即客户端只有首先看到了监视事件后,才会感知到它所设置监视的 znode 发生了变化
(a client will never see a change for which it has set a watch until it first sees the watch event). 网络延迟或者其他因素
可能导致不同的客户端在不同的时刻感知某一监视事件,但是不同的客户端所看到的一切具有一致的顺序。
被设置了watch的数据(The data for which the watch was set)
这是指节点发生变动的不同方式。你可以认为ZooKeeper维护了两个watch列表:data watch和child watch。getData()和exists()设置data watch,
而getChildren()设置child watch。或者,可以认为watch是根据返回值设置的。getData()和exists()返回节点本身的信息,而getChildren()返回
子节点的列表。因此,setData()会触发znode上设置的data watch(如果set成功的话)。一个成功的 create() 操作会触发被创建的znode上的数据watch,
以及其父节点上的child watch。而一个成功的 delete()操作将会同时触发一个znode的data watch和child watch(因为这样就没有子节点了),
同时也会触发其父节点的child watch。
Watch由client连接上的ZooKeeper服务器在本地维护。这样可以减小设置、维护和分发watch的开销。当一个客户端连接到一个新的服务器上时,
watch将会被以任意会话事件触发。当与一个服务器失去连接的时候,是无法接收到watch的。而当client重新连接时,如果需要的话,所有先前注册
过的watch,都会被重新注册。通常这是完全透明的。只有在一个特殊情况下,watch可能会丢失:对于一个未创建的znode的exist watch,
如果在客户端断开连接期间被创建了,并且随后在客户端连接上之前又删除了,这种情况下,这个watch事件可能会被丢失。
ZooKeeper对Watch提供了什么保障
对于watch,ZooKeeper提供了这些保障:
Watch与其他事件、其他watch以及异步回复都是有序的。 ZooKeeper客户端库保证所有事件都会按顺序分发。
客户端会保障它在看到相应的znode的新数据之前接收到watch事件。//这保证了在process()再次利用zk client访问时数据是存在的
从ZooKeeper接收到的watch事件顺序一定和ZooKeeper服务所看到的事件顺序是一致的。
关于Watch的一些值得注意的事情
Watch是一次性触发器,如果得到了一个watch事件,而希望在以后发生变更时继续得到通知,应该再设置一个watch。
因为watch是一次性触发器,而获得事件再发送一个新的设置watch的请求这一过程会有延时,所以无法确保看到了所有发生在ZooKeeper上的 一个节点
上的事件。所以请处理好在这个时间窗口中可能会发生多次znode变更的这种情况。(可以不处理,但至少要意识到这一点)。//也就是说,在process()
中如果处理得慢而没有注册new watch时,在这期间有其它事件出现时是不会通知!!
一个watch对象或一个函数/上下文对,为一个事件只会被通知一次。比如,如果同一个watch对象在同一个文件上分别通过exists和getData注册了两次,
而这个文件之后被删除了,这时这个watch对象将只会收到一次该文件的deletion通知。//同一个watch注册同一个节点多次只会生成一个event。
当从一个服务器上断开时(比如服务器出故障了),在再次连接上之前,将无法获得任何watch。请使用这些会话事件来进入安全模式:在disconnected
状态下将不会收到事件,所以程序在此期间应该谨慎行事。
总结
经过上面的描述,对于上一篇博客中连续修改节点内容部分监听事件丢失的原因也就变得显而易见了。虽然curator帮开发人员封装了重复注册监听的过程,
但是内部依旧需要重复进行注册,而在第一个watcher触发第二个watcher还未注册成功的间隙,进行节点数据的修改,显然无法收到watcher事件。
所 有的Zookeeper读操作,包括getData()、getChildren()和exists(),都有一个开关,可以在操作的同时再设置一个 watch。在ZooKeeper中,
Watch是一个一次性触发器,会在被设置watch的数据发生变化的时候,发送给设置watch的客户端。 watch的定义中有三个关键点:
一次性触发器
一 个watch事件将会在数据发生变更时发送给客户端。例如,如果客户端执行操作getData(“/znode1″, true),而后 /znode1 发生变更或是删除了,
客户端都会得到一个 /znode1 的watch事件。如果 /znode1 再次发生变更,则在客户端没有设置新的watch的情况下,是不会再给这个客户端发送watch事件的。
发送给客户端
这 就是说,一个事件会发送向客户端,但可能在在操作成功的返回值到达发起变动的客户端之前,这个事件还没有送达watch的客户端。Watch是异步发送 的。
但ZooKeeper保证了一个顺序:一个客户端在收到watch事件之前,一定不会看到它设置过watch的值的变动。网络时延和其他因素可能会导 致不同的客户端
看到watch和更新返回值的时间不同。但关键点是,每个客户端所看到的每件事都是有顺序的。
被设置了watch的数据
这 是指节点发生变动的不同方式。你可以认为ZooKeeper维护了两个watch列表:data watch和child watch。getData()和exists()设置data watch,
而getChildren()设置child watch。或者,可以认为watch是根据返回值设置的。getData()和exists()返回节点本身的信息,而getChildren()返回
子节点的列表。因此,setData()会触发znode上设置的data watch(如果set成功的话)。一个成功的 create() 操作会触发被创建的znode上的数据watch,
以及其父节点上的child watch。而一个成功的 delete()操作将会同时触发一个znode的data watch和child watch(因为这样就没有子节点了),
同时也会触发其父节点的child watch。
Watch 由client连接上的ZooKeeper服务器在本地维护。这样可以减小设置、维护和分发watch的开销。当一个客户端连接到一个新的服务器上 时,
watch将会被以任意会话事件触发。当与一个服务器失去连接的时候,是无法接收到watch的。而当client重新连接时,如果需要的话,所有先 前注册过
的watch,都会被重新注册。通常这是完全透明的。只有在一个特殊情况下,watch可能会丢失:对于一个未创建的znode的exist watch,如果在客户端
断开连接期间被创建了,并且随后在客户端连接上之前又删除了,这种情况下,这个watch事件可能会被丢失。
ZooKeeper对Watch提供了什么保障
对于watch,ZooKeeper提供了这些保障:
Watch与其他事件、其他watch以及异步回复都是有序的。 ZooKeeper客户端库保证所有事件都会按顺序分发。
客户端会保障它在看到相应的znode的新数据之前接收到watch事件。//这保证了在process()再次利用zk client访问时数据是存在的
从ZooKeeper接收到的watch事件顺序一定和ZooKeeper服务所看到的事件顺序是一致的。
关于Watch的一些值得注意的事情
Watch是一次性触发器,如果你得到了一个watch事件,而你希望在以后发生变更时继续得到通知,你应该再设置一个watch。
因 为watch是一次性触发器,而获得事件再发送一个新的设置watch的请求这一过程会有延时,所以你无法确保你看到了所有发生在ZooKeeper上的 一个
节点上的事件。所以请处理好在这个时间窗口中可能会发生多次znode变更的这种情况。(你可以不处理,但至少请认识到这一点)。//也就是说,在process()
中如果处理得慢而没有注册new watch时,在这期间有其它事件出现时是不会通知!!之前可能就是没有意识到这点所以才引出本话题***********
一个watch对象或一个函数/上下文对,为一个事件只会被通知一次。比如,如果同一个watch对象在同一个文件上分别通过exists和getData注册了两次,
而这个文件之后被删除了,这时这个watch对象将只会收到一次该文件的deletion通知。//同一个watch注册同一个节点多次只会生成一个event.这里我想
到如果一个watch注册不同的node,也应当出现多个event?
当你从一个服务器上断开时(比如服务器出故障了),在再次连接上之前,你将无法获得任何watch。请使用这些会话事件来进入安全模式:在disconnected
状态下你将不会收到事件,所以你的程序在此期间应该谨慎行事。 |
% SCALEMASSPROPS Scale mass and inertia of the bodies of an OpenSim model
% assuming that the geometry stays constant and only the mass changes
% proportionally to a coefficient assigned in input.
%
% osimModel = scaleMassProps(osimModel, coeff)
%
% Inputs:
% osimModel - the OpenSim model for which the mass properties of the
% segments will be scaled.
%
% coeff - ratio of mass new_mass/curr_model_mass. This is used to scale
% the inertial properties of the gait2392 model to the mass of a
% specific individual.
%
% Outputs:
% osimModel - the OpenSim model with the scaled inertial properties.
%
% See also GAIT2392MASSPROPS, MAPGAIT2392MASSPROPTOMODEL.
%
%-------------------------------------------------------------------------%
% Author: Luca Modenese
% Copyright 2020 Luca Modenese
%-------------------------------------------------------------------------%
function osimModel = scaleMassProps(osimModel, coeff)
% import libraries
import org.opensim.modeling.*
% get bodyset
subjspec_bodyset = osimModel.getBodySet;
for n_b = 0:subjspec_bodyset.getSize()-1
curr_body = subjspec_bodyset.get(n_b);
% updating the mass
curr_body.setMass(coeff* curr_body.getMass);
% updating the inertia matrix for the change in mass
m = curr_body.get_inertia();
% components of inertia
xx = m.get(0)*coeff;
yy = m.get(1)*coeff;
zz = m.get(2)*coeff;
xy = m.get(3)*coeff;
xz = m.get(4)*coeff;
yz = m.get(5)*coeff;
upd_inertia = Inertia(xx , yy , zz , xy , xz , yz);
% updating Inertia
curr_body.setInertia(upd_inertia);
clear m
end
end |
/* ************************************************************************
* Copyright 2013 Advanced Micro Devices, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ************************************************************************/
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
/* Include CLBLAS header. It automatically includes needed OpenCL header,
* so we can drop out explicit inclusion of cl.h header.
*/
#include <clBLAS.h>
/* This example uses predefined matrices and their characteristics for
* simplicity purpose.
*/
static const clblasOrder order = clblasRowMajor;
static const clblasSide side = clblasLeft;
static const size_t M = 4;
static const size_t N = 5;
static const cl_float alpha = 10;
static const clblasTranspose transA = clblasNoTrans;
static const clblasUplo uploA = clblasUpper;
static const clblasDiag diagA = clblasNonUnit;
static const cl_float A[] = {
11, 12, 13, 14,
0, 22, 23, 24,
0, 0, 33, 34,
0, 0, 0, 44
};
static const size_t lda = 4; /* i.e. lda = M */
static cl_float B[] = {
11, 12, 13, 14, 15,
21, 22, 23, 24, 25,
31, 32, 33, 34, 35,
41, 42, 43, 44, 45
};
static const size_t ldb = 5; /* i.e. ldb = N */
static cl_float result[20]; /* ldb * M */
static const size_t off = 1;
static const size_t offA = 4 + 1; /* K + off */
static const size_t offB = 5 + 1; /* N + off */
static void
printResult(const char* str)
{
size_t i, j, nrows;
printf("%s:\n", str);
nrows = (sizeof(result) / sizeof(cl_float)) / ldb;
for (i = 0; i < nrows; i++) {
for (j = 0; j < ldb; j++) {
printf("%d ", (int)result[i * ldb + j]);
}
printf("\n");
}
}
int
main(void)
{
cl_int err;
cl_platform_id platform = 0;
cl_device_id device = 0;
cl_context_properties props[3] = { CL_CONTEXT_PLATFORM, 0, 0 };
cl_context ctx = 0;
cl_command_queue queue = 0;
cl_mem bufA, bufB;
cl_event event = NULL;
int ret = 0;
/* Setup OpenCL environment. */
err = clGetPlatformIDs(1, &platform, NULL);
if (err != CL_SUCCESS) {
printf( "clGetPlatformIDs() failed with %d\n", err );
return 1;
}
err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, NULL);
if (err != CL_SUCCESS) {
printf( "clGetDeviceIDs() failed with %d\n", err );
return 1;
}
props[1] = (cl_context_properties)platform;
ctx = clCreateContext(props, 1, &device, NULL, NULL, &err);
if (err != CL_SUCCESS) {
printf( "clCreateContext() failed with %d\n", err );
return 1;
}
queue = clCreateCommandQueue(ctx, device, 0, &err);
if (err != CL_SUCCESS) {
printf( "clCreateCommandQueue() failed with %d\n", err );
clReleaseContext(ctx);
return 1;
}
/* Setup clblas. */
err = clblasSetup();
if (err != CL_SUCCESS) {
printf("clblasSetup() failed with %d\n", err);
clReleaseCommandQueue(queue);
clReleaseContext(ctx);
return 1;
}
/* Prepare OpenCL memory objects and place matrices inside them. */
bufA = clCreateBuffer(ctx, CL_MEM_READ_ONLY, M * M * sizeof(*A),
NULL, &err);
bufB = clCreateBuffer(ctx, CL_MEM_READ_WRITE, M * N * sizeof(*B),
NULL, &err);
err = clEnqueueWriteBuffer(queue, bufA, CL_TRUE, 0,
M * M * sizeof(*A), A, 0, NULL, NULL);
err = clEnqueueWriteBuffer(queue, bufB, CL_TRUE, 0,
M * N * sizeof(*B), B, 0, NULL, NULL);
/* Call clblas extended function. Perform TRMM for the lower right sub-matrices */
err = clblasStrmm(order, side, uploA, transA, diagA, M - off, N - off,
alpha, bufA, offA, lda, bufB, offB, ldb, 1, &queue,
0, NULL, &event);
if (err != CL_SUCCESS) {
printf("clblasStrmmEx() failed with %d\n", err);
ret = 1;
}
else {
/* Wait for calculations to be finished. */
err = clWaitForEvents(1, &event);
/* Fetch results of calculations from GPU memory. */
err = clEnqueueReadBuffer(queue, bufB, CL_TRUE, 0,
M * N * sizeof(*result),
result, 0, NULL, NULL);
/* At this point you will get the result of STRMM placed in 'result' array. */
puts("");
printResult("clblasStrmmEx result");
}
/* Release OpenCL events. */
clReleaseEvent(event);
/* Release OpenCL memory objects. */
clReleaseMemObject(bufB);
clReleaseMemObject(bufA);
/* Finalize work with clblas. */
clblasTeardown();
/* Release OpenCL working objects. */
clReleaseCommandQueue(queue);
clReleaseContext(ctx);
return ret;
} |
import 'package:abc_monitor/theme.dart';
import 'package:flutter/material.dart';
import '../../../constants.dart';
import '../../../widgets/bottom_bar.dart';
import '../../../widgets/card_conquistas_widget.dart';
import 'documentos_controller.dart';
import 'documentos_page.dart';
class DocumentosInformativosPage extends StatefulWidget {
const DocumentosInformativosPage({Key? key}) : super(key: key);
@override
State<DocumentosInformativosPage> createState() =>
_DocumentosInformativosPageState();
}
class _DocumentosInformativosPageState
extends State<DocumentosInformativosPage> {
List<dynamic> docs = [];
final controller = DocumentosController();
@override
void initState() {
super.initState();
controller.getDocumentos().then((value) => {docs = value, setState(() {})});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Documentos e Práticas'),
centerTitle: true,
forceMaterialTransparency: true,
automaticallyImplyLeading: false,
leading: Image.asset(Constants.personAsset),
actions: [
InkWell(
onTap: () {},
child: Image.asset(Constants.sininhoAsset),
),
],
),
bottomNavigationBar: const BottomBar(
page: BottomBarPage.documentos,
),
body: docs.isEmpty
? const Center(
child: CircularProgressIndicator(),
)
: Padding(
padding: const EdgeInsets.all(8.0),
child: SingleChildScrollView(
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.max,
children: [
Text(
'Documentos e informativos',
style: Theme.of(context)
.textTheme
.headlineMedium!
.copyWith(
fontWeight: FontWeight.bold,
),
),
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
const DocumentosPage()));
},
child: Text(
'Ver todos >',
style: Theme.of(context)
.textTheme
.bodyMedium!
.copyWith(
fontWeight: FontWeight.w500,
fontSize: 16,
decoration: TextDecoration.underline,
),
),
),
],
),
Container(height: 10),
Container(
height: 100,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: docs.length,
itemBuilder: (context, int index) {
return Card(
color: AppTheme.kDefaultColor,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
docs[index % 5][0],
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
docs[index % 5][1],
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
maxLines: 2,
style: Theme.of(context)
.textTheme
.bodyMedium!
.copyWith(
color: Colors.white,
),
),
),
],
),
);
},
),
),
Container(height: 10),
Align(
alignment: Alignment.centerLeft,
child: Text(
'Práticas do ABC+',
style: Theme.of(context)
.textTheme
.headlineMedium!
.copyWith(
fontWeight: FontWeight.bold,
),
),
),
Container(height: 10),
const CardConquistasWidget(
titulo: 'Adicione Irrigação em sua lavoura de café',
descricao: ' de 9 Hectares concluídos',
quantidade: 5,
),
const CardConquistasWidget(
titulo: 'Integre sua Lavoura com a Floresta (SAF)',
descricao: ' de 5 Hectares concluídos',
quantidade: 1,
),
const CardConquistasWidget(
titulo: 'Utilize plantio direto na sua Lavoura de Soja',
descricao: ' de 6 Hectares concluídos',
quantidade: 0,
),
],
),
),
),
);
}
} |
"""
URL configuration for ecommerce_business_store project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from ecommerce_app import views
urlpatterns = [
path('admin/', admin.site.urls),
path("views/",views.index),
path("customer-register/",views.customer_register),
path("update-customer/<id>",views.update_customer),
path("delete-customer/<id>",views.delete_customer),
path('class_view/',views.ClassView.as_view())
] |
import {
Card,
CardSuit,
CardSymbol,
CasinoRules,
CasinoRulesKeys,
Doubling,
Hand,
HandCode,
HandOutcome,
SimpleCardSymbol,
TrainingHands,
TrainingPairStatus,
TrainingProgress
} from '../types';
import { getRandomItem } from '../utils';
import {
createCard,
getCardEffectiveValue,
getCardsValues,
getRandomCard,
revealHoleCard,
symbolToSimpleSymbol,
valueToSymbol
} from './card';
import {
getHardHandSymbols,
getSoftHandSymbols,
getSplitHandSymbols,
isSoftHandCode,
isSplitHandCode
} from './hand-code';
export const areHandsSplitAces = (hands: Hand[]) =>
hands.length > 1 &&
hands[0].cards[0].symbol === SimpleCardSymbol.Ace &&
hands[1].cards[0].symbol === SimpleCardSymbol.Ace;
export const canBeDealerBlackjack = (hand: Hand) => {
const visibleCard = hand.cards[0];
const cardSymbol = symbolToSimpleSymbol(visibleCard.symbol);
return cardSymbol === SimpleCardSymbol.Ace || cardSymbol === SimpleCardSymbol.Ten;
};
const canBustOnNextCard = (hand: Hand) => {
return hand.values[0] > 11;
};
export const canDouble = (hand: Hand, hands: Hand[], casinoRules: CasinoRules) => {
const handEffectiveValue = getHandEffectiveValue(hand);
const isHandWithTwoCards = hand.cards.length === 2;
const isSingleHand = hands.length === 1;
const contains9To11 = hand.values.some((handValue) => [9, 10, 11].indexOf(handValue) > -1);
const is10To11 = handEffectiveValue === 10 || handEffectiveValue === 11;
const is9To11 = handEffectiveValue === 9 || is10To11;
return (
isHandWithTwoCards &&
(casinoRules[CasinoRulesKeys.doubling] >= Doubling.anyPair ||
(casinoRules[CasinoRulesKeys.doubling] >= Doubling.nineToElevenSoft && contains9To11) ||
(casinoRules[CasinoRulesKeys.doubling] >= Doubling.nineToEleven && is9To11) ||
(casinoRules[CasinoRulesKeys.doubling] >= Doubling.tenToEleven && is10To11)) &&
(isSingleHand || casinoRules[CasinoRulesKeys.doublingAfterSplit]) &&
(!areHandsSplitAces(hands) || casinoRules[CasinoRulesKeys.hitSplitAces])
);
};
export const canHit = (hands: Hand[], casinoRules: CasinoRules) =>
!areHandsSplitAces(hands) || casinoRules[CasinoRulesKeys.hitSplitAces];
export const canSplit = (hand: Hand, handsNumber: number, casinoRules: CasinoRules) =>
hand.cards.length === 2 &&
getCardEffectiveValue(hand.cards[0]) === getCardEffectiveValue(hand.cards[1]) &&
casinoRules[CasinoRulesKeys.splitsNumber] >= handsNumber;
export const canSurrender = (hand: Hand, handsNumber: number, casinoRules: CasinoRules) =>
handsNumber === 1 && hand.cards.length === 2 && casinoRules[CasinoRulesKeys.surrender];
export const createDealerHand = (
casinoRules: CasinoRules,
dealerSymbol?: CardSymbol,
dealerSuit?: CardSuit
) => {
const dealerCards: Card[] = [
dealerSymbol ? createCard(dealerSymbol, dealerSuit) : getRandomCard()
];
if (casinoRules[CasinoRulesKeys.blackjackPeek]) {
dealerCards.push(getRandomCard({ isHoleCard: true }));
}
return createHand(dealerCards);
};
export const createHand = (cards: Card[], bet = 1): Hand => ({
bet,
cards: cards,
values: getCardsValues(cards)
});
export const dealCard = (hand: Hand, card: Card) => {
hand.cards.push(card);
hand.values = getCardsValues(hand.cards);
};
// - If the player hand has no risk (0% probabilities of busting) and some untrained pair can
// be reached by adding a specific card to the player hand, it returns that card. Returns a
// a random card otherwise
// - Called after player hitting, splitting or starting a split hand.
export const getCardForUntrainedHand = (
playerHand: Hand,
dealerSymbol: SimpleCardSymbol,
trainingHands: TrainingHands,
trainingProgress: TrainingProgress
): Card => {
let nextCard = getRandomCard();
if (!canBustOnNextCard(playerHand)) {
const isPlayerHandSoft = playerHand.values.length > 1;
const playerHandValues = getCardsValues(playerHand.cards);
const valuesToUntrainedHands = Object.values(trainingHands)
.map((trainingHand) => {
const isHandUntrainedForDealerSymbol =
trainingProgress[trainingHand.code][dealerSymbol] ===
TrainingPairStatus.untrained;
let valueToReachThisHand: number;
if (isSplitHandCode(trainingHand.code)) {
// Untrained split hands can never be reached after user action
valueToReachThisHand = -1;
} else if (isSoftHandCode(trainingHand.code)) {
const currentHandMinValue = parseInt(trainingHand.code.split('/')[0], 10);
const softDifference = currentHandMinValue - playerHandValues[0];
if (isPlayerHandSoft) {
// E.g. Player hand = 3/13. Can reach 4/14+ but not 3/13- (equal or lower)
valueToReachThisHand = softDifference > 0 ? softDifference : -1;
} else {
// E.g. Player hand = 8. Can only 9/19 (soft hand)
valueToReachThisHand = softDifference === 1 ? softDifference : -1;
}
} else {
const currentHandHardValue = parseInt(trainingHand.code, 10);
const hardDifference = currentHandHardValue - playerHandValues[0];
if (isPlayerHandSoft) {
// E.g. Player hand = 5/15. Can reach 12-15 but not 11- (soft hand) neither
// 16+ (soft hand)
const makesSoftHand = playerHandValues[1] + hardDifference <= 21;
valueToReachThisHand =
!makesSoftHand && hardDifference > 1 && hardDifference <= 10
? hardDifference
: -1;
} else {
// E.g. Player hand = 7. Can reach 9-17 but not 7- (equal or lower),
// 8 (soft hand), 14 (split hand) neither 18+ (out of scope)
valueToReachThisHand =
hardDifference > 1 && // Lower & Soft hand
hardDifference <= 10 && // Out of scope
hardDifference !== playerHandValues[0] // Split hand
? hardDifference
: -1;
}
}
return isHandUntrainedForDealerSymbol && valueToReachThisHand > -1
? valueToReachThisHand
: -1;
})
.filter((value) => value > -1);
if (valuesToUntrainedHands.length > 0) {
nextCard = createCard(valueToSymbol(getRandomItem(valuesToUntrainedHands)));
}
}
return nextCard;
};
export const getHandEffectiveValue = (hand: Hand) => {
let effectiveValue = hand.values[0];
if (hand.values.some((v) => v < 22)) {
effectiveValue = [...hand.values].reverse().find((v) => v < 22)!;
}
return effectiveValue;
};
export const getHandValidValues = (hand: Hand): number[] => {
return hand.values.some((v) => v < 22) ? hand.values.filter((v) => v < 22) : [hand.values[0]];
};
export const handCodeToHand = (handCode: HandCode): Hand => {
const handSymbols = isSplitHandCode(handCode)
? getSplitHandSymbols(handCode)
: isSoftHandCode(handCode)
? getSoftHandSymbols(handCode)
: getHardHandSymbols(handCode);
return createHand(handSymbols.map((symbol) => createCard(symbol)));
};
export const handToHandCode = (hand: Hand): HandCode => {
const handSymbols = hand.cards.map((c) => symbolToSimpleSymbol(c.symbol));
const isSplitHand = handSymbols.length === 2 && handSymbols[0] === handSymbols[1];
return isSplitHand
? (handSymbols.join(',') as HandCode)
: (getHandValidValues(hand).join('/') as HandCode);
};
export const hasHoleCard = (hand: Hand) => hand.cards.length > 1 && hand.cards[1].isHoleCard;
const isAcesPair = (hand: Hand) =>
hand.cards.length === 2 &&
hand.cards[0].symbol === SimpleCardSymbol.Ace &&
hand.cards[1].symbol === SimpleCardSymbol.Ace;
export const isBlackjack = (hand: Hand, handsNumber: number) => {
return (
handsNumber === 1 &&
hand.cards.length === 2 &&
hand.values.length === 2 &&
hand.values[0] === 11 &&
hand.values[1] === 21
);
};
const isBust = (hand: Hand) => {
return getHandEffectiveValue(hand) > 21;
};
export const isDealerBlackjack = (hand: Hand) => {
const cardValues = getCardsValues(hand.cards, { peeking: true });
return (
hand.cards.length === 2 &&
cardValues.length === 2 &&
cardValues[0] === 11 &&
cardValues[1] === 21
);
};
export const isFinished = (hand: Hand, hands: Hand[], casinoRules: CasinoRules) => {
const isAcesPairHand = isAcesPair(hand);
return (
getHandEffectiveValue(hand) >= 21 ||
(areHandsSplitAces(hands) &&
((isAcesPairHand && !canSplit(hand, hands.length, casinoRules)) ||
(!isAcesPairHand && !casinoRules[CasinoRulesKeys.hitSplitAces])))
);
};
export const resolveHand = (
playerHand: Hand,
handsNumber: number,
dealerHand: Hand
): HandOutcome => {
const playerHandValue = getHandEffectiveValue(playerHand);
const dealerHandValue = getHandEffectiveValue(dealerHand!);
const handOutcome = isBust(playerHand)
? HandOutcome.bust
: isBlackjack(playerHand, handsNumber) && isBlackjack(dealerHand!, handsNumber)
? HandOutcome.push
: isBlackjack(playerHand, handsNumber)
? HandOutcome.blackjack
: isBlackjack(dealerHand!, handsNumber)
? HandOutcome.dealerWins
: isBust(dealerHand!)
? HandOutcome.playerWins
: playerHandValue > dealerHandValue
? HandOutcome.playerWins
: playerHandValue === dealerHandValue
? HandOutcome.push
: HandOutcome.dealerWins;
playerHand.outcome = handOutcome;
return handOutcome;
};
export const revealDealerHoleCard = (hand: Hand) => {
revealHoleCard(hand.cards[1]);
hand.values = getCardsValues(hand.cards);
}; |
#include <bits/stdc++.h>
using namespace std;
void printVector(vector<int> &nums) {
for (int i = 0; i < nums.size(); i++) {
cout << nums[i] << " ";
}
cout << endl;
}
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
unordered_map<int, int> frequencyMap;
vector<int> result;
int n = nums.size();
// create frequency map
for (int x : nums) {
frequencyMap[x]++;
}
for (auto const& element : frequencyMap) {
int curr_value = element.first;
int curr_freq = element.second;
pq.push(make_pair(curr_freq, curr_value));
while (pq.size() > k) {
pq.pop();
}
}
while (pq.size() > 0) {
result.push_back(pq.top().second);
pq.pop();
}
return result;
}
};
int main() {
vector<int> nums = {1, 1, 1, 2, 2, 3};
int k = 2;
Solution sol;
vector<int> ans = sol.topKFrequent(nums, k);
printVector(ans);
} |
Launch instances
Instances are virtual machines that run inside the cloud.
Before you can launch an instance, gather the following parameters:
- The **instance source** can be an image, snapshot, or block storage
volume that contains an image or snapshot.
- A **name** for your instance.
- The **flavor** for your instance, which defines the compute, memory,
and storage capacity of nova computing instances. A flavor is an
available hardware configuration for a server. It defines the size of
a virtual server that can be launched.
- Any **user data** files. A :doc:`user data </user/user-data>` file is a
special key in the metadata service that holds a file that cloud-aware
applications in the guest instance can access. For example, one application
that uses user data is the
`cloud-init <https://help.ubuntu.com/community/CloudInit>`__ system,
which is an open-source package from Ubuntu that is available on
various Linux distributions and that handles early initialization of
a cloud instance.
- Access and security credentials, which include one or both of the
following credentials:
- A **key pair** for your instance, which are SSH credentials that
are injected into images when they are launched. For the key pair
to be successfully injected, the image must contain the
``cloud-init`` package. Create at least one key pair for each
project. If you already have generated a key pair with an external
tool, you can import it into OpenStack. You can use the key pair
for multiple instances that belong to that project.
- A **security group** that defines which incoming network traffic
is forwarded to instances. Security groups hold a set of firewall
policies, known as *security group rules*.
- If needed, you can assign a **floating (public) IP address** to a
running instance to make it accessible from outside the cloud. See
:doc:`manage-ip-addresses`.
- You can also attach a block storage device, or **volume**, for
persistent storage.
.. note::
Instances that use the default security group cannot, by default, be
accessed from any IP address outside of the cloud. If you want those
IP addresses to access the instances, you must modify the rules for
the default security group.
After you gather the parameters that you need to launch an instance,
you can launch it from an :doc:`image<launch-instance-from-image>`
or a :doc:`volume<launch-instance-from-volume>`. You can launch an
instance directly from one of the available OpenStack images or from
an image that you have copied to a persistent volume. The OpenStack
Image service provides a pool of images that are accessible to members
of different projects.
Gather parameters to launch an instance
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Before you begin, source the OpenStack RC file.
#. Create a flavor.
Creating a flavor is typically only available to administrators of a cloud
because this has implications for scheduling efficiently in the cloud.
.. code-block:: console
$ openstack flavor create --ram 512 --disk 1 --vcpus 1 m1.tiny
#. List the available flavors.
.. code-block:: console
$ openstack flavor list
Note the ID of the flavor that you want to use for your instance::
+-----+-----------+-------+------+-----------+-------+-----------+
| ID | Name | RAM | Disk | Ephemeral | VCPUs | Is_Public |
+-----+-----------+-------+------+-----------+-------+-----------+
| 1 | m1.tiny | 512 | 1 | 0 | 1 | True |
| 2 | m1.small | 2048 | 20 | 0 | 1 | True |
| 3 | m1.medium | 4096 | 40 | 0 | 2 | True |
| 4 | m1.large | 8192 | 80 | 0 | 4 | True |
| 5 | m1.xlarge | 16384 | 160 | 0 | 8 | True |
+-----+-----------+-------+------+-----------+-------+-----------+
#. List the available images.
.. code-block:: console
$ openstack image list
Note the ID of the image from which you want to boot your instance::
+--------------------------------------+---------------------------------+--------+
| ID | Name | Status |
+--------------------------------------+---------------------------------+--------+
| 397e713c-b95b-4186-ad46-6126863ea0a9 | cirros-0.3.5-x86_64-uec | active |
| df430cc2-3406-4061-b635-a51c16e488ac | cirros-0.3.5-x86_64-uec-kernel | active |
| 3cf852bd-2332-48f4-9ae4-7d926d50945e | cirros-0.3.5-x86_64-uec-ramdisk | active |
+--------------------------------------+---------------------------------+--------+
You can also filter the image list by using :command:`grep` to find a specific
image, as follows:
.. code-block:: console
$ openstack image list | grep 'kernel'
| df430cc2-3406-4061-b635-a51c16e488ac | cirros-0.3.5-x86_64-uec-kernel | active |
#. List the available security groups.
.. code-block:: console
$ openstack security group list
.. note::
If you are an admin user, this command will list groups for all tenants.
Note the ID of the security group that you want to use for your instance::
+--------------------------------------+---------+------------------------+----------------------------------+
| ID | Name | Description | Project |
+--------------------------------------+---------+------------------------+----------------------------------+
| b0d78827-0981-45ef-8561-93aee39bbd9f | default | Default security group | 5669caad86a04256994cdf755df4d3c1 |
| ec02e79e-83e1-48a5-86ad-14ab9a8c375f | default | Default security group | 1eaaf6ede7a24e78859591444abf314a |
+--------------------------------------+---------+------------------------+----------------------------------+
If you have not created any security groups, you can assign the instance
to only the default security group.
You can view rules for a specified security group:
.. code-block:: console
$ openstack security group rule list default
#. List the available key pairs, and note the key pair name that you use for
SSH access.
.. code-block:: console
$ openstack keypair list
Launch an instance
~~~~~~~~~~~~~~~~~~
You can launch an instance from various sources.
.. toctree::
:maxdepth: 2
launch-instance-from-image.rst
launch-instance-from-volume.rst
launch-instance-using-ISO-image.rst |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.