text
stringlengths 184
4.48M
|
---|
<?php
namespace Setting\Bundle\ToolBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Setting\Bundle\ToolBundle\Entity\Course;
use Setting\Bundle\ToolBundle\Form\CourseType;
/**
* Course controller.
*
*/
class CourseController extends Controller
{
/**
* Lists all Course entities.
*
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('SettingToolBundle:Course')->findAll();
return $this->render('SettingToolBundle:Course:index.html.twig', array(
'entities' => $entities,
));
}
/**
* Creates a new Course entity.
*
*/
public function createAction(Request $request)
{
$entity = new Course();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
$this->get('session')->getFlashBag()->add(
'success',"Data has been inserted successfully"
);
return $this->redirect($this->generateUrl('course_new'));
}
return $this->render('SettingToolBundle:Course:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
/**
* Creates a form to create a Course entity.
*
* @param Course $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Course $entity)
{
$form = $this->createForm(new CourseType(), $entity, array(
'action' => $this->generateUrl('course_create'),
'method' => 'POST',
'attr' => array(
'class' => 'horizontal-form',
'novalidate' => 'novalidate',
)
));
return $form;
}
/**
* Displays a form to create a new Course entity.
*
*/
public function newAction()
{
$entity = new Course();
$form = $this->createCreateForm($entity);
return $this->render('SettingToolBundle:Course:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
/**
* Finds and displays a Course entity.
*
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('SettingToolBundle:Course')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Course entity.');
}
$deleteForm = $this->createDeleteForm($id);
return $this->render('SettingToolBundle:Course:show.html.twig', array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
));
}
/**
* Displays a form to new an existing Course entity.
*
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('SettingToolBundle:Course')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Course entity.');
}
$newForm = $this->createnewForm($entity);
$deleteForm = $this->createDeleteForm($id);
return $this->render('SettingToolBundle:Course:new.html.twig', array(
'entity' => $entity,
'form' => $newForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Creates a form to new a Course entity.
*
* @param Course $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createnewForm(Course $entity)
{
$form = $this->createForm(new CourseType(), $entity, array(
'action' => $this->generateUrl('course_update', array('id' => $entity->getId())),
'method' => 'PUT',
'attr' => array(
'class' => 'horizontal-form',
'novalidate' => 'novalidate',
)
));
return $form;
}
/**
* news an existing Course entity.
*
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('SettingToolBundle:Course')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Course entity.');
}
$deleteForm = $this->createDeleteForm($id);
$newForm = $this->createnewForm($entity);
$newForm->handleRequest($request);
if ($newForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('course_new', array('id' => $id)));
}
return $this->render('SettingToolBundle:Course:new.html.twig', array(
'entity' => $entity,
'form' => $newForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Deletes a Course entity.
*
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('SettingToolBundle:Course')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Course entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('course'));
}
/**
* Creates a form to delete a Course entity by id.
*
* @param mixed $id The entity id
*
* @return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('course_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Delete'))
->getForm()
;
}
/**
* Status a Page entity.
*
*/
public function statusAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->handleRequest($request);
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('SettingToolBundle:Course')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find District entity.');
}
$status = $entity->getStatus();
if($status == 1){
$entity->setStatus(0);
} else{
$entity->setStatus(1);
}
$em->flush();
$this->get('session')->getFlashBag()->add(
'success',"Status has been changed successfully"
);
return $this->redirect($this->generateUrl('course'));
}
} |
package com.empresa.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.empresa.entity.Deporte;
import com.empresa.entity.Modalidad;
import com.empresa.service.DeporteService;
import com.empresa.service.ModalidadService;
@Controller
public class ModalidadRegistraController {
@Autowired
private DeporteService deporteService;
@Autowired
private ModalidadService modalidadService;
@GetMapping(value = "/verRegistraModalidad")
public String verAlumno() {
return "registraModalidad";
}
@GetMapping(value = "/listaDeporte")
@ResponseBody
public List<Deporte> cargaDeporte() {
return deporteService.listarTodos();
}
@PostMapping("/registraModalidad")
@ResponseBody
public Map<?, ?> registra(Modalidad obj) {
HashMap<String, String> map = new HashMap<String, String>();
List<Modalidad> lstModalidad = modalidadService.buscaPorDeporteEnSede(
obj.getSede(),
obj.getDeporte().getIdDeporte());
if (!CollectionUtils.isEmpty(lstModalidad)) {
Modalidad objFind = lstModalidad.get(0);
map.put("MENSAJE", "Ya existe el deporte " +objFind.getDeporte().getNombre()
+" en la sede " + obj.getSede());
return map;
}
Modalidad objSalida = modalidadService.insertaModalidad(obj);
if (objSalida == null) {
map.put("MENSAJE", "Error en el registro");
} else {
map.put("MENSAJE", "Registro exitoso");
}
return map;
}
@GetMapping("/buscaPorNombreModalidad")
@ResponseBody
public String validaNombre(String nombre) {
List<Modalidad> lstModalidad = modalidadService.listaPorNombre(nombre);
if (CollectionUtils.isEmpty(lstModalidad)) {
return "{\"valid\" : true }";
} else {
return "{\"valid\" : false }";
}
}
} |
https://hackr.io/blog/microservices-interview-questions
https://hackr.io/blog/web-services-interview-questions
Q11: What is a Resource in Restful web services?
Q12: What are different HTTP Methods supported in Restful Web Services?
Q13: Mention what are the HTTP methods supported by REST?
Q14: Explain the architectural style for creating web API?
Q15: Mention whether you can use GET request instead of PUT to create a resource?
Q16: Mention what are resources in a REST architecture?
Q18: Mention some key characteristics of REST?
Q19: What are the core components of a HTTP Request?
Q20: What is purpose of a URI in REST based webservices?
Q21: What are advantages of SOAP Web Services?
Q22: What are disadvantages of SOAP Web Services?
Q23: What is UDDI?
Q24: What are disadvantages of REST web services?
Q26: What is the use of Accept and Content-Type Headers in HTTP Request?
Q27: How would you choose between SOAP and REST web services?
Q30: Mention what is the difference between PUT and POST?
Q31: Mention what is the difference between RPC or document style web services? How you determine to which one to choose?
Q32: What is messaging in RESTful webservices?
Q33: What are the core components of a HTTP response?
Q34: What is addressing in RESTful webservices?
Q35: What are the best practices to create a standard URI for a web service?
Q36: What is statelessness in RESTful Webservices?
Q37: What are the disadvantages of statelessness in RESTful Webservices?
Q38: What are the best practices for caching?
Q39: What is the purpose of HTTP Status Code?
Q40: What is Payload?
Q41: Explain WSDL?
Q42: What are the primary security issues of web service?
Q43: Define SOA?
Q45: What are the best practices to design a resource representation?
Q49: What are the advantages of statelessness in RESTful Webservices?
Q50: What do you mean by idempotent operation?
Q51: Which type of Webservices methods are to be idempotent?
Q52: What should be the purpose of OPTIONS method of RESTful web services?
Q53: Which header of HTTP response provides control over caching?
Q54: Explain Cache-control header
Q62: What should be the purpose of HEAD method of RESTful web services?
Q63: What are the best practices to be followed while designing a secure RESTful web service?
Q64: Enlist some important constraints for RESTful web services.
Q66: What is Open API Initiative?
Q67: Name some best practices for better RESTful API design
Q4: What Are The Fundamentals Of Microservices Design?
Q5: What are the features of Microservices?
Q6: How does Microservice Architecture work?
Q7: What is the difference between Monolithic, SOA and Microservices Architecture?
Q8: What are the challenges you face while working Microservice Architectures?
Q9: How can we perform Cross-Functional testing?
Q10: What are main differences between Microservices and Monolithic Architecture?
Q11: What are the standard patterns of orchestrating microservices?
Q12: What are smart endpoints and dumb pipes?
Q13: What is the difference between a proxy server and a reverse proxy server?
Q14: Whether do you find GraphQL the right fit for designing microservice architecture?
Q15: What is Idempotence?
Q16: What are the pros and cons of Microservice Architecture?
Q17: What do you understand by Distributed Transaction?
Q18: What do you understand by Contract Testing?
Q19: What is the role of an architect in Microservices architecture?
Q20: Can we create State Machines out of Microservices?
Q21: Explain what is the API Gateway pattern
Q22: Mention some benefits and drawbacks of an API Gateway
Q23: What is Materialized View pattern and when will you use it?
Q24: How should the various services share a common DB Schema and code?
Q25: What Did The Law Stated By Melvin Conway Implied?
Q26: Name the main differences between SOA and Microservices?
Q27: What is the difference between cohesion and coupling?
Q28: What is a Consumer-Driven Contract (CDC)?
Q29: What are Reactive Extensions in Microservices?
Q30: What is the most accepted transaction strategy for microservices
Q31: What does it mean that shifting to microservices creates a run-time problem?
Q32: Why would one use sagas over 2PC and vice versa?
Q33: Provide an example of "smart pipes" and "dumb endpoint"
Q34: How would you implement SSO for Microservice Architecture?
Microservices Interview Questions and Answers
The questions and answers listed here have been compiled from many resources off the internet. This should not be considered as the ultimate guide for microservices interview. Please acquire in-depth knowledge in this field and consult more books and resource guides for connecting questions in this regard.
Question: What do you understand by Microservices?
Answer: Microservices or more appropriately Microservices Architecture is an SDLC approach based on which large applications are built as a collection of small functional modules. These functional modules are independently deployable, scalable, target specific business goals, and communicate with each other over standard protocols. Such modules can also be implemented using different programming languages, have their databases, and deployed on different software environments. Each module here is minimal and complete.
Question: What are the main features of Microservices?
Answer: Microservices have the following main features:
Multiple Individually Deployable Components.
Service Distribution based on Business Capabilities.
Decentralized Data Management.
DevOps Implementation.
Technical Independence.
Hidden Component Complexity to avoid unnecessary microservices dependencies.
features of Microservices
Question: What are the main components of Microservices?
Answer: The main components for a Microservice Architecture are:
Containers, Clustering, and Orchestration
IaC [Infrastructure as Code Conception]
Cloud Infrastructure
API Gateway
Enterprise Service Bus
Service Delivery
Question: How does a Microservice Architecture work?
Answer: Under a microservice architecture, an application is simplified into multiple modules that independently perform the single precise standalone task:
Are fragmented into loosely coupled various modules, each of which performs a distinct function.
It can be or are distributed across clouds and data centers.
Implement each module as an independent service/process which can be replaced, updated, or deleted without disrupting the rest of the application.
Under microservice architecture, an application can grow along with its requirements.
Question: What are the fundamental characteristics of a Microservices Design?
Answer:
Services split up and organized around business functionality.
Separate modules handled and owned by different development teams.
Decentralized Framework.
Maintenance of respective modules by respective development teams.
Separate modules may be maintained by different databases.
Modules in a Microservice Architecture are separately deployable. They can be updated, enhanced, or deleted without disrupting the entire architecture.
Real-time monitoring of the application.
Question: What are the main challenges in Microservice Deployment?
Answer: The challenges in Microservice can be both technical as well as functional.
From the point of business, the main challenges are:
Require heavy investment
Heavy Infrastructure Setup
Excessive Planning for managing operations overhead
Staff Selection and maintenance.
From a technical standpoint –
Communication between different microservices in the application.
Component automation
Application maintenance
Configuration Management
Heavy Operations Overhead
Deployment Challenges
Testing and Debugging Challenges
Question: What are the advantages and disadvantages of Microservices?
Answer:
Advantages:
Improved Scalability
Fault Isolation
Localized Complexity
Increased Agility
Simplified Debugging & Maintenance
Better correspondence of developers with business users.
Smaller development teams
Better scope for technology upgradation.
Disadvantages:
Complicated as a whole.
Requires accurate pre-planning
Modular dependencies are hard to calculate.
Less control over third party applications
Modular Interdependencies are challenging to track.
More opportunities for malicious intrusions.
Complete end-to-end testing is difficult.
Deployment Challenges.
Question: What are the different strategies of Microservices Deployment?
Answer:
Multiple Service Instance per Host: Run single or multiple service instances of the application on single/multiple physical/virtual hosts.
Service Instance per Host: Run a service instance per host.
Service Instance per Container: Run each service instance in its respective container.
Serverless Deployment: Package the service as a ZIP file and upload it to the Lambda function. The Lambda function is a stateless service that automatically runs enough micro-services to handle all requests.
Question: List the differences between Monolithic, SOA, and Microservices Architecture with an example for each.
Answer:
In Monolithic Architecture, all software components of the application are assembled and packed tightly. SOA [Service Oriented Architecture] is a collection of services that communicate with each other through simple data passing or activity coordination. Microservices Architecture is a collection of small functional modules. These functional modules are independently deployable, scalable, target specific business goals, and communicate with each other over standard protocols.
Question: What is Domain Driven Design?
Answer: Domain-Driven Design is an architectural style based on Object-Oriented Analysis Design concepts and principles. It helps in developing a complex system by connecting the related components of the software system into a continuously evolving system. Domain-Driven Design is based on three core principles:
Focus on the core domain and domain logic.
Base complex designs on models of the domain.
Regularly collaborate with the domain experts to improve the application model and resolve any emerging domain-related issues.
Question: What is the Spring Boot?
Answer: Spring Boot is an open-sourced, Java-based framework that provides its developers with an excellent platform for developing a stand-alone and production-grade spring application. It is easy to understand, increases productivity, and reduces development time. It automatically configures a claim based on the added dependencies of an application.
Question: How do you override a Spring Boot Project’s Default Properties?
Answer: Specify the properties in application.properties.
Spring MVC applications need the suffix and the prefix to be specified. This can be done by:
For suffix – spring.mvc.view.suffix: .jsp
For prefix – spring.mvc.view.prefix: /WEB-INF/
Question: What is the difference between Monolithic, SOA and Microservices Architecture?
Answer:
Monolithic Architecture: In this type of architecture, different components of an application like UI, business logic, data access layer are combined into a single platform or program.
SOA (Service Oriented Architecture): In this architecture, individual components are loosely coupled and perform a discrete function. There are two main roles – service provider and service consumer. In SOA type, modules can be integrated and reused, making it flexible and reliable.
Microservices Architecture: It is a type of SOA in which a series of autonomous components are built and combined to make an app. These components are integrated using APIs. This approach focuses on business priorities and capabilities and offers high agility, i.e. each component of the app can be built independently of the other.
Question: Difference between Cohesion and Coupling?
Answer: Coupling: it is the relationship between module A and another module B. Any module can be highly coupled (highly dependent), loosely coupled and uncoupled with other modules. The best coupling is loose coupling achieved through interfaces.
Cohesion: it is the relationship between 2 or more parts within a module. If a module has high cohesion, it means the module can perform a certain task with utmost efficiency on its own, without communication with other modules. High cohesion enhances the functional strength of a module.Cohesion and Coupling
Question: Mention the problems that are solved by Spring Cloud?
Answer: Spring cloud can solve the following problems:
Network issues, latency overhead, bandwidth issues, security issues and other issues with distributed systems
Redundancy issues that occur in distributed systems.
Balancing the distribution of load between resources like network links, CPU, clusters etc.
Performance issues because of operational overheads.
Service discovery issues to ensure smooth communication between services in a cluster.
Question: What is Distributed Transaction?
Answer: Distribution transaction has two or more network hosts that are engaged. Transactions are handled by a transaction manager that takes care of developing and handling transactions. If the transaction involves more than one peer, transaction managers of each peer communicate with each other using subordinate or superior relationships.
Same way, resources are handled by the resource manager that also coordinates with the distributed transaction coordinator for transaction atomicity and isolation.
Question: Explain end to end Microservices Testing?
Answer: It is a testing technique used to test the entire flow of an application using a business transaction. Since several components are involved in microservices architecture, these tests can cover the gaps during a unit or integration testing. It also gives end to end confidence, ensures that the network parameters are appropriately configured and helps microservices to evolve.
Question: What is Mike Cohn’s Test Pyramid?
Answer: The pyramid helps maximize automation at all levels of testing, i.e. unit testing, service level testing, UI testing. The pyramid indicates that while unit tests are faster and more isolated, UI tests, which are at the highest level, take time and focus on integration.Mike Cohn’s Test Pyramid
Question: How do you implement a Spring Security in a Spring Boot Application?
Answer:
Add spring-boot-starter-security in the file pom.xml.
Create a Spring config class that will override the required method while extending the WebSecurityConfigurerAdapter to achieve security in the application.
Question: How will you Configure Spring Boot Application Login?
Answer: Spring Boot Application Login can be configured by specifying the logging.level in the application. Properties file. It is usually pre-configured as console output.
Question: What is Spring Cloud?
Answer: While building a distributed system, there are a few problems that are encountered. They are Configuration Management, Service Discovery, Circuit breakers, and distributed sessions. Spring Boot is a collection of tools that provides solutions to such commonly encountered problems.
Question: What is an Actuator?
Answer: The actuator brings in production-ready features into an application. It is mainly used to expose operational information about the running application’s health, metrics, info, dump, env, etc. It uses HTTP endpoints or JMX beans to interact with it.
Question: What is a Container?
Answer: Containers are isolated workload environments in a virtualized operating system. It consists of an application and all the features and files required to run it. Each box is an independent environment and is not tied to the software on a physical environment, thus providing a solution for application portability.
Container
Question: What are Coupling and Cohesion?
Answer: The strength of dependencies between services in a microservice architecture is said to be coupling. Cohesion refers to the related logic between two or more services. The entire concept of microservices is based on the ability to deploy and update service while keeping other services intact. Hence, loose coupling and high cohesion is the key to a microservice design.
Question: What is PACT in Microservices Architecture?
Answer: A contract between a consumer application and a provider application is called a PACT. Each pact is a collection of interactions. It is an open-source tool that can be used to implement the Consumer-Driven Contract in Microservices.
Question: What is Contract Testing?
Answer: Contract Testing ensures that the explicit and implicit contracts of a microservice architecture work as expected. There are two perspectives to contract to test – Consumer and Provider. The consumer is the [application] entity using the microservice, and the provider is the [application] entity providing the service. Such services work under predefined specifications, and contract testing ensures so.
Question: What is OAuth?
Answer: OAuth stands for Open-standard Authorization Protocol or framework that describes how unrelated servers and services can safely allow authenticated access to their assets without sharing the initial related, single logon credential. This is also known as secure, third-party, user-agent, delegated authorization.
Question: What can you derive/understand from Conway’s Law?
Answer: Melvin Conway stated this idea in the late 1960s. This law implies that ‘organizations which design systems are constrained to produce designs which are copies of the communication structures of these organizations.” In simpler words, the team of people who design a piece of software will eventually make the design as per their perspective.
Question: What are the steps in an End-to-End Microservices Testing?
Answer: End-To-End testing of a microservice application ensures that every process in the form is running properly. This validates that the system as a whole is working properly. As the microservices application is built with multiple modules orchestrated dynamically, an end to end testing covers all the gaps between the services.
The steps to an end-to-end microservices testing are:
Define what you expect from an e2e testing.
Define the scope of the system to be tested.
Perform authentication in a test environment.
Choose a testing framework that addresses most of the issues.
Test Asynchronous flows
Automate Testing
Question: What is the difference between Mock & Stub?
Answer: A Mock is generally a dummy object where certain features are set into it initially. Its behavior mainly depends on these features, which are then tested.
A Stub is an object that helps in running the test. It functions in a fixed manner under certain conditions. This hard-coded behavior helps the stub to run the test.
Question: What can we derive from Mike Cohn’s Test Pyramid?
Answer: Mike Cohn’s Test Pyramid describes the type of automated tests required for software development. The Test Pyramid is only a metaphor that implies a grouping of tests based on their granularity. This Pyramid tells which kind of tests should be applied to different levels of the pyramid.
Mike Cohn’s test pyramid consists of three layers that a test suite should consist:
Unit Testing
Service Testing
User Interface Testing.
Two points to be derived from Cohn’s pyramid is that:
Define tests with different granularity
The higher in the level you get, the fewer tests you should have.
Question: How does Docker help in Microservices?
Answer: Microservices, as we know, are self-contained, individual units that perform only one business function, so much so that each unit can be considered an application on its own. The application development environment and application deployment environment are bound to vary in many aspects. This gives rise to deployment issues. Docker provides a static background for the application to run, thus avoiding deployment issues. It is, in fact, a containerization tool. It reduces overhead and deploys thousands of microservices on the same server. Docker ensures that an application microservices will run on their own environments and are entirely separate from their operating system.
Question: What is Canary Releasing?
Answer: Canary releasing is a technique by which new software versions are introduced by rolling out the updated version to a small subset of users before rolling it out to the entire infrastructure and making it available to everybody. This technique is so-called because it is based on canary releases in coal mines to alert miners when the toxic gases reach dangerous levels.
Question: What are the different types of credentials of a two-factor Authentication?
Answer: Two-factor authentication calls for a second round of authentication to an account login process. Entering a username – password is a one-factor authentication. Username – Password authentication and then say mobile number or a secret key authentication can be considered as a two - factor authentication.
The different types of credentials for two-factor authentication can be:
Something you know - A PIN, password or a pattern
Something you have – ID, ATM No., Phone No, or an OTP
Something you are – Your Biometrics.
2 Factor Authentication
Question: What is a Client Certificate?
Answer: A Client Certificate is a digital certificate that is used by client systems to make authenticated requests to a remote server. It plays a key role in many mutual authentication designs, providing strong assurances of a requester’s identity.
Question: What is a CDC [Consumer Driven Contract]?
Answer: Consumer-Driven Contracts are patterns for evolving services. Here, each consumer captures their provider in a separate contract. All these contracts are then shared with the provider, which helps them to gain an insight into the obligations they must fulfill for each individual client.
Question: What are non-deterministic tests, and how will you eliminate them?
Answer: NDT or Non-Deterministic are unreliable tests. Such tests sometimes pass and sometimes fail. When these tests fail, they are re-run to give. Non-Determinism from tests can be eliminated in the following ways:
Quarantine
Asynchronous
Remote Services
Isolation
Time
Resource Leaks
Question: What are Reactive Extensions in Microservices?
Answer: Reactive Extensions is a design approach through which results are collected by calling multiple services in order to compile a combined response. Also known as Rx, these calls can be synchronous or asynchronous.
Question: What is the role of RESTful APIs in Microservices?
Answer: A microservice is based on the concept where all it's component services require to interact with one another to complete the business functionality. This requires each microservice to have an interface. RESTful APIs provide a logical model for building these interfaces. It is based on the open networking principles of the Web. Thus, it serves as the most critical enabler of microservices.
Question: What is Eureka in Microservices?
Answer: Eureka is alternatively known as the Netflix Service Discovery Server. It uses Spring Cloud and is not heavy on the application development process.
Question: How will you balance the server-side load by utilizing Spring Cloud?
Answer: The server-side load balancing can be done by using Netflix Zuul. It is also known as a JVM based router.
Question: When will you see fit to use the Netflix Hystrix?
Answer: Hystrix is an error tolerance and latency library. Hystrix mainly isolates the access points. It also makes sure that all 3rd Party libraries and services are restricted. Thus, we can use Hystrix to ensure that an application runs efficiently and avoids the kind of failures that occur in distributed systems.
Question: What is Spring Batch Framework?
Answer: Spring Batch is an open-source framework for batch processing – execution of a series of jobs. Spring Batch provides classes and APIs to read/write resources, transaction management, job processing statistics, job restart, and partitioning techniques to process high volume data.
Question: What is Tasklet, and what is a Chunk?
Answer: The Tasklet is a simple interface with one method to execute. A tasklet can be used to perform single tasks like running queries, deleting files, etc. In Spring Batch, the tasklet is an interface that can be used to perform unique tasks like clean or set up resources before or after any step execution.
Spring Batch uses a ‘Chunk Oriented’ processing style within its most common implementation. Chunk Oriented Processing refers to reading the data one at a time and creating chunks that will be written out, within a transaction boundary.
Question: How will you deploy Exception Handling in Microservices?
Answer: If an exception occurs while processing an HTTP request, you need to catch the exception in your controller or service and return an appropriate ResponseEntity manually. Here are some thumb rules for exception handling.
Add @ResponseStatus for exceptions that you write.
For all other exceptions, implement an @ExceptionHandler method on a @ControllerAdvice class or use an instance of SimpleMappingExceptionResolver.
For Controller specific exceptions, add @ExceptionHandler methods to your controller.
Point to be noted is that @ExceptionHandler methods on the controller are always selected before those on any @ControllerAdvice instance. It is undefined in what order ControllerAdvices are processed.
Question: How can you access RESTful Microservices?
Answer: Considering the microservice architecture concept, each microservice needs to have an interface. Based on the principles of open networking of the Web, RESTful APIs provide the most logical model for building interfaces between the various components of the microservices architecture. RESTful APIs can be accessed in two ways:
Using a REST Template that is load balanced.
I am using multiple microservices.
Question: How do independent Microservices communicate with each other?
Answer: Microservices can communicate with each other through:
HTTP for traditional Request-Response.
Websockets for streaming.
Brokers or Server Programs running Advanced Routing Algorithms.
For message brokers, RabbitMQ, Nats, Kafka, etc., can be used, each built for a particular message semantic. Another way is to use Backend As A Service like Space Cloud, which automates the entire backend.
Question: What is Semantic Monitoring?
Answer: Semantic Monitoring or Synthetic Monitoring is running a subset of the application’s automated tests against the live production system. These results are monitored, and alerts are generated in case of failures. Semantic Monitoring approaches microservice monitoring from the business transaction perspective. Instead of monitoring each component, its semantic monitoring ascertains how well the transaction performs for business and the users. It also detects the faulty service layer and the corresponding microservice instance, all at the same flow. This approach allows for faster triaging and reduces the meantime to repair.
Question: How do you perform security testing of Microservices?
Answer: Microservices Application is a collection of smaller, independent, functional modules that may be developed in different programming languages, have different data sources, and run on different operating systems. This makes testing of the microservices as a whole a very tough task. The different pieces/modules need to be tested independently. There are three common procedures for this.
Code Scanning: In order to ensure that every line of code is bug-free and can be replicated.
Flexibility: The security protocols should be flexible as per the requirements of the system.
Adaptability: The security protocols should be adaptable to the malicious intrusions.
Question: What do you understand by Idempotence, and how is it used?
Answer: Idempotence refers to the repeated performing of a task even though the end result remains the same. It is used mostly as a data source or a remote service in a way that when it receives the instruction more than once, it processes the instruction only once.
Question: What are the uses of Reports and Dashboards in Microservices environments?
Answer: Reports and Dashboards are generally used to monitor a system. For microservices Reports and Dashboards help to:
Find which microservice support which resource.
Find out the services that are impacted whenever changes in components are made/occur.
Provide an easy point of access for documentation purposes.
Review versions of the deployed components.
Obtain compliance from the components.
Question: What are the tools that can be considered for managing a microservice architecture?
Answer: The main tools that can be used to build/manage a microservice architecture are:
MongoDB: It is a document-based open-source distributed database. Here data is stored in JSON format with a different structure for different documents. It also supports a lot of programming languages like C, C++, C#, PERL, PHP, Python, Java, Ruby, Scala, etc.
Elasticsearch: It is a full-text search engine.
KAFKA: It is an event queue system. All transactions are processed via the event queue, thus avoiding the web like random interactions between different services. Kafka renders a microservice architecture robust and clean.
JENKINS: It is an automation tool that enables Continuous Integration and Continuous Development. It supports many plugins and easily integrates with almost every tool.
DOCKER: The application development environment and application deployment environment are bound to vary in many aspects. This gives rise to deployment issues. Docker provides a static background for the application to run, thus avoiding deployment issues.
KUBERNETES: With thousands of services running in an application, Kubernetes, as an engine orchestrates the entire process.
JAEGER: It is an open-source end to end distributed tracing tool. Jaeger monitors distributed transactions, helps in performance optimization, and finds the dependencies between services. It also gives the root cause analysis.
FLUENT: In a multiservice architecture, where all the different systems are managed via different programming languages, different databases, and run in different operating systems, logging in, and keeping track of it is a significant issue. Fluentd provides a single logging layer and simplifies this issue. Logs can be also be collected and aggregated onto a data source.
PROMETHEUS: It is a monitoring tool, which helps to check if all services are working fine when the application is deployed. It is a time-series data store. It collects metrics from an application and displays it in a graphical format.
grafana: Grafana provides analytics and monitoring into different visualization formats like graphs, charts, tables, etc.
NGINX: It acts as a reverse proxy. It acts as a single point entry through which all the API calls are made.
Question: How do you create State Machines out of Microservices?
Answer: Each microservice owning its database is an independently deployable program. This enables the creation of State Machines by which we can specify different states and events for a particular microservice.
Question: What are the most common mistakes while transitioning to Microservices?
Answer:
Failure to outline the main challenges.
I am rewriting already existing programs.
Vague definitions of responsibilities, timeline, and boundaries.
Failure to identify and implement automation.
Question: Where is the WebMVC Test Annotation used?
Answer: WebMvcTest Annotation is used for unit testing Spring MVC Applications, where the test objective is to focus on Spring MVC Components.
Ex: @WebMvcTest(value = ToTestController.class, secure = false)
In the above example, the intention is to launch the ToTestController. All other controllers and mappings will not be launched when this unit test is executed.
Question: Give one/a few examples of microservices implementation.
Answer: Netflix, Paypal, Amazon, eBay, Twitter, and many other large-scale websites have started as monolithic and evolved into a microservices architecture. |
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:sudoo/app/base/base_bloc.dart';
import 'package:sudoo/app/model/category_callback.dart';
import 'package:sudoo/app/model/product_info_action_callback.dart';
import 'package:sudoo/app/pages/product/product_list/product_list_data_source.dart';
import 'package:sudoo/app/widgets/loading_view.dart';
import 'package:sudoo/domain/model/discovery/category.dart';
import 'package:sudoo/domain/model/discovery/upsert_product.dart';
import 'package:sudoo/domain/repository/category_repository.dart';
import 'package:sudoo/domain/repository/product_repository.dart';
import 'package:sudoo/extensions/list_ext.dart';
import '../../../../domain/model/discovery/category_product.dart';
class ProductListBloc extends BaseBloc implements CategoryCallback, ProductInfoActionCallback {
final ProductRepository productRepository;
final CategoryRepository categoryRepository;
late ProductListDataSource productDataSource;
final LoadingViewController loadingController = LoadingViewController();
final ValueNotifier<int> totalProducts = ValueNotifier(0);
final List<Category> categories = List.empty(growable: true);
int _offset = 0;
final int _limit = 20;
ProductListBloc(
this.productRepository,
this.categoryRepository,
) {
productDataSource = ProductListDataSource(
loadMore: loadMore,
categoryCallback: this,
productActionCallback: this,
patchProduct: patchProduct,
);
}
@override
void onDispose() {
productDataSource.dispose();
}
@override
void onInit() {
getCategories();
loadMore();
}
Future<void> loadMore() async {
final result = await productRepository.getProducts(_offset, _limit);
if (result.isSuccess) {
final pagination = result.get();
productDataSource.addProducts(pagination.products);
_offset = pagination.pagination.offset;
totalProducts.value = pagination.pagination.total;
} else {
showErrorMessage(result.requireError());
}
}
Future<void> navigateToProductDetail(String productId) async {}
Future<UpsertProduct> patchProduct(UpsertProduct product) async {
final result = await productRepository.patchProduct(product);
if (result.isSuccess) {
return Future.value(result.get());
} else {
showErrorMessage(result.requireError());
return Future.error(result.requireError());
}
}
@override
Future<List<Category>> getCategoriesOfProduct(String productId) async {
print("Sudoo => getCategoriesOfProduct: $productId");
final result = await productRepository.getCategories(productId);
return result.getDataOrNull().orEmpty;
}
Future<List<Category>> getCategories() async {
final result = await categoryRepository.getCategories();
if (result.isSuccess) {
categories.clear();
categories.addAll(result.get());
return Future.value(result.get());
} else {
showErrorMessage(result.requireError());
return Future.error(result.requireError());
}
}
@override
Future<CategoryProduct> upsertCategoryToProduct(
CategoryProduct categoryProduct,
) async {
final result =
await productRepository.upsertCategoryToProduct(categoryProduct);
if (result.isSuccess) {
return Future.value(result.get());
} else {
showErrorMessage(result.requireError());
return Future.error(result.requireError());
}
}
@override
Future<CategoryProduct> deleteCategoryToProduct(
CategoryProduct categoryProduct,
) async {
final result =
await productRepository.deleteCategoryToProduct(categoryProduct);
if (result.isSuccess) {
return Future.value(result.get());
} else {
showErrorMessage(result.requireError());
return Future.error(result.requireError());
}
}
@override
List<Category> getCategoriesWithout(List<Category> categories) {
final categoryIds = categories.map((e) => e.categoryId).toList();
return this
.categories
.where((element) => !categoryIds.contains(element.categoryId))
.toList();
}
@override
Future<void> deleteProduct(String productId) async {
final result = await productRepository.deleteProduct(productId);
if (result.isSuccess) {
productDataSource.deleteProduct(result.get() as String);
} else {
showErrorMessage(result.requireError());
}
}
@override
void manageImages() {
}
@override
Future<void> viewDetailProduct(String productId) async {
navigateToProductDetail(productId);
}
} |
import { BrowserModule } from '@angular/platform-browser';
import { ApplicationModule, NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { NavMenuComponent } from './components/nav-menu/nav-menu.component';
import { HomeComponent } from './components/home/home.component';
import { CounterComponent } from './components/counter/counter.component';
import { FetchDataComponent } from './components/fetch-data/fetch-data.component';
import { CustomerComponent } from './components/customer/customer.component';
import { NewcustomerComponent } from './components/newcustomer/newcustomer.component';
import { DeletecustomerComponent } from './components/deletecustomer/deletecustomer.component';
import { UpdatecustomerComponent } from './components/updatecustomer/updatecustomer.component';
import { CustomerService } from './services/customer.service';
import { ShowcustomerComponent } from './components/showcustomer/showcustomer.component';
import { StoreModule, StoreRootModule,Store } from '@ngrx/store';
import { Actions, Effect, EffectsModule, ofType } from '@ngrx/effects'
import { OrdersComponent } from './orders/orders.component';
import * as fromTransaction from '../app/store/transaction.reducer'
import * as fromCounter from '../app/store/counter.reducer';
import { reducers, metaReducers } from './reducers';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { environment } from '../environments/environment';
@NgModule({
declarations: [
AppComponent,
NavMenuComponent,
HomeComponent,
CounterComponent,
FetchDataComponent,
CustomerComponent,
NewcustomerComponent,
DeletecustomerComponent,
UpdatecustomerComponent,
ShowcustomerComponent
],
imports: [
BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
HttpClientModule,
FormsModule,
ReactiveFormsModule,
RouterModule.forRoot([
{ path: '', component: HomeComponent, pathMatch: 'full' },
{ path: 'customer', component: CustomerComponent },
{ path: 'new-customer', component: NewcustomerComponent },
{ path: 'update-customer/:id', component: UpdatecustomerComponent },
{ path: 'delete-customer/:id', component: DeletecustomerComponent },
{ path: 'show-customer/:id', component: ShowcustomerComponent },
{ path: 'counter', component: CounterComponent },
{ path: 'fetch-data', component: FetchDataComponent },
{ path: 'owner', loadChildren: () => import('./components/owner/owner.module').then(m => m.OwnerModule) },
]),
//EffectsModule.forFeature([TransactionEffects]),
//StoreModule.forRoot({game:fromTransaction.reducer,count:fromCounter.counterReducer}),
StoreModule.forRoot({count:fromCounter.counterReducer}),
StoreModule.forRoot(reducers, { metaReducers }),
!environment.production ? StoreDevtoolsModule.instrument() : [],
// EffectsModule.forRoot([CustomerEffect])
],
providers: [CustomerService],
bootstrap: [AppComponent]
})
export class AppModule { } |
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var context = undefined;
var main_gain = undefined;
const note_names = [
'Do',
'Do# / Réb',
'Ré',
'Ré# / Mib',
'Mi',
'Fa',
'Fa# / Solb',
'Sol',
'Sol# / Lab',
'La',
'La# / Sib',
'Si',
];
const modes = [
{name: 'majeur', intervals: [2, 2, 1, 2, 2, 2, 1]},
{name: 'mineur', intervals: [2, 1, 2, 2, 1, 2, 2]},
];
var melody = [
{pitch: 60, beats: 1},
{pitch: 60, beats: 1},
{pitch: 60, beats: 1},
{pitch: 62, beats: 1},
{pitch: 64, beats: 2},
{pitch: 62, beats: 2},
{pitch: 60, beats: 1},
{pitch: 64, beats: 1},
{pitch: 62, beats: 1},
{pitch: 62, beats: 1},
{pitch: 60, beats: 2},
];
const note_sequence = document.getElementById('note_sequence');
// ---- UTILITY FUNCTIONS ----
function db_to_amplitude(db) {
return Math.pow(10.0, db / 20.0);
}
function amplitude_to_db(ampl) {
return 20.0 * Math.log10(ampl);
}
function mod(n, m) {
return ((n % m) + m) % m;
}
function div(n, m) {
return Math.floor(n / m);
}
function midi_to_frequency(note) {
const a4_frequency = 440;
const a4_note = 69;
return Math.pow(2, (note - a4_note) / 12) * a4_frequency;
}
function midi_to_octave_and_semitones(midi_note) {
const c4 = 60;
const n = Math.floor((midi_note - c4) / 12);
const base_note = mod(midi_note - c4, 12);
const octave = 4 + n;
return {octave: octave, semitones: base_note};
}
function octave_and_semitones_to_midi(a) {
return (a.octave + 1) * 12 + a.semitones;
}
function random_int(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min); // The maximum is exclusive and the minimum is inclusive
}
function random_element(arr) {
return arr[random_int(0, arr.length)];
}
// ----------------
function play_note(note, volume, time, duration) {
const osc = new OscillatorNode(context, {frequency: midi_to_frequency(note), type: 'triangle'});
const gain_node = new GainNode(context, {});
const attack = .01;
const decay = .05;
const release = .05;
const sustain = duration - attack - decay - release;
const sustain_rate = .8;
osc.frequency.setValueAtTime(midi_to_frequency(note), time);
gain_node.gain.setValueAtTime(0, time);
gain_node.gain.linearRampToValueAtTime(volume, time + attack);
gain_node.gain.linearRampToValueAtTime(volume * sustain_rate, time + attack + decay);
gain_node.gain.setValueAtTime(volume * sustain_rate, time + attack + decay + sustain);
gain_node.gain.linearRampToValueAtTime(0, time + attack + decay + sustain + release);
osc.connect(gain_node).connect(main_gain);
osc.start(time);
osc.stop(time + duration);
}
function midi_pitch_to_base_note(midi_pitch) {
const result = mod(midi_pitch, 12);
console.assert(result >= 0 && result < 12);
return result;
}
function get_next_note_choices(base, max_interval, scale_semitones) {
const choices = [base];
for (const direction of [-1, 1]) {
var interval = 0;
var current = {degree: base.degree, octave: base.octave};
while (Math.abs(interval) <= max_interval) {
const prev_pos = current.degree;
const prev_octave = current.octave;
current.degree += direction;
current.octave += div(current.degree, scale_semitones.length);
current.degree = mod(current.degree, scale_semitones.length);
interval += (scale_semitones[current.degree] - scale_semitones[prev_pos]) + 12 * (current.octave - prev_octave);
if (Math.abs(interval) <= max_interval) {
choices.push({degree: current.degree, octave: current.octave});
}
}
}
return choices;
}
function generate_melody(length, max_interval, scale_semitones, first_degree) {
const melody = [{octave: 0, degree: first_degree}];
for (var i = 1; i < length; i++) {
const prev = melody[melody.length - 1];
melody.push(random_element(get_next_note_choices(prev, max_interval, scale_semitones)));
}
return melody;
}
function regen_melody() {
const melody_length = parseInt(document.getElementById('melody_length').value);
const max_interval = parseInt(document.getElementById('max_interval').value);
const key_value = document.getElementById('key').value;
var mode_index;
var key_index;
if (key_value === 'random') {
mode_index = random_int(0, modes.length);
key_index = random_int(0, 12);
} else {
console.log('key_value = ', key_value);
[mode_index, key_index] = JSON.parse(key_value);
}
console.log(mode_index);
console.log(key_index);
const scale_intervals = modes[mode_index].intervals;
const scale_semitones = [0];
for (const i of scale_intervals) {
scale_semitones.push(scale_semitones[scale_semitones.length - 1] + i)
}
const last = scale_semitones.pop(); // remove last element
console.assert(last === 12);
console.assert(scale_semitones.length === 7);
var first;
if (document.getElementById('tonic').checked) {
first = 0;
} else {
first = random_int(0, scale_intervals.length);
}
const midi_base = 60 + key_index;
melody = generate_melody(melody_length, max_interval, scale_semitones, first).map((x) => {
const pitch = midi_base + x.octave * 12 + scale_semitones[x.degree];
return {pitch: pitch, beats: 1};
});
}
function refresh_melody() {
note_sequence.replaceChildren();
for (var i = 0; i < melody.length; i++) {
const note = melody[i];
const pitch_box = document.createElement('select');
const opt = document.createElement('option');
opt.value = undefined;
opt.text = 'Choisir une note...';
pitch_box.appendChild(opt);
for (var j = 0; j < note_names.length; j++) {
const opt = document.createElement('option');
opt.value = j;
opt.text = note_names[j];
pitch_box.appendChild(opt);
}
pitch_box.classList.add('pitch_box');
if (i == 0) {
pitch_box.disabled = true;
pitch_box.classList.add('valid');
pitch_box.value = midi_pitch_to_base_note(melody[i].pitch);
pitch_box.text = note_names[pitch_box.value];
}
note_sequence.appendChild(pitch_box);
}
var txt = '';
for (var i = 0; i < melody.length; i++) {
txt += note_names[midi_pitch_to_base_note(melody[i].pitch)];
txt += ', ';
}
/* document.getElementById('debug_text').innerText = txt; */
}
function create_audio_context_if_not_exists() {
if (context === undefined) {
context = new AudioContext();
main_gain = new GainNode(context, {gain: 1});
main_gain.connect(context.destination);
}
}
function play_melody() {
create_audio_context_if_not_exists();
const bpm = parseInt(document.getElementById('bpm').value);
let t = context.currentTime + .05; // add a bit of delay to avoid artefacts
for (const note of melody) {
const duration = 60 * (note.beats / bpm);
play_note(note.pitch, 1, t, duration);
t += duration;
}
}
function midi_note_to_name(midi_note) {
const a = midi_to_octave_and_semitones(midi_note);
return note_names[a.semitones] + a.octave.toString();
}
// ---- Code that runs on first page load ----
{
refresh_melody();
const regen_button = document.getElementById('regen_button');
regen_button.addEventListener('click', () => {
regen_melody();
refresh_melody();
play_melody();
});
const play_button = document.getElementById('play_button');
play_button.addEventListener('click', () => {
play_melody();
});
const validate_button = document.getElementById('validate_button');
validate_button.addEventListener('click', () => {
for (var i = 0; i < melody.length; i++) {
const pitch_box = note_sequence.children[i];
const chosen_value = parseInt(pitch_box.value);
if (midi_pitch_to_base_note(melody[i].pitch) == chosen_value) {
pitch_box.classList.remove('invalid');
pitch_box.classList.add('valid');
} else {
pitch_box.classList.remove('valid');
pitch_box.classList.add('invalid');
}
}
});
const key_select = document.getElementById('key');
const opt = document.createElement('option');
opt.value = 'random';
opt.text = 'Aléatoire';
key_select.appendChild(opt);
for (var mode_index = 0; mode_index < modes.length; mode_index++) {
const mode = modes[mode_index];
for (var note = 0; note < note_names.length; note++) {
const opt = document.createElement('option');
opt.value = JSON.stringify([mode_index, note]);
opt.text = note_names[note] + ' ' + mode.name;
key_select.appendChild(opt);
}
}
key_select.value = JSON.stringify([0, 0]);
const volume_slider = document.getElementById('volume');
volume_slider.addEventListener('input', (event) => {
create_audio_context_if_not_exists();
const volume_value = event.target.value;
const dB = (volume_value - 1) * 30;
let gain = db_to_amplitude(dB);
const linear_range = .1;
if (volume_value < linear_range) {
gain = (volume_value / linear_range) * db_to_amplitude((linear_range - 1) * 30);
}
console.log(volume_value.toString() + ' ' + gain.toString());
main_gain.gain.linearRampToValueAtTime(gain, context.currentTime + .05);
});
} |
<?php
namespace App\Core\Models;
use App\Core\Application;
use App\Core\Contracts\UserInterface;
use App\Core\Models\Enum\ValidationRule;
use App\Core\Models\Traits\Validation;
use DateTime;
use Exception;
use PDO;
class User extends Model implements UserInterface
{
use Validation;
public int $id;
public string $firstName = '';
public string $lastName = '';
public string $email = '';
public string $password = '';
public string $confirmPassword = '';
public \DateTime $createdAt;
public \DateTime $updatedAt;
/**
* @throws Exception
*/
public static function findOne(array $array): static|null
{
$tableName = static::tableName();
$attributes = array_keys($array);
$sql = implode("AND ", array_map(fn($attr) => "$attr = :$attr", $attributes));
$statement = Application::$app->database->pdo->prepare("SELECT id, first_name AS firstName, last_name AS lastName, email, password, created_at AS createdAt, updated_at AS updatedAt FROM $tableName WHERE $sql");
foreach ($array as $key => $value) {
$statement->bindValue(":$key", $value);
}
$statement->execute();
// Fetch the data as an associative array
$data = $statement->fetch(PDO::FETCH_ASSOC);
if ($data) {
// Convert createdAt to a DateTime object
$data['createdAt'] = new DateTime($data['createdAt']);
// Convert updatedAt to a DateTime object
$data['updatedAt'] = new DateTime($data['updatedAt']);
// Create and populate the User object
$user = new static();
$user->loadData($data);
return $user;
}
return null;
}
public function validate(): bool|array
{
// clear errors
$this->errors = [];
// get the requirements
$requirements = $this->getRequirements();
foreach ($requirements as $field=>$rules){
$fieldName = $field;
foreach ($rules as $rule){
$ruleName = $rule;
$ruleValue = null;
if(is_array($rule)) {
$ruleName = $rule[0];
$ruleValue = $rule['ruleValue'];
}
$this->validateByRule($ruleName, $fieldName, $this->{$fieldName}, $ruleValue);
}
}
return $this->errors;
}
public function getRequirements(): array
{
return [
'firstName' => [
ValidationRule::required,
[ValidationRule::min, 'ruleValue' => 3],
[ValidationRule::max, 'ruleValue' => 60],
],
'lastName' => [
ValidationRule::required,
[ValidationRule::min, 'ruleValue' => 3],
[ValidationRule::max, 'ruleValue' => 60],
],
'email' => [
ValidationRule::required,
ValidationRule::email,
ValidationRule::unique,
],
'password' => [
ValidationRule::required,
[ValidationRule::min, 'ruleValue' => 8],
[ValidationRule::max, 'ruleValue' => 60],
],
'confirmPassword' => [
ValidationRule::required,
[ValidationRule::match, 'ruleValue' => 'password'],
],
];
}
// save the user to the database
public function save(): bool
{
$hashedPassword= password_hash($this->password, PASSWORD_DEFAULT);
$this->createdAt = new \DateTime();
$this->updatedAt = new \DateTime();
$sql = "INSERT INTO user (first_name, last_name, email, password, created_at, updated_at)
VALUES (:firstName, :lastName, :email, :password, :createdAt, :updatedAt)";
$statement = Application::$app->database->pdo->prepare($sql);
$statement->bindValue(':firstName', $this->firstName);
$statement->bindValue(':lastName', $this->lastName);
$statement->bindValue(':email', $this->email);
$statement->bindValue(':password', $hashedPassword);
$statement->bindValue(':createdAt', $this->createdAt->format('Y-m-d H:i:s'));
$statement->bindValue(':updatedAt', $this->updatedAt->format('Y-m-d H:i:s'));
return $statement->execute();
}
public static function tableName(): string
{
return 'user';
}
public static function primaryKey(): string
{
return 'id';
}
public function getID(): int
{
return $this->id;
}
public function getPassword(): string
{
return $this->password;
}
public function getDisplayName(): string
{
return $this->firstName . ' ' . $this->lastName;
}
} |
/* This file is part of the KDE project
Copyright (C) 2004 Adam Pigg <adam@piggz.co.uk>
Copyright (C) 2006 Jaroslaw Staniek <js@iidea.pl>
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 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef PQXXIMPORT_H
#define PQXXIMPORT_H
#include <migration/keximigrate.h>
//Kexi Includes
#include <kexidb/field.h>
#include <kexidb/connection.h>
#include <pqxx/pqxx>
namespace KexiMigration
{
class PqxxMigrate : public KexiMigrate
{
Q_OBJECT
KEXIMIGRATION_DRIVER
public:
PqxxMigrate(QObject *parent, const char *name, const QStringList &args = QStringList());
virtual ~PqxxMigrate();
protected:
//Driver specific function to return table names
virtual bool drv_tableNames(QStringList& tablenames);
//Driver specific implementation to read a table schema
virtual bool drv_readTableSchema(
const QString& originalName, KexiDB::TableSchema& tableSchema);
//Driver specific connection implementation
virtual bool drv_connect();
virtual bool drv_disconnect();
virtual tristate drv_queryStringListFromSQL(
const QString& sqlStatement, uint columnNumber, QStringList& stringList,
int numRecords = -1);
/*! Fetches single record from result obtained
by running \a sqlStatement.
\a firstRecord should be first initialized to true, so the method can run
the query at first call and then set it will set \a firstRecord to false,
so subsequent calls will only fetch records.
On success the result is stored in \a data and true is returned,
\a data is resized to appropriate size. cancelled is returned on EOF. */
//! @todo SQL-dependent!
virtual tristate drv_fetchRecordFromSQL(const QString& sqlStatement,
KexiDB::RowData& data, bool &firstRecord);
virtual bool drv_copyTable(const QString& srcTable,
KexiDB::Connection *destConn, KexiDB::TableSchema* dstTable);
private:
//lowlevel functions/objects
//database connection
pqxx::connection* m_conn;
//transaction
pqxx::nontransaction* m_trans;
//lowlevel result
pqxx::result* m_res;
//! Used in drv_fetchRecordFromSQL
pqxx::result::const_iterator m_fetchRecordFromSQL_iter;
//perform a query on the database
bool query(const QString& statement);
//Clear the result info
void clearResultInfo ();
pqxx::oid tableOid(const QString& tablename);
//Convert the pqxx type to a kexi type
KexiDB::Field::Type type(int t, const QString& fname);
//Find out the field constraints
//Return whether or not the field is a pkey
bool primaryKey(pqxx::oid table, int col) const;
//Return whether or not the field is unique
bool uniqueKey(pqxx::oid table, int col) const;
//Return whether or not the field is a foreign key
bool foreignKey(pqxx::oid table, int col) const;
//Return whether or not the field is not null
bool notNull(pqxx::oid table, int col) const;
//Return whether or not the field is not empty
bool notEmpty(pqxx::oid table, int col) const;
//Return whether or not the field is auto incrementing
bool autoInc(pqxx::oid table, int col) const;
};
}
#endif |
#ifdef USE_OPENCV
#include <opencv2/core/core.hpp>
#endif // USE_OPENCV
#include <string>
#include <vector>
#include "caffe/data_transformer.hpp"
#include "caffe/util/io.hpp"
#include "caffe/util/math_functions.hpp"
#include "caffe/util/rng.hpp"
namespace caffe {
template<typename Dtype>
DataTransformer<Dtype>::DataTransformer(const TransformationParameter& param,
Phase phase)
: param_(param), phase_(phase) {
// check if we want to use mean_file
if (param_.has_mean_file()) {
CHECK_EQ(param_.mean_value_size(), 0) <<
"Cannot specify mean_file and mean_value at the same time";
const string& mean_file = param.mean_file();
if (Caffe::root_solver()) {
LOG(INFO) << "Loading mean file from: " << mean_file;
}
BlobProto blob_proto;
ReadProtoFromBinaryFileOrDie(mean_file.c_str(), &blob_proto);
data_mean_.FromProto(blob_proto);
}
// check if we want to use mean_value
if (param_.mean_value_size() > 0) {
CHECK(param_.has_mean_file() == false) <<
"Cannot specify mean_file and mean_value at the same time";
for (int c = 0; c < param_.mean_value_size(); ++c) {
mean_values_.push_back(param_.mean_value(c));
}
}
}
template<typename Dtype>
void DataTransformer<Dtype>::Transform(const Datum& datum,
Dtype* transformed_data) {
const string& data = datum.data();
const int datum_channels = datum.channels();
const int datum_height = datum.height();
const int datum_width = datum.width();
const int crop_size = param_.crop_size();
const Dtype scale = param_.scale();
const bool do_mirror = param_.mirror() && Rand(2);
const bool has_mean_file = param_.has_mean_file();
const bool has_uint8 = data.size() > 0;
const bool has_mean_values = mean_values_.size() > 0;
CHECK_GT(datum_channels, 0);
CHECK_GE(datum_height, crop_size);
CHECK_GE(datum_width, crop_size);
Dtype* mean = NULL;
if (has_mean_file) {
CHECK_EQ(datum_channels, data_mean_.channels());
CHECK_EQ(datum_height, data_mean_.height());
CHECK_EQ(datum_width, data_mean_.width());
mean = data_mean_.mutable_cpu_data();
}
if (has_mean_values) {
CHECK(mean_values_.size() == 1 || mean_values_.size() == datum_channels) <<
"Specify either 1 mean_value or as many as channels: " << datum_channels;
if (datum_channels > 1 && mean_values_.size() == 1) {
// Replicate the mean_value for simplicity
for (int c = 1; c < datum_channels; ++c) {
mean_values_.push_back(mean_values_[0]);
}
}
}
int height = datum_height;
int width = datum_width;
int h_off = 0;
int w_off = 0;
if (crop_size) {
height = crop_size;
width = crop_size;
// We only do random crop when we do training.
if (phase_ == TRAIN) {
h_off = Rand(datum_height - crop_size + 1);
w_off = Rand(datum_width - crop_size + 1);
} else {
h_off = (datum_height - crop_size) / 2;
w_off = (datum_width - crop_size) / 2;
}
}
Dtype datum_element;
int top_index, data_index;
for (int c = 0; c < datum_channels; ++c) {
for (int h = 0; h < height; ++h) {
for (int w = 0; w < width; ++w) {
data_index = (c * datum_height + h_off + h) * datum_width + w_off + w;
if (do_mirror) {
top_index = (c * height + h) * width + (width - 1 - w);
} else {
top_index = (c * height + h) * width + w;
}
if (has_uint8) {
datum_element =
static_cast<Dtype>(static_cast<uint8_t>(data[data_index]));
} else {
datum_element = datum.float_data(data_index);
}
if (has_mean_file) {
transformed_data[top_index] =
(datum_element - mean[data_index]) * scale;
} else {
if (has_mean_values) {
transformed_data[top_index] =
(datum_element - mean_values_[c]) * scale;
} else {
transformed_data[top_index] = datum_element * scale;
}
}
}
}
}
}
template<typename Dtype>
void DataTransformer<Dtype>::Transform(const Datum& datum,
Blob<Dtype>* transformed_blob) {
// If datum is encoded, decoded and transform the cv::image.
if (datum.encoded()) {
#ifdef USE_OPENCV
CHECK(!(param_.force_color() && param_.force_gray()))
<< "cannot set both force_color and force_gray";
cv::Mat cv_img;
if (param_.force_color() || param_.force_gray()) {
// If force_color then decode in color otherwise decode in gray.
cv_img = DecodeDatumToCVMat(datum, param_.force_color());
} else {
cv_img = DecodeDatumToCVMatNative(datum);
}
// Transform the cv::image into blob.
return Transform(cv_img, transformed_blob);
#else
LOG(FATAL) << "Encoded datum requires OpenCV; compile with USE_OPENCV.";
#endif // USE_OPENCV
} else {
if (param_.force_color() || param_.force_gray()) {
LOG(ERROR) << "force_color and force_gray only for encoded datum";
}
}
const int crop_size = param_.crop_size();
const int datum_channels = datum.channels();
const int datum_height = datum.height();
const int datum_width = datum.width();
// Check dimensions.
const int channels = transformed_blob->channels();
const int height = transformed_blob->height();
const int width = transformed_blob->width();
const int num = transformed_blob->num();
CHECK_EQ(channels, datum_channels);
CHECK_LE(height, datum_height);
CHECK_LE(width, datum_width);
CHECK_GE(num, 1);
if (crop_size) {
CHECK_EQ(crop_size, height);
CHECK_EQ(crop_size, width);
} else {
CHECK_EQ(datum_height, height);
CHECK_EQ(datum_width, width);
}
Dtype* transformed_data = transformed_blob->mutable_cpu_data();
Transform(datum, transformed_data);
}
template<typename Dtype>
void DataTransformer<Dtype>::Transform(const vector<Datum> & datum_vector,
Blob<Dtype>* transformed_blob) {
const int datum_num = datum_vector.size();
const int num = transformed_blob->num();
const int channels = transformed_blob->channels();
const int height = transformed_blob->height();
const int width = transformed_blob->width();
CHECK_GT(datum_num, 0) << "There is no datum to add";
CHECK_LE(datum_num, num) <<
"The size of datum_vector must be no greater than transformed_blob->num()";
Blob<Dtype> uni_blob(1, channels, height, width);
for (int item_id = 0; item_id < datum_num; ++item_id) {
int offset = transformed_blob->offset(item_id);
uni_blob.set_cpu_data(transformed_blob->mutable_cpu_data() + offset);
Transform(datum_vector[item_id], &uni_blob);
}
}
#ifdef USE_OPENCV
template<typename Dtype>
void DataTransformer<Dtype>::Transform(const vector<cv::Mat> & mat_vector,
Blob<Dtype>* transformed_blob,
const bool is_video) {
if (is_video) {
const int mat_num = mat_vector.size();
const int num = transformed_blob->shape(0);
const int channels = transformed_blob->shape(1);
const int length = transformed_blob->shape(2);
const int height = transformed_blob->shape(3);
const int width = transformed_blob->shape(4);
bool mean_cube_subtracted = false;
// if mean cube file is given, 3d mean cube should be subtracted at this
// level
Dtype* mean = NULL;
const bool has_mean_file = param_.has_mean_file();
if (has_mean_file) {
CHECK(data_mean_.channels() == mat_vector[0].channels() ||
data_mean_.channels() == 1);
CHECK_EQ(mat_vector[0].rows, data_mean_.height());
CHECK_EQ(mat_vector[0].cols, data_mean_.width());
mean = data_mean_.mutable_cpu_data();
if ((1 != length) && (length == data_mean_.length())) {
mean_cube_subtracted = true;
} else {
CHECK_EQ(1, data_mean_.length()); // will be applied later
}
}
// mirroring and random cropping should not be done on each image
// individually as images come from a same video clip
rng_seed_ = caffe_rng_rand();
CHECK_GT(mat_num, 0) << "There is no MAT to add";
CHECK_EQ(num, 1) << "First dimension (batch number) must be 1";
CHECK_EQ(mat_num, length) <<
"The size of mat_vector must be equals to transformed_blob->shape(2)";
vector<int> uni_blob_shape(5);
uni_blob_shape[0] = 1;
uni_blob_shape[1] = channels;
uni_blob_shape[2] = 1;
uni_blob_shape[3] = height;
uni_blob_shape[4] = width;
Blob<Dtype> uni_blob(uni_blob_shape);
vector<int> indices(5);
for (int item_id = 0; item_id < mat_num; ++item_id) {
cv::Mat cv_img = mat_vector[item_id].clone();
/* Adam added
*
*/
/*CHECK(cv_img.depth() == CV_8U) << "Image data type must " <<
"be unsigned byte";*/
// mean cube subtraction for C3D data
if (mean_cube_subtracted) {
for (int c = 0; c < cv_img.channels(); ++c) {
for (int h = 0; h < cv_img.rows; ++h) {
for (int w = 0; w < cv_img.cols; ++w) {
int mean_index = ((c * length + item_id) * height + h) * width
+ w;
if(cv_img.depth()==CV_8U)
cv_img.at<cv::Vec3b>(h, w)[c] -= mean[mean_index];
if(cv_img.depth()==CV_16U)
cv_img.at<cv::Vec3w>(h, w)[c] -= mean[mean_index];
}
}
}
}
indices[0] = 0;
indices[1] = 0;
indices[2] = item_id;
indices[3] = 0;
indices[4] = 0;
int offset = transformed_blob->offset(indices);
uni_blob.set_cpu_data(transformed_blob->mutable_cpu_data() + offset);
Transform(cv_img, &uni_blob, mean_cube_subtracted, true);
}
} else {
const int mat_num = mat_vector.size();
const int num = transformed_blob->num();
const int channels = transformed_blob->channels();
const int height = transformed_blob->height();
const int width = transformed_blob->width();
CHECK_GT(mat_num, 0) << "There is no MAT to add";
CHECK_EQ(mat_num, num) <<
"The size of mat_vector must be equals to transformed_blob->num()";
Blob<Dtype> uni_blob(1, channels, height, width);
for (int item_id = 0; item_id < mat_num; ++item_id) {
int offset = transformed_blob->offset(item_id);
uni_blob.set_cpu_data(transformed_blob->mutable_cpu_data() + offset);
Transform(mat_vector[item_id], &uni_blob, false);
}
}
}
template<typename Dtype>
void DataTransformer<Dtype>::Transform(const cv::Mat& cv_img,
Blob<Dtype>* transformed_blob,
const bool force_no_mean,
const bool is_video) {
const int crop_size = param_.crop_size();
const int img_channels = cv_img.channels();
const int img_height = cv_img.rows;
const int img_width = cv_img.cols;
// Check dimensions.
const int channels = transformed_blob->channels();
const int height = transformed_blob->height();
const int width = transformed_blob->width();
const int num = transformed_blob->num();
CHECK_EQ(channels, img_channels);
CHECK_LE(height, img_height);
CHECK_LE(width, img_width);
CHECK_GE(num, 1);
/* Adam edited
*
*/
//CHECK(cv_img.depth() == CV_8U) << "Image data type must be unsigned byte";
const Dtype scale = param_.scale();
const bool do_mirror = param_.mirror() && Rand(2);
const bool has_mean_file = param_.has_mean_file();
const bool has_mean_values = mean_values_.size() > 0;
CHECK_GT(img_channels, 0);
CHECK_GE(img_height, crop_size);
CHECK_GE(img_width, crop_size);
Dtype* mean = NULL;
if (has_mean_file && !force_no_mean) {
CHECK_EQ(img_channels, data_mean_.channels());
CHECK_EQ(img_height, data_mean_.height());
CHECK_EQ(img_width, data_mean_.width());
mean = data_mean_.mutable_cpu_data();
}
if (has_mean_values && !force_no_mean) {
CHECK(mean_values_.size() == 1 || mean_values_.size() == img_channels) <<
"Specify either 1 mean_value or as many as channels: " << img_channels;
if (img_channels > 1 && mean_values_.size() == 1) {
// Replicate the mean_value for simplicity
for (int c = 1; c < img_channels; ++c) {
mean_values_.push_back(mean_values_[0]);
}
}
}
// For videos, re-use random seed to replicate randomness
// (e.g. same croppings, mirrorings)
if (is_video)
SetRandFromSeed(rng_seed_);
int h_off = 0;
int w_off = 0;
cv::Mat cv_cropped_img = cv_img;
if (crop_size) {
CHECK_EQ(crop_size, height);
CHECK_EQ(crop_size, width);
// We only do random crop when we do training.
if (phase_ == TRAIN) {
h_off = Rand(img_height - crop_size + 1);
w_off = Rand(img_width - crop_size + 1);
} else {
h_off = (img_height - crop_size) / 2;
w_off = (img_width - crop_size) / 2;
}
cv::Rect roi(w_off, h_off, crop_size, crop_size);
cv_cropped_img = cv_img(roi);
} else {
CHECK_EQ(img_height, height);
CHECK_EQ(img_width, width);
}
CHECK(cv_cropped_img.data);
Dtype* transformed_data = transformed_blob->mutable_cpu_data();
int top_index;
if(cv_cropped_img.depth()==CV_8U)
{
for (int h = 0; h < height; ++h) {
/*
* Adam edited
* don't use the uint16, we read uchar here!!!!!!!!!!!!!!!!
*/
const uchar* ptr = cv_cropped_img.ptr<uchar>(h);
int img_index = 0;
for (int w = 0; w < width; ++w) {
for (int c = 0; c < img_channels; ++c) {
if (do_mirror) {
top_index = (c * height + h) * width + (width - 1 - w);
} else {
top_index = (c * height + h) * width + w;
}
// int top_index = (c * height + h) * width + w;
Dtype pixel = static_cast<Dtype>(ptr[img_index++]);
if (has_mean_file && !force_no_mean) {
int mean_index = (c * img_height + h_off + h) * img_width + w_off + w;
transformed_data[top_index] =
(pixel - mean[mean_index]) * scale;
} else {
if (has_mean_values && !force_no_mean) {
// Adam edited label should not substract mean
transformed_data[top_index] = pixel*scale;
//(pixel - mean_values_[c]) * scale;
} else {
transformed_data[top_index] = pixel * scale;
}
}
}
}
}
}
if(cv_cropped_img.depth()==CV_16U)
{
for (int h = 0; h < height; ++h) {
/*
* Adam edited
* don't use the uint16, we read uchar here!!!!!!!!!!!!!!!!
*/
const ushort* ptr = cv_cropped_img.ptr<ushort>(h);
int img_index = 0;
for (int w = 0; w < width; ++w) {
for (int c = 0; c < img_channels; ++c) {
if (do_mirror) {
top_index = (c * height + h) * width + (width - 1 - w);
} else {
top_index = (c * height + h) * width + w;
}
// int top_index = (c * height + h) * width + w;
Dtype pixel = static_cast<Dtype>(ptr[img_index++]);
if (has_mean_file && !force_no_mean) {
int mean_index = (c * img_height + h_off + h) * img_width + w_off + w;
transformed_data[top_index] =
(pixel - mean[mean_index]) * scale;
} else {
if (has_mean_values && !force_no_mean) {
transformed_data[top_index] =
(pixel - mean_values_[c]) * scale;
} else {
transformed_data[top_index] = pixel * scale;
}
}
}
}
}
}
}
#endif // USE_OPENCV
template<typename Dtype>
void DataTransformer<Dtype>::Transform(Blob<Dtype>* input_blob,
Blob<Dtype>* transformed_blob) {
const int crop_size = param_.crop_size();
const int input_num = input_blob->num();
const int input_channels = input_blob->channels();
const int input_height = input_blob->height();
const int input_width = input_blob->width();
if (transformed_blob->count() == 0) {
// Initialize transformed_blob with the right shape.
if (crop_size) {
transformed_blob->Reshape(input_num, input_channels,
crop_size, crop_size);
} else {
transformed_blob->Reshape(input_num, input_channels,
input_height, input_width);
}
}
const int num = transformed_blob->num();
const int channels = transformed_blob->channels();
const int height = transformed_blob->height();
const int width = transformed_blob->width();
const int size = transformed_blob->count();
CHECK_LE(input_num, num);
CHECK_EQ(input_channels, channels);
CHECK_GE(input_height, height);
CHECK_GE(input_width, width);
const Dtype scale = param_.scale();
const bool do_mirror = param_.mirror() && Rand(2);
const bool has_mean_file = param_.has_mean_file();
const bool has_mean_values = mean_values_.size() > 0;
int h_off = 0;
int w_off = 0;
if (crop_size) {
CHECK_EQ(crop_size, height);
CHECK_EQ(crop_size, width);
// We only do random crop when we do training.
if (phase_ == TRAIN) {
h_off = Rand(input_height - crop_size + 1);
w_off = Rand(input_width - crop_size + 1);
} else {
h_off = (input_height - crop_size) / 2;
w_off = (input_width - crop_size) / 2;
}
} else {
CHECK_EQ(input_height, height);
CHECK_EQ(input_width, width);
}
Dtype* input_data = input_blob->mutable_cpu_data();
if (has_mean_file) {
CHECK_EQ(input_channels, data_mean_.channels());
CHECK_EQ(input_height, data_mean_.height());
CHECK_EQ(input_width, data_mean_.width());
for (int n = 0; n < input_num; ++n) {
int offset = input_blob->offset(n);
caffe_sub(data_mean_.count(), input_data + offset,
data_mean_.cpu_data(), input_data + offset);
}
}
if (has_mean_values) {
CHECK(mean_values_.size() == 1 || mean_values_.size() == input_channels) <<
"Specify either 1 mean_value or as many as channels: " << input_channels;
if (mean_values_.size() == 1) {
caffe_add_scalar(input_blob->count(), -(mean_values_[0]), input_data);
} else {
for (int n = 0; n < input_num; ++n) {
for (int c = 0; c < input_channels; ++c) {
int offset = input_blob->offset(n, c);
caffe_add_scalar(input_height * input_width, -(mean_values_[c]),
input_data + offset);
}
}
}
}
Dtype* transformed_data = transformed_blob->mutable_cpu_data();
for (int n = 0; n < input_num; ++n) {
int top_index_n = n * channels;
int data_index_n = n * channels;
for (int c = 0; c < channels; ++c) {
int top_index_c = (top_index_n + c) * height;
int data_index_c = (data_index_n + c) * input_height + h_off;
for (int h = 0; h < height; ++h) {
int top_index_h = (top_index_c + h) * width;
int data_index_h = (data_index_c + h) * input_width + w_off;
if (do_mirror) {
int top_index_w = top_index_h + width - 1;
for (int w = 0; w < width; ++w) {
transformed_data[top_index_w-w] = input_data[data_index_h + w];
}
} else {
for (int w = 0; w < width; ++w) {
transformed_data[top_index_h + w] = input_data[data_index_h + w];
}
}
}
}
}
if (scale != Dtype(1)) {
DLOG(INFO) << "Scale: " << scale;
caffe_scal(size, scale, transformed_data);
}
}
template<typename Dtype>
vector<int> DataTransformer<Dtype>::InferBlobShape(const Datum& datum) {
if (datum.encoded()) {
#ifdef USE_OPENCV
CHECK(!(param_.force_color() && param_.force_gray()))
<< "cannot set both force_color and force_gray";
cv::Mat cv_img;
if (param_.force_color() || param_.force_gray()) {
// If force_color then decode in color otherwise decode in gray.
cv_img = DecodeDatumToCVMat(datum, param_.force_color());
} else {
cv_img = DecodeDatumToCVMatNative(datum);
}
// InferBlobShape using the cv::image.
return InferBlobShape(cv_img);
#else
LOG(FATAL) << "Encoded datum requires OpenCV; compile with USE_OPENCV.";
#endif // USE_OPENCV
}
const int crop_size = param_.crop_size();
const int datum_channels = datum.channels();
const int datum_height = datum.height();
const int datum_width = datum.width();
// Check dimensions.
CHECK_GT(datum_channels, 0);
CHECK_GE(datum_height, crop_size);
CHECK_GE(datum_width, crop_size);
// Build BlobShape.
vector<int> shape(4);
shape[0] = 1;
shape[1] = datum_channels;
shape[2] = (crop_size)? crop_size: datum_height;
shape[3] = (crop_size)? crop_size: datum_width;
return shape;
}
template<typename Dtype>
vector<int> DataTransformer<Dtype>::InferBlobShape(
const vector<Datum> & datum_vector) {
const int num = datum_vector.size();
CHECK_GT(num, 0) << "There is no datum to in the vector";
// Use first datum in the vector to InferBlobShape.
vector<int> shape = InferBlobShape(datum_vector[0]);
// Adjust num to the size of the vector.
shape[0] = num;
return shape;
}
#ifdef USE_OPENCV
template<typename Dtype>
vector<int> DataTransformer<Dtype>::InferBlobShape(const cv::Mat& cv_img) {
const int crop_size = param_.crop_size();
const int img_channels = cv_img.channels();
const int img_height = cv_img.rows;
const int img_width = cv_img.cols;
// Check dimensions.
CHECK_GT(img_channels, 0);
CHECK_GE(img_height, crop_size);
CHECK_GE(img_width, crop_size);
// Build BlobShape.
vector<int> shape(4);
shape[0] = 1;
shape[1] = img_channels;
shape[2] = (crop_size)? crop_size: img_height;
shape[3] = (crop_size)? crop_size: img_width;
return shape;
}
template<typename Dtype>
vector<int> DataTransformer<Dtype>::InferBlobShape(
const vector<cv::Mat> & mat_vector, const bool is_video) {
const int num = mat_vector.size();
CHECK_GT(num, 0) << "There is no cv_img to in the vector";
if (is_video) {
vector<int> tmp_shape = InferBlobShape(mat_vector, false);
CHECK_EQ(tmp_shape.size(), 4) << "A mat_vector must be 4-dimensional";
vector<int> shape(5);
shape[0] = 1; // num of batches
shape[1] = tmp_shape[1]; // num of channels
shape[2] = num; // this is actually "length" of C3D blob
shape[3] = tmp_shape[2];
shape[4] = tmp_shape[3];
return shape;
} else {
// Use first cv_img in the vector to InferBlobShape.
vector<int> shape;
shape = InferBlobShape(mat_vector[0]);
// Adjust num to the size of the vector.
shape[0] = num;
return shape;
}
}
#endif // USE_OPENCV
template <typename Dtype>
void DataTransformer<Dtype>::InitRand() {
const bool needs_rand = param_.mirror() ||
(phase_ == TRAIN && param_.crop_size());
if (needs_rand) {
const unsigned int rng_seed = caffe_rng_rand();
rng_.reset(new Caffe::RNG(rng_seed));
} else {
rng_.reset();
}
}
template <typename Dtype>
void DataTransformer<Dtype>::SetRandFromSeed(const unsigned int rng_seed) {
rng_.reset(new Caffe::RNG(rng_seed));
}
template <typename Dtype>
int DataTransformer<Dtype>::Rand(int n) {
CHECK(rng_);
CHECK_GT(n, 0);
caffe::rng_t* rng =
static_cast<caffe::rng_t*>(rng_->generator());
return ((*rng)() % n);
}
INSTANTIATE_CLASS(DataTransformer);
} // namespace caffe |
library(tidyverse)
datasourceConfirmed <- "https://github.com/CSSEGISandData/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv"
datasourceDeaths <- "https://github.com/CSSEGISandData/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv"
# use library curl to download the data (are there other ways?)
library(curl)
# load the number of confirmed cases [region x time]
tmp <- tempfile()
curl_download(datasourceConfirmed, tmp)
dataConfirmed <- read.csv(tmp)
# load the number of deaths [region x time]
tmp2 <- tempfile()
curl_download(datasourceDeaths, tmp2)
dataDeaths <- read.csv(tmp2)
# 121 Germany
# 138 Italy
# 202 Spain
# 206 Sweden
region <- 206
confirmed <- as.numeric(dataConfirmed[region, -(1:4)])
deaths <- as.numeric(dataDeaths[region, -(1:4)])
confirmedDiff <- c(0, diff(confirmed))
deathsDiff <- c(0, diff(deaths))
confirmedDoubleLogRatio <- log(log(confirmed / confirmedDiff))
deathsDoubleLogRatio <- log(log(deaths / deathsDiff))
confirmedDoubleLogRatio[!is.finite(confirmedDoubleLogRatio)] <- NA
deathsDoubleLogRatio[!is.finite(deathsDoubleLogRatio)] <- NA
dataRegion <- data.frame(days = 1:(dim(dataConfirmed)[2]-4),
date = as.Date(colnames(dataConfirmed)[-(1:4)], "X%m.%d.%y"),
confirmed = confirmed,
confirmedDiff = confirmedDiff,
confirmedRatio = confirmedDoubleLogRatio,
deaths = deaths,
deathsDiff = deathsDiff,
deathsRatio = deathsDoubleLogRatio)
modelConfirmed <- lm(confirmedRatio ~ days, dataRegion, na.action = na.omit)
modelDeaths <- lm(deathsRatio ~ days, dataRegion, na.action = na.omit)
dataRegion
library(ggplot2)
library(gridExtra)
DiffPlot <- ggplot(dataRegion, aes(date, confirmedRatio)) +
ggtitle(paste("A: log(log(N/deltaN)) for", dataConfirmed[region, 2])) +
geom_point() +
geom_point(data = dataRegion, aes(date, deathsRatio), colour = 'red') +
geom_smooth(data = dataRegion,
method = "lm",
aes(date, deathsRatio),
colour = 'red',
method.args = list(na.action = na.omit)) +
geom_smooth(data = dataRegion,
method = "lm",
aes(date, confirmedRatio),
colour = 'black',
method.args = list(na.action = na.omit)) +
theme(legend.position = c(0.9, 0.9))
GumbelPlot <- ggplot(dataRegion, aes(date, confirmedDiff)) +
ggtitle(paste("B: deltaN for", dataConfirmed[region, 2])) +
geom_point() +
geom_point(data = dataRegion, aes(date, deathsDiff), colour = 'red')
grid.arrange(DiffPlot, GumbelPlot, ncol=2)
dataRegion %>%
select(days, date, ends_with("Ratio")) %>%
pivot_longer(confirmedRatio:deathsRatio) %>%
ggplot(aes(date, value, col=name))+
geom_point()+
geom_smooth(method="lm",
data=function(dtx)subset(dtx, name == "confirmedRatio")) |
#Region "Microsoft.VisualBasic::9bfdb4a3b03181d85a66e7dc10a57910, mzkit\src\mzkit\Task\Properties\SpectrumProperty.vb"
' Author:
'
' xieguigang (gg.xie@bionovogene.com, BioNovoGene Co., LTD.)
'
' Copyright (c) 2018 gg.xie@bionovogene.com, BioNovoGene Co., LTD.
'
'
' MIT License
'
'
' 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.
' /********************************************************************************/
' Summaries:
' Code Statistics:
' Total Lines: 111
' Code Lines: 95
' Comment Lines: 0
' Blank Lines: 16
' File Size: 4.94 KB
' Class SpectrumProperty
'
' Properties: activationMethod, basePeakMz, centroided, collisionEnergy, highMass
' lowMass, maxIntensity, msLevel, n_fragments, polarity
' precursorCharge, precursorMz, rawfile, retentionTime, rtmin
' scanId, totalIons
'
' Constructor: (+1 Overloads) Sub New
'
' Function: ToString
'
' Sub: Copy
'
' /********************************************************************************/
#End Region
Imports System.ComponentModel
Imports System.Text
Imports System.Windows.Forms
Imports BioNovoGene.Analytical.MassSpectrometry.Assembly.mzData.mzWebCache
Imports BioNovoGene.Analytical.MassSpectrometry.Math.Ms1
Imports BioNovoGene.Analytical.MassSpectrometry.Math.Spectra
Imports BioNovoGene.Analytical.MassSpectrometry.Math.Spectra.SplashID
Imports Microsoft.VisualBasic.Math.Information
Imports Microsoft.VisualBasic.Math.LinearAlgebra
Imports Microsoft.VisualBasic.Serialization.JSON
Imports stdNum = System.Math
Public Class SpectrumProperty : Implements ICopyProperties
<Description("The ms level of current scan data.")>
<Category("Precursor Ion")> Public ReadOnly Property msLevel As Integer
<Description("M/z of current ion scan.")>
<Category("Precursor Ion")> Public ReadOnly Property precursorMz As Double
<Description("The retension time in seconds.")>
<Category("Precursor Ion")> Public ReadOnly Property retentionTime As Double
<Description("The retension time in minute.")>
<Category("Precursor Ion")> Public ReadOnly Property rtmin As Double
<Description("The charge value of current ion.")>
<Category("Precursor Ion")> Public ReadOnly Property precursorCharge As Double
<Description("The charge polarity of current ion.")>
<Category("Precursor Ion")> Public ReadOnly Property polarity As String
<Description("Activation method for produce the product fragments of current ion's scan.")>
<Category("MSn")> Public ReadOnly Property activationMethod As String
<Description("Energy level that used for produce the product fragments of current ion's scan.")>
<Category("MSn")> Public ReadOnly Property collisionEnergy As String
<Description("Current ion scan is in centroid mode? False means in profile mode.")>
<Category("MSn")> Public ReadOnly Property centroided As String
<Description("spectral entropy for centroid spectrum[Li, Y., Kind, T., Folz, J. et al. Spectral entropy outperforms MS/MS dot product similarity for small-molecule compound identification. Nat Methods 18, 1524–1531 (2021).]")>
Public ReadOnly Property spectrum_entropy As Double
<Category("Product Ions")>
Public ReadOnly Property basePeakMz As Double
<Category("Product Ions")>
Public ReadOnly Property maxIntensity As String
<Category("Product Ions")>
Public ReadOnly Property totalIons As String
<Category("Product Ions")>
Public ReadOnly Property n_fragments As Integer
<Category("Product Ions")>
Public ReadOnly Property lowMass As Double
<Category("Product Ions")>
Public ReadOnly Property highMass As Double
Public ReadOnly Property rawfile As String
Public ReadOnly Property scanId As String
Public ReadOnly Property splashId As String
Sub New(scanId As String, rawfile As String, msLevel As Integer, attrs As ScanMS2)
With attrs
Me.msLevel = msLevel
collisionEnergy = .collisionEnergy
centroided = .centroided
precursorMz = .parentMz.ToString("F4")
retentionTime = .rt.ToString("F2")
precursorCharge = .charge
polarity = .polarity
activationMethod = .activationMethod.Description
rtmin = stdNum.Round(retentionTime / 60, 2)
End With
Dim ms2 As ms2() = attrs.GetMs.ToArray
If ms2.Length > 0 Then
With ms2.OrderByDescending(Function(i) i.intensity).First
basePeakMz = stdNum.Round(.mz, 4)
maxIntensity = .intensity.ToString("G4")
End With
totalIons = (Aggregate i In ms2 Into Sum(i.intensity)).ToString("G4")
n_fragments = ms2.Length
spectrum_entropy = 0
With ms2.Select(Function(i) i.mz).ToArray
lowMass = stdNum.Round(.Min, 4)
highMass = stdNum.Round(.Max, 4)
End With
End If
If msLevel > 1 AndAlso ms2.Length > 0 Then
Dim v As New Vector(From mzi As ms2
In ms2.Centroid(Tolerance.DeltaMass(0.3), New RelativeIntensityCutoff(0.05))
Select mzi.intensity)
spectrum_entropy = (v / v.Sum).ShannonEntropy
End If
Me.rawfile = rawfile
Me.scanId = scanId
Me.splashId = Splash.MSSplash.CalcSplashID(attrs)
End Sub
Public Overrides Function ToString() As String
Return Me.GetJson
End Function
Public Sub Copy() Implements ICopyProperties.Copy
Dim text As New StringBuilder($"spectrum property{vbTab}value")
Call text.AppendLine()
Call text.AppendLine($"rawfile{vbTab}{rawfile}")
Call text.AppendLine($"scanId{vbTab}{scanId}")
Call text.AppendLine($"msLevel{vbTab}{msLevel}")
Call text.AppendLine($"precursorMz{vbTab}{precursorMz}")
Call text.AppendLine($"retentionTime{vbTab}{retentionTime}")
Call text.AppendLine($"rt(min){vbTab}{rtmin}")
Call text.AppendLine($"precursorCharge{vbTab}{precursorCharge}")
Call text.AppendLine($"polarity{vbTab}{polarity}")
Call text.AppendLine($"activationMethod{vbTab}{activationMethod}")
Call text.AppendLine($"collisionEnergy{vbTab}{collisionEnergy}")
Call text.AppendLine($"centroided{vbTab}{centroided}")
Call text.AppendLine($"basePeakMz{vbTab}{basePeakMz}")
Call text.AppendLine($"maxIntensity{vbTab}{maxIntensity}")
Call text.AppendLine($"totalIons{vbTab}{totalIons}")
Call text.AppendLine($"n_fragments{vbTab}{n_fragments}")
Call text.AppendLine($"lowMass{vbTab}{lowMass}")
Call text.AppendLine($"highMass{vbTab}{highMass}")
Call text.AppendLine($"spectrum_entropy{vbTab}{spectrum_entropy}")
Call Clipboard.Clear()
Call Clipboard.SetText(text.ToString)
End Sub
End Class |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Page called by administrator to migrate course data (for addressing any issues on 4.3 upgrade).
*
* @package format_tiles
* @copyright 2023 David Watson {@link http://evolutioncode.uk}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
**/
require_once('../../../../config.php');
global $PAGE, $DB, $OUTPUT;
require_login();
$systemcontext = context_system::instance();
$pagecontext = null;
$issiteadmin = has_capability('moodle/site:config', $systemcontext);
if ($issiteadmin) {
// Site admins can see overview page with all courses.
$courseid = optional_param('courseid', 0, PARAM_INT);
$pagecontext = $courseid ? context_course::instance($courseid) : $systemcontext;
} else {
// Teacher must pass a course ID to fix one course to which they have access.
$courseid = required_param('courseid', PARAM_INT);
$pagecontext = context_course::instance($courseid);
require_capability('moodle/course:update', $pagecontext);
}
$pageurlparams = $courseid ? ['courseid' => $courseid] : null;
$pageurl = new moodle_url('/course/format/tiles/editor/migratecoursedata.php', $pageurlparams);
$PAGE->set_url($pageurl);
$PAGE->set_context($pagecontext);
if ($courseid) {
$courseurl = new moodle_url('/course/view.php', ['id' => $courseid]);
$course = $DB->get_record('course', ['id' => $courseid, 'format' => 'tiles']);
if (!$course) {
debugging("Course $courseid is not found or not a tiles course");
redirect($courseurl, get_string('error'), null, \core\output\notification::NOTIFY_ERROR);
}
$PAGE->set_heading($course->fullname);
$PAGE->set_course($course);
$countlegacyoptions = $DB->get_field_sql(
"SELECT COUNT(cfo.id) FROM {course_format_options} cfo
WHERE cfo.courseid = ? AND cfo.format = 'tiles'
AND cfo.name IN('tilephoto', 'tileicon')",
[$courseid]
);
if (!$countlegacyoptions) {
debugging("No legacy options found for course $courseid");
redirect($courseurl, get_string('error'), null, \core\output\notification::NOTIFY_ERROR);
}
// In this case we need to process the course now, if sesskey is present.
$sesskey = optional_param('sesskey', '', PARAM_TEXT);
if ($sesskey) {
require_sesskey();
\format_tiles\format_option::migrate_legacy_format_options($courseid);
\core\notification::success(
get_string('migratedcourseid', 'format_tiles', $courseid)
. ' ' . html_writer::link($courseurl, $course->fullname)
);
redirect($issiteadmin ? $pageurl->out_omit_querystring() : $courseurl);
} else {
// We need to ask the user if they are sure.
echo $OUTPUT->header();
echo html_writer::tag(
'h4', get_string('suremigratelegacyoptions', 'format_tiles', $countlegacyoptions),
['class' => 'mb-3']
);
$continueurl = new moodle_url($pageurl, ['sesskey' => sesskey()]);
echo html_writer::link($continueurl, get_string('continue'), ['class' => 'btn btn-danger']);
echo html_writer::link($courseurl, get_string('cancel'), ['class' => 'btn btn-secondary ml-2']);
echo $OUTPUT->footer();
die();
}
}
if (!$issiteadmin) {
throw new \Exception("Not allowed");
}
// If we reach here we are not looking at a specific course - show admin full list of courses.
$settingsurl = new moodle_url('/admin/settings.php', ['section' => 'formatsettingtiles']);
$PAGE->set_heading(get_string('admintools', 'format_tiles'));
$PAGE->navbar->add(get_string('administrationsite'), new moodle_url('/admin/search.php'));
$PAGE->navbar->add(get_string('plugins', 'admin'), new moodle_url('/admin/category.php', ['category' => 'modules']));
$PAGE->navbar->add(get_string('courseformats'), new moodle_url('/admin/category.php', ['category' => 'formatsettings']));
$PAGE->navbar->add(get_string('pluginname', 'format_tiles'), $settingsurl);
$PAGE->navbar->add(get_string('migratecoursedata', 'format_tiles'));
$legacycourses = $DB->get_records_sql(
"SELECT * FROM
(SELECT c.id as courseid, c.fullname,
(SELECT COUNT(cfo.id) FROM {course_format_options} cfo
WHERE cfo.courseid = c.id AND cfo.format = 'tiles' AND cfo.name IN('tilephoto', 'tileicon')) as legacyoptions,
(SELECT COUNT(tfo.id) FROM {format_tiles_tile_options} tfo
WHERE tfo.courseid = c.id AND tfo.optiontype IN (?, ?)) as newoptions
FROM {course} c
) counts
WHERE counts.legacyoptions > 0",
[\format_tiles\format_option::OPTION_SECTION_PHOTO, \format_tiles\format_option::OPTION_SECTION_ICON]
);
$table = new html_table();
$table->head = [
get_string('course'),
get_string('legacytiledata', 'format_tiles'),
get_string('newtiledata', 'format_tiles'),
get_string('migratenow', 'format_tiles'),
];
$table->data = [];
foreach ($legacycourses as $legacycourse) {
$table->data[] = [
html_writer::link(
new moodle_url('/course/view.php', ['id' => $legacycourse->courseid]),
$legacycourse->fullname
),
$legacycourse->legacyoptions,
$legacycourse->newoptions,
html_writer::link(
new moodle_url('/course/format/tiles/editor/migratecoursedata.php',
['courseid' => $legacycourse->courseid]),
get_string('migratenow', 'format_tiles'),
['class' => 'btn btn-primary']
),
];
}
if (empty($table->data)) {
$table->data[] = [get_string('none'), '', '', ''];
}
$croncheck = new \tool_task\check\cronrunning();
$cronresult = $croncheck->get_result();
echo $OUTPUT->header();
if ($cronresult->get_status() !== $cronresult::OK) {
\core\notification::warning($cronresult->get_summary());
}
echo html_writer::div(get_string('unmigratedcoursesintro', 'format_tiles', count($legacycourses)), 'mb-2');
echo html_writer::table($table);
echo $OUTPUT->footer(); |
// --- Directions
// Write a function that accepts a positive number N.
// The function should console log a step shape
// with N levels using the # character. Make sure the
// step has spaces on the right hand side!
// --- Examples
// steps(2)
// '# '
// '##'
// steps(3)
// '# '
// '## '
// '###'
// steps(4)
// '# '
// '## '
// '### '
// '####'
// Solution #1
// function steps(n) {
// for (let i = 1; i <= n; i++) {
// let step = '';
// for (let j = 1; j <= i; j++) {
// step += '#';
// }
// if (step.length < n) {
// for (let j = step.length; j < n; j++) {
// step += ' ';
// }
// }
// console.log(step);
// }
// }
// Solution #2
// function steps(n) {
// for (let row = 0; row < n; row++) {
// let step = '';
// for (let col = 0; col < n; col++) {
// if (col <= row) {
// step += '#';
// } else {
// step += ' ';
// }
// }
// console.log(step);
// }
// }
// Solution #3
// function steps(n, space = 0) {
// if (n <= 0) {
// return;
// }
// let stair = '';
// for (let i = 0; i < n; i++) {
// stair += '#';
// }
// for (let i = 0; i < space; i++) {
// stair += ' ';
// }
// steps(n - 1, space + 1);
// console.log(stair);
// }
function steps(n, row = 0, stair = '') {
if (n === row) {
return;
}
if (n === stair.length) {
console.log(stair);
return steps(n, row + 1);
}
if (stair.length <= row) {
stair += '#';
} else {
stair += ' ';
}
steps(n, row, stair);
}
module.exports = steps; |
<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
class RolesSedeer extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
$roleAdmin = Role::create(['name' => 'Admin', 'guard_name' => 'api']);
$roleUSer = Role::create(['name' => 'User', 'guard_name' => 'api']);
Permission::create(['name' => 'admin.dashboard.index', 'guard_name' => 'api'])->syncRoles([$roleAdmin]);
Permission::create(['name' => 'admin.users.index', 'guard_name' => 'api'])->syncRoles([$roleAdmin]);
Permission::create(['name' => 'user.tasks.index', 'guard_name' => 'api'])->syncRoles([$roleAdmin, $roleUSer]);
Permission::create(['name' => 'user.tasks.show', 'guard_name' => 'api'])->syncRoles([$roleAdmin, $roleUSer]);
Permission::create(['name' => 'user.tasks.store', 'guard_name' => 'api'])->syncRoles([$roleAdmin, $roleUSer]);
Permission::create(['name' => 'user.tasks.update', 'guard_name' => 'api'])->syncRoles([$roleAdmin, $roleUSer]);
Permission::create(['name' => 'user.tasks.destroy', 'guard_name' => 'api'])->syncRoles([$roleAdmin, $roleUSer]);
Permission::create(['name' => 'user.tasks.restore', 'guard_name' => 'api'])->syncRoles([$roleAdmin, $roleUSer]);
Permission::create(['name' => 'user.tasks.share', 'guard_name' => 'api'])->syncRoles([$roleAdmin, $roleUSer]);
Permission::create(['name' => 'user.tasks.deleteShare', 'guard_name' => 'api'])->syncRoles([$roleAdmin, $roleUSer]);
Permission::create(['name' => 'user.categories.index', 'guard_name' => 'api'])->syncRoles([$roleAdmin, $roleUSer]);
}
} |
/* Lattice Boltzmann sample, written in C++, using the OpenLB
* library
*
* Copyright (C) 2018 Robin Trunk
* E-mail contact: info@openlb.net
* The most recent release of OpenLB can be downloaded at
* <http://www.openlb.net/>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
/* youngLaplace2d.cpp
* In this example a Young-Laplace test is performed. A circular domain
* of fluid 2 is immersed in fluid 1. A diffusive interface forms and the
* surface tension can be calculated using the Laplace pressure relation.
* The pressure difference is calculated between a point in the middle of
* the circular domain and a point furthest away from it in the
* computational domain (here left bottom corner).
*
* This example shows the simplest case for the free-energy model with two
* fluid components.
*/
#include "olb2D.h"
#include "olb2D.hh" // use only generic version!
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace olb;
using namespace olb::descriptors;
using namespace olb::graphics;
using namespace std;
typedef double T;
typedef D2Q9<CHEM_POTENTIAL,FORCE> DESCRIPTOR;
// Parameters for the simulation setup
const int N = 100;
const T nx = 100.;
const T radius = 0.25 * nx;
const T alpha = 1.5; // Interfacial width [lattice units]
const T kappa1 = 0.0075; // For surface tensions [lattice units]
const T kappa2 = 0.005; // For surface tensions [lattice units]
const T gama = 1.; // For mobility of interface [lattice units]
const int maxIter = 60000;
const int vtkIter = 200;
const int statIter = 1000;
void prepareGeometry( SuperGeometry2D<T>& superGeometry )
{
OstreamManager clout( std::cout,"prepareGeometry" );
clout << "Prepare Geometry ..." << std::endl;
superGeometry.rename( 0,1 );
superGeometry.innerClean();
superGeometry.checkForErrors();
superGeometry.print();
clout << "Prepare Geometry ... OK" << std::endl;
}
void prepareLattice( SuperLattice2D<T, DESCRIPTOR>& sLattice1,
SuperLattice2D<T, DESCRIPTOR>& sLattice2,
Dynamics<T, DESCRIPTOR>& bulkDynamics1,
Dynamics<T, DESCRIPTOR>& bulkDynamics2,
UnitConverter<T, DESCRIPTOR>& converter,
SuperGeometry2D<T>& superGeometry )
{
OstreamManager clout( std::cout,"prepareLattice" );
clout << "Prepare Lattice ..." << std::endl;
// define lattice Dynamics
sLattice1.defineDynamics( superGeometry, 0, &instances::getNoDynamics<T, DESCRIPTOR>() );
sLattice2.defineDynamics( superGeometry, 0, &instances::getNoDynamics<T, DESCRIPTOR>() );
sLattice1.defineDynamics( superGeometry, 1, &bulkDynamics1 );
sLattice2.defineDynamics( superGeometry, 1, &bulkDynamics2 );
// bulk initial conditions
// define circular domain for fluid 2
std::vector<T> v( 2,T() );
AnalyticalConst2D<T,T> zeroVelocity( v );
AnalyticalConst2D<T,T> one ( 1. );
SmoothIndicatorCircle2D<T,T> circle( {nx/2., nx/2.}, radius, 10.*alpha );
AnalyticalIdentity2D<T,T> rho( one );
AnalyticalIdentity2D<T,T> phi( one - circle - circle );
sLattice1.iniEquilibrium( superGeometry, 1, rho, zeroVelocity );
sLattice2.iniEquilibrium( superGeometry, 1, phi, zeroVelocity );
sLattice1.initialize();
sLattice2.initialize();
clout << "Prepare Lattice ... OK" << std::endl;
}
void prepareCoupling(SuperLattice2D<T, DESCRIPTOR>& sLattice1,
SuperLattice2D<T, DESCRIPTOR>& sLattice2)
{
OstreamManager clout( std::cout,"prepareCoupling" );
clout << "Add lattice coupling" << endl;
// Add the lattice couplings
// The chemical potential coupling must come before the force coupling
FreeEnergyChemicalPotentialGenerator2D<T, DESCRIPTOR> coupling1(
alpha, kappa1, kappa2);
FreeEnergyForceGenerator2D<T, DESCRIPTOR> coupling2;
sLattice1.addLatticeCoupling( coupling1, sLattice2 );
sLattice2.addLatticeCoupling( coupling2, sLattice1 );
clout << "Add lattice coupling ... OK!" << endl;
}
void getResults( SuperLattice2D<T, DESCRIPTOR>& sLattice2,
SuperLattice2D<T, DESCRIPTOR>& sLattice1, int iT,
SuperGeometry2D<T>& superGeometry, Timer<T>& timer,
UnitConverter<T, DESCRIPTOR> converter)
{
OstreamManager clout( std::cout,"getResults" );
SuperVTMwriter2D<T> vtmWriter( "youngLaplace2d" );
if ( iT==0 ) {
// Writes the geometry, cuboid no. and rank no. as vti file for visualization
SuperLatticeGeometry2D<T, DESCRIPTOR> geometry( sLattice1, superGeometry );
SuperLatticeCuboid2D<T, DESCRIPTOR> cuboid( sLattice1 );
SuperLatticeRank2D<T, DESCRIPTOR> rank( sLattice1 );
vtmWriter.write( geometry );
vtmWriter.write( cuboid );
vtmWriter.write( rank );
vtmWriter.createMasterFile();
}
// Get statistics
if ( iT%statIter==0 ) {
// Timer console output
timer.update( iT );
timer.printStep();
sLattice1.getStatistics().print( iT, converter.getPhysTime(iT) );
sLattice2.getStatistics().print( iT, converter.getPhysTime(iT) );
}
// Writes the VTK files
if ( iT%vtkIter==0 ) {
AnalyticalConst2D<T,T> half_( 0.5 );
SuperLatticeFfromAnalyticalF2D<T, DESCRIPTOR> half(half_, sLattice1);
SuperLatticeDensity2D<T, DESCRIPTOR> density1( sLattice1 );
density1.getName() = "rho";
SuperLatticeDensity2D<T, DESCRIPTOR> density2( sLattice2 );
density2.getName() = "phi";
SuperIdentity2D<T,T> c1 (half*(density1+density2));
c1.getName() = "density-fluid-1";
SuperIdentity2D<T,T> c2 (half*(density1-density2));
c2.getName() = "density-fluid-2";
vtmWriter.addFunctor( density1 );
vtmWriter.addFunctor( density2 );
vtmWriter.addFunctor( c1 );
vtmWriter.addFunctor( c2 );
vtmWriter.write( iT );
// calculate bulk pressure, pressure difference and surface tension
if (iT%statIter==0) {
AnalyticalConst2D<T,T> two_( 2. );
AnalyticalConst2D<T,T> onefive_( 1.5 );
AnalyticalConst2D<T,T> k1_( kappa1 );
AnalyticalConst2D<T,T> k2_( kappa2 );
AnalyticalConst2D<T,T> cs2_( 1./descriptors::invCs2<T,DESCRIPTOR>() );
SuperLatticeFfromAnalyticalF2D<T, DESCRIPTOR> two(two_, sLattice1);
SuperLatticeFfromAnalyticalF2D<T, DESCRIPTOR> onefive(onefive_, sLattice1);
SuperLatticeFfromAnalyticalF2D<T, DESCRIPTOR> k1(k1_, sLattice1);
SuperLatticeFfromAnalyticalF2D<T, DESCRIPTOR> k2(k2_, sLattice1);
SuperLatticeFfromAnalyticalF2D<T, DESCRIPTOR> cs2(cs2_, sLattice1);
// Calculation of bulk pressure:
// c_1 = density of fluid 1; c_2 = density of fluid 2
// p_bulk = rho*c_s^2 + kappa1 * (3/2*c_1^4 - 2*c_1^3 + 0.5*c_1^2)
// + kappa2 * (3/2*c_2^4 - 2*c_2^3 + 0.5*c_2^2)
SuperIdentity2D<T,T> bulkPressure ( density1*cs2
+ k1*( onefive*c1*c1*c1*c1 - two*c1*c1*c1 + half*c1*c1 )
+ k2*( onefive*c2*c2*c2*c2 - two*c2*c2*c2 + half*c2*c2 ) );
AnalyticalFfromSuperF2D<T, T> interpolPressure( bulkPressure, true, 1);
double position[2] = { 0.5*nx, 0.5*nx };
double pressureIn = 0.;
double pressureOut = 0.;
interpolPressure(&pressureIn, position);
position[0] = ((double)N/100.)*converter.getPhysDeltaX();
position[1] = ((double)N/100.)*converter.getPhysDeltaX();
interpolPressure(&pressureOut, position);
clout << "Pressure Difference: " << pressureIn-pressureOut << " ; ";
clout << "Surface Tension: " << radius*(pressureIn-pressureOut) << std::endl;
clout << "Analytical Pressure Difference: " << alpha/(6.*radius) * (kappa1 + kappa2) << " ; ";
clout << "Analytical Surface Tension: " << alpha/6. * (kappa1 + kappa2) << std::endl;
}
}
}
int main( int argc, char *argv[] )
{
// === 1st Step: Initialization ===
olbInit( &argc, &argv );
singleton::directories().setOutputDir( "./tmp/" );
OstreamManager clout( std::cout,"main" );
UnitConverterFromResolutionAndRelaxationTime<T,DESCRIPTOR> converter(
(T) N, // resolution
(T) 1., // lattice relaxation time (tau)
(T) nx, // charPhysLength: reference length of simulation geometry
(T) 1.e-6, // charPhysVelocity: maximal/highest expected velocity during simulation in __m / s__
(T) 0.1, // physViscosity: physical kinematic viscosity in __m^2 / s__
(T) 1. // physDensity: physical density in __kg / m^3__
);
// Prints the converter log as console output
converter.print();
// === 2nd Step: Prepare Geometry ===
std::vector<T> extend = { nx, nx, nx };
std::vector<T> origin = { 0, 0, 0 };
IndicatorCuboid2D<T> cuboid(extend,origin);
#ifdef PARALLEL_MODE_MPI
CuboidGeometry2D<T> cGeometry( cuboid, converter.getPhysDeltaX(), singleton::mpi().getSize() );
#else
CuboidGeometry2D<T> cGeometry( cuboid, converter.getPhysDeltaX() );
#endif
// set periodic boundaries to the domain
cGeometry.setPeriodicity( true, true );
// Instantiation of loadbalancer
HeuristicLoadBalancer<T> loadBalancer( cGeometry );
loadBalancer.print();
// Instantiation of superGeometry
SuperGeometry2D<T> superGeometry( cGeometry,loadBalancer );
prepareGeometry( superGeometry );
// === 3rd Step: Prepare Lattice ===
SuperLattice2D<T, DESCRIPTOR> sLattice1( superGeometry );
SuperLattice2D<T, DESCRIPTOR> sLattice2( superGeometry );
ForcedBGKdynamics<T, DESCRIPTOR> bulkDynamics1 (
converter.getLatticeRelaxationFrequency(),
instances::getBulkMomenta<T,DESCRIPTOR>() );
FreeEnergyBGKdynamics<T, DESCRIPTOR> bulkDynamics2 (
converter.getLatticeRelaxationFrequency(), gama,
instances::getBulkMomenta<T,DESCRIPTOR>() );
prepareLattice( sLattice1, sLattice2, bulkDynamics1, bulkDynamics2,
converter, superGeometry );
prepareCoupling( sLattice1, sLattice2);
SuperField2D<T,DESCRIPTOR,CHEM_POTENTIAL> sExternal1 (superGeometry, sLattice1, sLattice1.getOverlap() );
SuperField2D<T,DESCRIPTOR,CHEM_POTENTIAL> sExternal2 (superGeometry, sLattice2, sLattice2.getOverlap() );
// === 4th Step: Main Loop with Timer ===
int iT = 0;
clout << "starting simulation..." << endl;
Timer<T> timer( maxIter, superGeometry.getStatistics().getNvoxel() );
timer.start();
for ( iT=0; iT<=maxIter; ++iT ) {
// Computation and output of the results
getResults( sLattice2, sLattice1, iT, superGeometry, timer, converter );
// Collide and stream execution
sLattice1.collideAndStream();
sLattice2.collideAndStream();
// MPI communication for lattice data
sLattice1.communicate();
sLattice2.communicate();
// Execute coupling between the two lattices
sLattice1.executeCoupling();
sExternal1.communicate();
sExternal2.communicate();
sLattice2.executeCoupling();
}
timer.stop();
timer.printSummary();
} |
<template>
<b-card>
<!-- filter -->
<div v-if="loading" class="text-center mt-4">
<b-spinner label="Loading..."></b-spinner>
</div>
<div class="col-12 mt-16">
<div>
<b-row class="align-items-center">
<b-col lg="6" class="my-1">
<b-form-group label="" label-for="filter-input" label-cols-sm="1" label-align-sm="right" label-size="sm"
class="mb-0">
<b-input-group size="sm">
<b-form-input id="filter-input" v-model="filter" type="search"
placeholder="Type to Search"></b-form-input>
<b-input-group-append>
<b-button :disabled="!filter" @click="filter = ''">Clear</b-button>
</b-input-group-append>
</b-input-group>
</b-form-group>
</b-col>
<b-col lg="6" class="my-1 d-flex justify-content-end">
<b-button @click="exportDataToCSV" variant="primary" class="mb-8 mr-8">Export</b-button>
</b-col>
<b-col lg="6" class="my-1 d-flex justify-content-end">
<b-button @click="openModal" variant="primary" class="mb-8 mr-8">
Add Booking
</b-button>
</b-col>
</b-row>
</div>
</div>
<b-modal v-model="modalVisible" title="Add Booking" hide-footer>
<!-- Your form content goes here -->
<form @submit.prevent="submitForm">
<div class="row">
<div class="col-md-6 col-12">
<b-form-group id="input-group-1" label="Transaction Id:" label-for="transaction_id">
<b-form-input id="transaction_id" type="text" placeholder="Enter transaction id" v-model="transaction_id"
required></b-form-input>
</b-form-group>
</div>
<div class="col-md-6 col-12">
<b-form-group id="input-group-2" label="Booking No:" label-for="booking_no">
<b-form-input id="booking_no" type="text" placeholder="Enter booking_no" v-model="booking_no"
required></b-form-input>
</b-form-group>
</div>
<div class="col-md-6 col-12">
<b-form-group id="input-group-1" label=" Captain Name:" label-for="captain_name">
<b-form-input id="captain_name" type="text" placeholder="Enter captain_name " v-model="captain_name"
required></b-form-input>
</b-form-group>
</div>
<div class="col-md-6 col-12">
<b-form-group id="input-group-1" label="Vehicle Class" label-for="vehicle_class">
<b-form-input id="vehicle_class" type="text" placeholder="Enter vehicle class" v-model="vehicle_class"
required></b-form-input>
</b-form-group>
</div>
<div class="col-md-6 col-12">
<b-form-group id="input-group-1" label=" Vehicle No" label-for="vehicle_no">
<b-form-input id="vehicle_no" type="text" placeholder="Enter vehicle no" v-model="vehicle_no"
required></b-form-input>
</b-form-group>
</div>
<div class="col-md-6 col-12">
<b-form-group id="input-group-1" label=" Customer Name" label-for="customer_name">
<b-form-input id="customer_name" type="text" placeholder="Enter customer name " v-model="customer_name"
required></b-form-input>
</b-form-group>
</div>
<div class="col-md-6 col-12">
<b-form-group id="input-group-1" label="Pickup Location" label-for="pickup_location">
<b-form-input id="pickup_location" type="text" placeholder="Enter pickup location"
v-model="pickup_location" required></b-form-input>
</b-form-group>
</div>
<div class="col-md-6 col-12">
<b-form-group id="input-group-1" label="Drop Location" label-for="drop_location">
<b-form-input id="drop_location" type="text" placeholder="Enter drop location" v-model="drop_location"
required></b-form-input>
</b-form-group>
</div>
<div class="col-md-6 col-12">
<b-form-group id="input-group-1" label="Booking Date" label-for="booking_date">
<b-form-input id="booking_date" type="date" placeholder="Enter booking date"
v-model="booking_date"></b-form-input>
</b-form-group>
</div>
<div class="col-md-6 col-12">
<b-form-group id="input-group-1" label="Amount" label-for="amount">
<b-form-input id="amount" type="text" placeholder="Enter amount " v-model="amount"
required></b-form-input>
</b-form-group>
</div>
<div class="col-md-6 col-12">
<b-form-group id="input-group-1" label="Kilometer" label-for="kilometer">
<b-form-input id="kilometer" type="text" placeholder="Enter kilometer" v-model="kilometer"
required></b-form-input>
</b-form-group>
</div>
<div class="col-md-6 col-12">
<b-form-group id="input-group-1" label="Day Status" label-for="day_status">
<b-form-input id="day_status" type="text" placeholder="Enter day_status" v-model="day_status"
required></b-form-input>
</b-form-group>
</div>
</div>
<div class="d-flex justify-content-end">
<b-button type="submit" variant="primary">Submit</b-button>
</div>
</form>
</b-modal>
<!-- filter end -->
<b-row>
<div class="col-12 mt-16">
<b-table id="dataTable" :items="users" :fields="fields" :current-page="currentPage" :per-page="perPage"
:filter="filter" :filter-included-fields="filterOn" :sort-by.sync="sortBy" :sort-desc.sync="sortDesc"
:sort-direction="sortDirection" show-empty @filtered="onFiltered" y responsive>
<!-- Action Button Code -->
<!-- <template #cell(actions)="row">
<b-button @click="downloadFile(row.item.file)" variant="primary"
>Download</b-button
>
</template> -->
<template #cell(actions)="row">
<b-button @click="showBooking(row.item.id)" variant="link" class="p-0">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="currentColor" style="
color: rgba(0, 255, 195, 0.87);
margin-left: 6px;
margin-bottom: 10px;
" class="bi bi-eye" viewBox="0 0 16 16">
<path
d="M16 8s-3-5.5-8-5.5S0 8 0 8s3 5.5 8 5.5S16 8 16 8zM1.173 8a13.133 13.133 0 0 1 1.66-2.043C4.12 4.668 5.88 3.5 8 3.5c2.12 0 3.879 1.168 5.168 2.457A13.133 13.133 0 0 1 14.828 8c-.058.087-.122.183-.195.288-.335.48-.83 1.12-1.465 1.755C11.879 11.332 10.119 12.5 8 12.5c-2.12 0-3.879-1.168-5.168-2.457A13.134 13.134 0 0 1 1.172 8z" />
<path d="M8 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5zM4.5 8a3.5 3.5 0 1 1 7 0 3.5 3.5 0 0 1-7 0z" />
</svg>
</b-button>
<b-button @click="editUser(row.item.id)" variant="link" class="p-0">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="currentColor"
style="color: orange; margin-left: 10px; margin-bottom: 10px" class="bi bi-pencil" viewBox="0 0 16 16">
<!-- ... your existing SVG path ... -->
<path
d="M12.146.146a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1 0 .708l-10 10a.5.5 0 0 1-.168.11l-5 2a.5.5 0 0 1-.65-.65l2-5a.5.5 0 0 1 .11-.168l10-10zM11.207 2.5 13.5 4.793 14.793 3.5 12.5 1.207 11.207 2.5zm1.586 3L10.5 3.207 4 9.707V10h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.293l6.5-6.5zm-9.761 5.175-.106.106-1.528 3.821 3.821-1.528.106-.106A.5.5 0 0 1 5 12.5V12h-.5a.5.5 0 0 1-.5-.5V11h-.5a.5.5 0 0 1-.468-.325z" />
</svg>
</b-button>
<b-button @click="showDeleteConfirmation = true" variant="link" class="p-0">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="currentColor"
style="color: red; margin-left: 6px; margin-bottom: 10px" class="bi bi-eye" viewBox="0 0 16 16">
<!-- ... your SVG path ... -->
<path
d="M6.5 1h3a.5.5 0 0 1 .5.5v1H6v-1a.5.5 0 0 1 .5-.5ZM11 2.5v-1A1.5 1.5 0 0 0 9.5 0h-3A1.5 1.5 0 0 0 5 1.5v1H2.506a.58.58 0 0 0-.01 0H1.5a.5.5 0 0 0 0 1h.538l.853 10.66A2 2 0 0 0 4.885 16h6.23a2 2 0 0 0 1.994-1.84l.853-10.66h.538a.5.5 0 0 0 0-1h-.995a.59.59 0 0 0-.01 0H11Zm1.958 1-.846 10.58a1 1 0 0 1-.997.92h-6.23a1 1 0 0 1-.997-.92L3.042 3.5h9.916Zm-7.487 1a.5.5 0 0 1 .528.47l.5 8.5a.5.5 0 0 1-.998.06L5 5.03a.5.5 0 0 1 .47-.53Zm5.058 0a.5.5 0 0 1 .47.53l-.5 8.5a.5.5 0 1 1-.998-.06l.5-8.5a.5.5 0 0 1 .528-.47ZM8 4.5a.5.5 0 0 1 .5.5v8.5a.5.5 0 0 1-1 0V5a.5.5 0 0 1 .5-.5Z" />
</svg>
</b-button>
<b-modal v-model="showDeleteConfirmation" title="Delete Confirmation">
<p>Are you sure you want to delete this item?</p>
<template #modal-footer>
<b-button variant="danger" @click="deleteItem(row.item.id)">Delete</b-button>
<b-button variant="secondary" @click="showDeleteConfirmation = false">Cancel</b-button>
</template>
</b-modal>
<!-- <b-button
@click="toggleCardModal(row.item)"
variant="link"
class="p-0"
>
</b-button> -->
</template>
<b-form-group label="Filter" label-for="filter-input" label-cols-sm="3" label-align-sm="right" label-size="sm"
class="mb-0">
<b-input-group size="sm">
<b-form-input id="filter-input" v-model="filter" type="search"
placeholder="Type to Search"></b-form-input>
<b-input-group-append>
<b-button :disabled="!filter" @click="filter = ''">Clear</b-button>
</b-input-group-append>
</b-input-group>
</b-form-group>
</b-table>
<div class="mx-8 d-flex justify-content-end">
<b-pagination v-model="currentPage" :total-rows="rows" :per-page="perPage"
aria-controls="my-table"></b-pagination>
</div>
<b-row class="mt-16 align-items-center justify-content-end">
<b-row>
<div v-if="codeActive" class="col-12 mt-24 hljs-container" :class="{ active: codeActiveClass }">
<pre v-highlightjs>
<code class="hljs html">
{{ codeText }}
</code>
</pre>
</div>
</b-row>
</b-row>
</div>
</b-row>
</b-card>
</template>
<script>
import {
BRow,
BCol,
BCard,
BButton,
BTable,
BFormGroup,
BInputGroup,
BFormInput,
BFormSelect,
BPagination,
BInputGroupAppend,
BSpinner,
} from "bootstrap-vue";
import axios from "axios";
import Papa from "papaparse";
// new code
// import code from "./code";
// new code end
export default {
data() {
return {
perPage: 8,
currentPage: 1,
sortBy: "age",
sortDesc: false,
selectedCardOption: "",
rowToUpdate: null,
modalVisible: false,
editMode: false,
users: [], // Instead of 'items', use 'users' array to store fetched data
fields: [
{ key: "id", sortable: true },
{ key: "transaction_id", sortable: true },
{ key: "booking_no", sortable: true },
{ key: "captain_name", sortable: true },
{ key: "vehicle_class", sortable: true },
{ key: "vehicle_no", sortable: true },
{ key: "customer_name", sortable: true },
{ key: "pickup_location", sortable: true },
{ key: "drop_location", sortable: true },
{ key: "booking_date", sortable: true },
{ key: "amount", sortable: true },
{ key: "kilometer", sortable: true },
{ key: "day_status", sortable: true },
{ key: "actions", label: "Actions" },
],
filter: "", // Define filter property for search functionality
totalRows: 0, // Initialize totalRows to 0
showDeleteConfirmation: false,
itemIdToDelete: null,
loading: false,
startDateFilter: "",
endDateFilter: "",
day_status: "",
pickup_location: "",
drop_location: "",
customer_name: "",
vehicle_class: "",
vehicle_no: "",
amount: "",
booking_date: "",
kilometer: "",
captain_name: "",
transaction_id: "",
booking_no: "",
your_booking_id: null,
};
},
components: {
BRow,
BCol,
BCard,
BButton,
BTable,
BFormGroup,
BInputGroup,
BFormInput,
BFormSelect,
BPagination,
BInputGroupAppend,
BSpinner,
},
computed: {
sortOptions() {
return this.fields
.filter((f) => f.sortable)
.map((f) => {
return { text: f.label, value: f.key };
});
},
rows() {
return this.users.length;
},
},
mounted() {
this.fetchData();
},
methods: {
fetchData() {
this.loading = true; // Set loading to true before fetching data
let apiUrl = "booking";
axios
.get(apiUrl) // Replace 'your_api_endpoint_url_here' with your actual API URL
.then((response) => {
this.users = response.data.data;
this.totalRows = this.users.length;
})
.catch((error) => {
console.error("Error fetching data:", error);
})
.finally(() => {
this.loading = false; // Set loading to false after fetching data, whether success or error
});
},
openModal() {
this.resetFormFields();
this.modalVisible = true;
},
resetFormFields() {
this.transaction_id = '';
this.booking_no = '';
this.captain_name = '';
this.vehicle_class = '';
this.vehicle_no = '';
this.customer_name = '';
this.pickup_location = '';
this.drop_location = '';
this.amount = '';
this.kilometer = '';
this.booking_date = '';
this.day_status = '';
// ... reset other fields ...
},
submitForm() {
if (this.editMode) {
// Perform update logic based on the data in the form fields
this.isLoading = true;
// Create a FormData object to handle the image file
const formData = new FormData();
formData.append("transaction_id", this.transaction_id);
formData.append("amount", this.amount);
formData.append("day_status", this.day_status);
formData.append("pickup_location", this.pickup_location);
formData.append("drop_location", this.drop_location);
formData.append("vehicle_no", this.vehicle_no);
formData.append("vehicle_class", this.vehicle_class);
formData.append("booking_date", this.booking_date);
formData.append("customer_name", this.customer_name);
formData.append("kilometer", this.kilometer);
formData.append("captain_name", this.captain_name);
formData.append("booking_no", this.booking_no);
axios.post(`bookingUpdate/${this.your_booking_id}`, formData)
.then((response) => {
console.log(response.data);
this.$bvToast.toast("Booking Updated successfully!", {
title: "Success",
variant: "success",
solid: true,
appendToast: true,
toaster: "b-toaster-top-right",
autoHideDelay: 5000,
variant: "primary", // Background color
});
this.isLoading = false;
})
.catch((error) => {
this.errors = error.response.data.errors;
console.log(error.response.data);
this.isLoading = false;
});
// Reset editMode
this.editMode = false;
} else {
this.isLoading = true;
// Create a FormData object to handle the image file
const formData = new FormData();
formData.append("transaction_id", this.transaction_id);
formData.append("amount", this.amount);
formData.append("day_status", this.day_status);
formData.append("pickup_location", this.pickup_location);
formData.append("drop_location", this.drop_location);
formData.append("vehicle_no", this.vehicle_no);
formData.append("vehicle_class", this.vehicle_class);
formData.append("booking_date", this.booking_date);
formData.append("customer_name", this.customer_name);
formData.append("kilometer", this.kilometer);
formData.append("captain_name", this.captain_name);
formData.append("booking_no", this.booking_no);
axios
.post("booking", formData)
.then((response) => {
console.log(response.data);
this.$bvToast.toast("Booking added successfully!", {
title: "Success",
variant: "success",
solid: true,
appendToast: true,
toaster: "b-toaster-top-right",
autoHideDelay: 5000,
variant: "primary", // Background color
});
this.isLoading = false;
})
.catch((error) => {
this.errors = error.response.data.errors;
console.log(error.response.data);
this.isLoading = false;
});
}
this.modalVisible = false;
},
onFiltered(filteredItems) {
this.totalRows = filteredItems.length;
this.currentPage = 1;
},
codeClick() {
this.codeActive = !this.codeActive;
},
exportDataToCSV() {
const csv = Papa.unparse(this.users);
const blob = new Blob([csv], { type: "text/csv" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "exported_data.csv";
a.click();
URL.revokeObjectURL(url);
},
deleteItem(itemId) {
this.itemIdToDelete = itemId; // Set the item ID to be deleted
axios
.delete(`booking/${itemId}`)
.then((response) => {
this.showDeleteConfirmation = false;
this.fetchData(); // Refresh the data after deletion
})
.catch((error) => {
// Handle error
console.error("Error deleting item:", error);
});
},
downloadFile(fileUrl) {
// Construct a download link for the file
const link = document.createElement("a");
link.href = "https://boltapi.fastnetstaffing.in/" + fileUrl;
link.download = "downloaded_file"; // Specify the default filename for the downloaded file
link.target = "_blank"; // Open the link in a new tab
link.click();
},
async editUser(userId) {
try {
// Make an API call to fetch user data based on userId
const response = await axios.get(`booking/${userId}`);
// Populate form fields with the fetched user data
const userData = response.data.data; // Ensure the correct property is used (response.data.data)
this.transaction_id = userData.transaction_id;
this.booking_no = userData.booking_no;
this.captain_name = userData.captain_name;
this.vehicle_class = userData.vehicle_class;
this.vehicle_no = userData.vehicle_no;
this.customer_name = userData.customer_name;
this.pickup_location = userData.pickup_location;
this.drop_location = userData.drop_location;
this.amount = userData.amount;
this.kilometer = userData.kilometer;
this.booking_date = userData.booking_date;
this.day_status = userData.day_status;
this.your_booking_id = userId;
// ... Populate other fields accordingly
this.editMode = true;
this.modalVisible = true;
} catch (error) {
console.error('Error fetching user data:', error);
// Handle error, show a notification, etc.
}
},
showBooking(userId) {
this.$router.push({ name: "bookingReport", params: { id: userId } });
},
},
};
</script> |
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:nysse_asemanaytto/core/components/layout.dart';
import 'package:nysse_asemanaytto/embeds/embeds.dart';
import './electricity_production_embed_settings.dart';
import '_electricity_production.dart';
import 'dart:developer' as developer;
GlobalKey<_ElectricityProductionEmbedWidgetState> _widgetState = GlobalKey();
class ElectricityProductionEmbed extends Embed {
const ElectricityProductionEmbed({required super.name});
@override
EmbedWidgetMixin<ElectricityProductionEmbed> createEmbed(
covariant ElectricityProductionEmbedSettings settings) =>
ElectricityProductionEmbedWidget(key: _widgetState, settings: settings);
@override
EmbedSettings<Embed> createDefaultSettings() =>
ElectricityProductionEmbedSettings(
apiKey: null,
pollRateMinutes: 3,
showPieChartTitles: true,
);
}
const List<Dataset> _datasets = [
Dataset(
id: 192,
updateRate: Duration(minutes: 3),
isTotalValue: true,
title: "Tuotanto",
unit: "MW",
color: Color(0xFF277158),
),
Dataset(
id: 193,
updateRate: Duration(minutes: 3),
isTotalValue: true,
title: "Kulutus",
unit: "MW",
color: Color(0xFF683956),
),
Dataset(
id: 188,
updateRate: Duration(minutes: 3),
title: "Ydinvoima",
unit: "MW",
color: Color(0xFFdcc81c),
),
Dataset(
id: 191,
updateRate: Duration(minutes: 3),
title: "Vesivoima",
unit: "MW",
color: Color(0xFF84c8f7),
),
Dataset(
id: 202,
updateRate: Duration(minutes: 3),
title: "Yhteistuotanto",
subtitle: "teollisuus",
unit: "MW",
color: Color(0xFF6d838f),
),
Dataset(
id: 201,
updateRate: Duration(minutes: 3),
title: "Yhteistuotanto",
subtitle: "kaukolämpö",
unit: "MW",
color: Color(0xFFd5dde3),
),
Dataset(
id: 181,
updateRate: Duration(minutes: 3),
title: "Tuulivoima",
unit: "MW",
color: Color(0xFF4d9d88),
),
Dataset(
id: 248,
updateRate: Duration(minutes: 15),
title: "Aurinkovoima",
unit: "MW",
color: Color(0xFFffef62),
),
Dataset(
id: 205,
updateRate: Duration(minutes: 3),
title: "Muu tuotanto",
unit: "MW",
color: Color(0xFFe5b2bb),
),
Dataset(
id: 183,
updateRate: Duration(minutes: 3),
title: "Tehoreservi",
unit: "MW",
color: Color(0xFFd5121e),
),
];
class ElectricityProductionEmbedWidget extends StatefulWidget
implements EmbedWidgetMixin<ElectricityProductionEmbed> {
final ElectricityProductionEmbedSettings settings;
const ElectricityProductionEmbedWidget({super.key, required this.settings});
@override
State<ElectricityProductionEmbedWidget> createState() =>
_ElectricityProductionEmbedWidgetState();
@override
Duration? getDuration() => const Duration(seconds: 15);
@override
void onDisable() {}
@override
void onEnable() {
if (settings.apiKey != null) {
_widgetState.currentState?.update();
}
}
}
const TextStyle _kDefaultTextStyle = TextStyle(
fontFamily: "Inter",
height: 1.0,
color: Color(0xFF3d5560),
);
class _ElectricityProductionEmbedWidgetState
extends State<ElectricityProductionEmbedWidget> {
final Map<int, double> data = {};
Exception? error;
DateTime? refreshAfter;
void update() {
DateTime now = DateTime.now();
if (refreshAfter != null && !now.isAfter(refreshAfter!)) {
return;
}
developer.log(
"Fetching electricity production data...",
name:
"_electricity_production_embed._ElectricityProductionEmbedWidgetState",
);
getData(
apiKey: widget.settings.apiKey!,
datasets: _datasets,
now: now,
).then((value) => _setData(value));
}
void _setData(FingridData data) {
setState(() {
refreshAfter = data.recommendedRefreshTime;
if (data.error != null) {
error = data.error;
} else {
for (final entry in data.data!.entries) {
this.data[entry.key.id] = entry.value;
}
}
});
}
@override
Widget build(BuildContext context) {
if (widget.settings.apiKey == null) {
return ErrorWidget.withDetails(message: "No API key provided.");
}
if (error != null) {
return ErrorWidget(error!);
}
Map<Dataset, double?> subproduction = Map.fromEntries(
_datasets
.where((e) => !e.isTotalValue)
.map((e) => MapEntry(e, data[e.id])),
);
double sumProduction = 0;
for (double? p in subproduction.values) {
if (p != null) {
sumProduction += p;
}
}
final layout = Layout.of(context);
return Container(
color: const Color(0xFFf3f6f8),
padding: EdgeInsets.all(layout.padding),
child: LayoutBuilder(builder: (context, constraints) {
final double elementHeight = constraints.maxHeight;
final double titleHeight = layout.tileHeight / 2;
final double chartSize = elementHeight - titleHeight - layout.padding;
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(
height: elementHeight,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
"Sähköjärjestelmän tila",
textAlign: TextAlign.center,
style: _kDefaultTextStyle.copyWith(
fontWeight: FontWeight.bold,
fontSize: titleHeight,
),
),
SizedBox(
height: chartSize,
child: AspectRatio(
aspectRatio: 1 / 1,
child: _ProductionChart(
data: subproduction,
dataSum: sumProduction,
showTitle: widget.settings.showPieChartTitles,
radius: chartSize / 2,
),
),
),
],
),
),
SizedBox(width: layout.padding),
Expanded(
child: _ProductionDataChart(
data: Map.fromEntries(
_datasets.map((e) => MapEntry(e, data[e.id])),
),
),
),
],
);
}),
);
}
}
class _ProductionChart extends StatelessWidget {
final Map<Dataset, double?> data;
final double dataSum;
final bool showTitle;
final double radius;
const _ProductionChart({
required this.data,
required this.dataSum,
required this.showTitle,
required this.radius,
});
@override
Widget build(BuildContext context) {
final List<PieChartSectionData> sections =
data.entries.where((e) => e.value != null).map(
(e) {
double value = e.value!;
double frac = value / dataSum;
return PieChartSectionData(
value: e.value,
color: e.key.color,
radius: radius,
showTitle: showTitle && frac >= 0.1,
title: "${(frac * 100).round()} %",
titleStyle: _kDefaultTextStyle.copyWith(fontWeight: FontWeight.bold),
);
},
).toList(growable: true);
// sort as reverse so that chart goes from biggest down clockwise
sections.sort((a, b) => b.value.compareTo(a.value));
return PieChart(
PieChartData(
centerSpaceRadius: 0,
sectionsSpace: radius / 100,
borderData: FlBorderData(show: false),
startDegreeOffset: -90,
pieTouchData: PieTouchData(enabled: false),
sections: sections,
),
);
}
}
class _ProductionDataChart extends StatelessWidget {
final Map<Dataset, double?> data;
const _ProductionDataChart({
required this.data,
});
@override
Widget build(BuildContext context) {
final layout = Layout.of(context);
final List<Widget> children = data.entries
.map(
(e) => __ProductionData(
title: e.key.title,
subtitle: e.key.subtitle,
value: e.value,
color: e.key.color,
icon: e.key.isTotalValue
? SvgPicture.asset(
"assets/images/icon_fingrid_chart.svg",
colorFilter:
const ColorFilter.mode(Colors.white, BlendMode.srcIn),
)
: null,
),
)
.toList(growable: false);
return LayoutBuilder(builder: (context, constraints) {
final double spacingX = layout.quarterPadding;
final double spacingY = layout.quarterPadding;
const int crossAxisCount = 2;
final int rowCount = (children.length / crossAxisCount).ceil();
final double trueWidth =
constraints.maxWidth - ((crossAxisCount - 1) * spacingX);
final double trueHeight =
constraints.maxHeight - ((rowCount - 1) * spacingY);
final double childWidth = trueWidth / crossAxisCount;
final double childHeight = trueHeight / rowCount;
return GridView.count(
crossAxisCount: crossAxisCount,
mainAxisSpacing: spacingY,
crossAxisSpacing: spacingX,
childAspectRatio: childWidth / childHeight,
children: children,
);
});
}
}
class __ProductionData extends StatelessWidget {
final String title;
final String? subtitle;
final double? value;
final Color color;
final Widget? icon;
const __ProductionData({
required this.title,
required this.subtitle,
required this.value,
required this.color,
required this.icon,
});
@override
Widget build(BuildContext context) {
return LayoutBuilder(builder: (context, constraints) {
final layout = Layout.of(context);
final double fontSize = constraints.maxHeight / 6;
final TextStyle textStyle =
_kDefaultTextStyle.copyWith(fontSize: fontSize);
return Container(
padding: EdgeInsets.only(
left: layout.halfPadding,
right: layout.halfPadding,
),
color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget?>[
Text(title, style: textStyle),
subtitle != null
? Text(
subtitle!,
style: textStyle.copyWith(
color: textStyle.color!.withAlpha(192),
fontStyle: FontStyle.italic,
),
)
: null,
SizedBox(height: layout.quarterPadding),
Row(
children: [
SizedBox(
width: 2 * fontSize,
height: 2 * fontSize,
child: DecoratedBox(
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(layout.halfPadding),
),
child: Center(
child: SizedBox(
width: 1.5 * fontSize,
height: 1.5 * fontSize,
child: icon,
),
),
),
),
SizedBox(width: layout.quarterPadding),
Text(
(value?.round() ?? "???").toString(),
style: textStyle.copyWith(
fontWeight: FontWeight.bold,
fontSize: fontSize * 2,
),
),
SizedBox(width: layout.quarterPadding),
Padding(
padding: EdgeInsets.only(top: fontSize / 2),
child: Text(
"MW",
style: textStyle,
),
),
],
),
].nonNulls.toList(growable: false),
),
);
});
}
} |
package no.elg.hex.screens
import com.badlogic.gdx.Gdx
import no.elg.hex.Hex
import no.elg.hex.event.HexagonChangedTeamEvent
import no.elg.hex.event.HexagonVisibilityChanged
import no.elg.hex.event.SimpleEventListener
import no.elg.hex.input.BasicIslandInputProcessor
import no.elg.hex.input.BasicIslandInputProcessor.Companion.MAX_ZOOM
import no.elg.hex.input.BasicIslandInputProcessor.Companion.MIN_ZOOM
import no.elg.hex.input.SmoothTransition
import no.elg.hex.island.Island
import no.elg.hex.renderer.OutlineRenderer
import no.elg.hex.renderer.SpriteRenderer
import no.elg.hex.renderer.StrengthBarRenderer
import no.elg.hex.renderer.VerticesRenderer
import no.elg.hex.screens.SplashIslandScreen.Companion.createIslandScreen
import no.elg.hex.util.GridSize.Companion.calculateGridSize
import no.elg.hex.util.isLazyInitialized
import kotlin.math.max
/** @author Elg */
open class PreviewIslandScreen(val id: Int, val island: Island, private val isPreviewRenderer: Boolean) : AbstractScreen(), ReloadableScreen {
val basicIslandInputProcessor by lazy { BasicIslandInputProcessor(this) }
var smoothTransition: SmoothTransition? = null
private val visibleGridSize
get() = if (Hex.args.mapEditor) {
island.calculateGridSize()
} else {
lazyVisibleGridSize
}
private val lazyVisibleGridSize by lazy { island.calculateGridSize() }
private val verticesRenderer by lazy { VerticesRenderer(this) }
private val outlineRenderer by lazy { OutlineRenderer(this) }
private val spriteRenderer by lazy { SpriteRenderer(this) }
private val strengthBarRenderer by lazy { StrengthBarRenderer(this.island) }
private lateinit var teamChangedListener: SimpleEventListener<HexagonChangedTeamEvent>
private lateinit var visibilityChangedListener: SimpleEventListener<HexagonVisibilityChanged>
override fun render(delta: Float) {
verticesRenderer.frameUpdate()
outlineRenderer.frameUpdate()
spriteRenderer.frameUpdate()
if (!isPreviewRenderer) {
if (StrengthBarRenderer.isEnabled) {
strengthBarRenderer.frameUpdate()
}
smoothTransition?.zoom(delta)?.also { done ->
if (done) {
smoothTransition = null
}
}
}
}
fun centerCamera() {
val data = island.grid.gridData
if (island.allHexagons.isEmpty()) return
with(visibleGridSize) {
// Sum the distance from the edge of the grid to the first visible hexagon
// |.###..| (`.` are invisible, `#` are visible hexagons)
// The offset would then be 3
val gridWidthOffset = maxInvX - minX - maxX
val gridHeightOffset = maxInvY - minY - maxY
val islandCenterX = (maxInvX - gridWidthOffset) / 2
val islandCenterY = (maxInvY - gridHeightOffset) / 2
// Add some padding as the min/max x/y are calculated from the center of the hexagons
val widthZoom = (maxX - minX + ZOOM_PADDING_HEXAGONS * data.hexagonWidth) / camera.viewportWidth
val heightZoom = (maxY - minY + ZOOM_PADDING_HEXAGONS * data.hexagonHeight) / camera.viewportHeight
camera.position.x = islandCenterX.toFloat()
camera.position.y = islandCenterY.toFloat()
camera.zoom = max(widthZoom, heightZoom).toFloat()
}
if (!isPreviewRenderer) {
enforceCameraBounds(false)
}
updateCamera()
}
fun enforceCameraBounds(updateCamera: Boolean = true) {
with(visibleGridSize) {
camera.position.x = camera.position.x.coerceIn(minX.toFloat(), maxX.toFloat())
camera.position.y = camera.position.y.coerceIn(minY.toFloat(), maxY.toFloat())
}
camera.zoom = camera.zoom.coerceIn(MIN_ZOOM, MAX_ZOOM)
if (updateCamera) {
updateCamera()
Gdx.graphics.requestRendering()
}
}
override fun resize(width: Int, height: Int) {
super.resize(width, height)
if (StrengthBarRenderer.isEnabled) {
strengthBarRenderer.resize(width, height)
}
centerCamera()
}
override fun recreate(): AbstractScreen =
createIslandScreen(id, island, false).also {
Gdx.app.postRunnable {
it.resize(Gdx.graphics.width, Gdx.graphics.height)
it.camera.combined.set(camera.combined)
it.camera.position.set(camera.position)
it.camera.zoom = camera.zoom
}
}
override fun show() {
basicIslandInputProcessor.show()
if (!isPreviewRenderer) {
teamChangedListener = SimpleEventListener.create {
island.hexagonsPerTeam.compute(it.old) { _, old -> (old ?: 0) - 1 }
island.hexagonsPerTeam.compute(it.new) { _, old -> (old ?: 0) + 1 }
}
visibilityChangedListener = SimpleEventListener.create {
island.hexagonsPerTeam.compute(it.data.team) { _, old -> (old ?: 0) + if (it.isDisabled) -1 else 1 }
}
}
}
override fun dispose() {
island.select(null)
super.dispose()
if (::verticesRenderer.isLazyInitialized) {
verticesRenderer.dispose()
}
if (::outlineRenderer.isLazyInitialized) {
outlineRenderer.dispose()
}
if (::spriteRenderer.isLazyInitialized) {
spriteRenderer.dispose()
}
if (::strengthBarRenderer.isLazyInitialized) {
strengthBarRenderer.dispose()
}
if (::teamChangedListener.isInitialized) {
teamChangedListener.dispose()
}
if (::visibilityChangedListener.isInitialized) {
visibilityChangedListener.dispose()
}
}
companion object {
const val ZOOM_PADDING_HEXAGONS = 2
}
} |
from pydantic import BaseSettings
class Settings(BaseSettings):
PROJECT_NAME: str
SECRET_KEY: str
DEBUG: str
ALLOWED_HOSTS: list[str] = ["http://localhost", "http://127.0.0.1"]
DOCS_URL: str | None = None
OPENAPI_URL: str | None = None
REDOC_URL: str | None = None
class Config:
env_file: str = ".env"
env_file_encoding: str = "utf-8"
settings = Settings() |
using System;
using System.Collections.Generic;
using Unity.XR.CoreUtils;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.Interaction.Toolkit;
namespace com.perceptlab.armultiplayer
{
public class AlignTheWorld : MonoBehaviour
{
private ARSession _ARSession;
[Header("XR Rig and Player Set up")]
[SerializeField, Tooltip("The game object in hierarchy that moves with locomotion; \"Camera Offset\" in MRTK XR Rig and \"XR Origin\" in VR")]
GameObject player;
[SerializeField, Tooltip("The camera")]
GameObject player_camera;
[SerializeField, Tooltip("When reset is pressed the camera's position will be set to this transform's position, if not provided, the starting position will be used")]
private Transform defaultCameraTransform;
[Header("Input")]
// assign the actions asset to this field in the inspector:
[SerializeField, Tooltip("The action asset with MoveX, MoveY, MoveZ, RotateY, 1D axes and ActivateAlign and DoneAlign buttons")]
private InputActionAsset actions;
[Header("Speed")]
[SerializeField]
private float move_speed = 0.03f;
[SerializeField]
private float rotatoin_speed = 1f;
[SerializeField]
public UnityEvent onDoneAlign;
private bool active = true;
private bool done = false;
private InputAction moveX;
private InputAction moveY;
private InputAction moveZ;
private InputAction rotateY;
private Vector3 defaultCameraPosition;
private void Awake()
{
RLogger.Log("Align the world is active");
actions.FindActionMap("Align").FindAction("ActivateAlign").performed += OnActivateAlign;
actions.FindActionMap("Align").FindAction("DoneAlign").performed += OnDoneAlign;
actions.FindActionMap("Align").FindAction("Reset").performed += OnReset;
moveX = actions.FindActionMap("Align").FindAction("MoveX");
moveY = actions.FindActionMap("Align").FindAction("MoveY");
moveZ = actions.FindActionMap("Align").FindAction("MoveZ");
rotateY = actions.FindActionMap("Align").FindAction("RotateY");
defaultCameraPosition = (defaultCameraTransform == null)? player_camera.transform.position: defaultCameraTransform.position;
}
private void Start()
{
RLogger.Log("Align the world is active");
_ARSession = GetComponent<ARSession>();
if (_ARSession != null)
{
_ARSession.enabled = true;
}
}
private void OnActivateAlign(InputAction.CallbackContext context)
{
RLogger.Log("BeginEndAlign was pressed");
active = !active;
if (_ARSession != null)
{
_ARSession.enabled = active;
}
}
private void OnDoneAlign(InputAction.CallbackContext context)
{
if (done)
return;
RLogger.Log("DoneAlign was pressed, player position is: " + player.transform.position);
active = false;
done = true;
onDoneAlign?.Invoke();
if (_ARSession != null)
{
_ARSession.enabled = false;
// revert the changes caused by _ARSession.MatchFrameRate = True
Application.targetFrameRate = 0;
QualitySettings.vSyncCount = 1;
}
actions.FindActionMap("Align").Disable();
}
private void OnReset(InputAction.CallbackContext context)
{
RLogger.Log("Reset was pressed");
moveCameraToDestination(defaultCameraPosition);
makeCameraFaceDirection(Vector3.right);
}
private void moveCameraToDestination(Vector3 destination)
{
Vector3 diff = player_camera.transform.position - player.transform.position;
player.transform.position = destination + diff;
}
private void makeCameraFaceDirection(Vector3 direction)
{
direction.y = 0; direction.Normalize();
Vector3 cameraFacing = player_camera.transform.forward; cameraFacing.y = 0; cameraFacing.Normalize();
float angle = Vector3.SignedAngle(cameraFacing, direction, Vector3.up);
player.transform.RotateAround(player_camera.transform.position, Vector3.up, angle);
}
// Moves the player instead of the world. Player is in the same real position, thus, the virtual world is being moved!
void Update()
{
if (done)
{
RLogger.Log("align the world is destroyed cause: done");
Destroy(this);
}
if (active)
{
movePlayer();
}
}
void movePlayer()
{
float movex = moveX.ReadValue<float>();
float movez = -moveZ.ReadValue<float>();
float movey = -moveY.ReadValue<float>();
float rotatey = rotateY.ReadValue<float>();
//Vector3 player_forward = player_camera.transform.forward; player_forward.y = 0f; player_forward = Vector3.Normalize(player_forward);
//Vector3 player_right = player_camera.transform.right; player_right.y = 0f; player_right = Vector3.Normalize(player_right);
//Vector3 translate = - player_forward*movez + player_right*movex - Vector3.up*movey;
Vector3 translate = -Vector3.right * movez - Vector3.forward * movex - Vector3.up * movey;
player.transform.Translate(-1f* translate * move_speed, Space.World);
// if we assume objects are rendered straight up, which we did!, we only need to rotate the room about the world y axis to adjust (we have assuemd x and z axes rotations are 0)
player.transform.RotateAround(player.transform.position, Vector3.up, -1f * rotatey * rotatoin_speed);
}
void OnEnable()
{
actions.FindActionMap("Align").Enable();
}
void OnDisable()
{
actions.FindActionMap("Align").Disable();
}
// alternatively, you can move the room instead of player (the logic might be easier) and when done align is pressed, call relocate to add room to origin and relocate the player
// this method is not tested
//private void PerformRelocatin()
//{
// // a_pos = diff_pos + b_pos => diff_pos = a_pos - b_pos => diff_pos = new_a_pos - new_b_pos => new_a_pos = diff_pos + new_b_pos
// // a_rot = diff_rot * b_rot => diff_rot = a_rot * inverse(b_rot) => diff_rot = new_a_rot * inverse(new_b_rot) => new_a_rot = diff_rot*new_b_rot
// RLogger.Log("performing relocation");
// Vector3 diff_pos = player.transform.position - room.transform.position;
// Quaternion diff_rot = player.transform.rotation * Quaternion.Inverse(room.transform.rotation);
// room.transform.position = Vector3.zero;
// room.transform.rotation = Quaternion.identity;
// player.transform.position = diff_pos;
// player.transform.rotation = diff_rot;
// RLogger.Log("relocation performed");
//}
/*********************************************
* list of all required defined buttons and axes:
* BegnEndAlign : button
* DoneAlign: button
* Reset: button
* MoveX: axis -1 to 1
* MoveZ: axis -1 to 1
* MoveY: axix -1 to 1
* RotateY: axis -1 to 1
*********************************************/
}
} |
package tp1;
import java.util.Iterator;
public class MySimpleLinkedList implements Iterable<Integer>{
private Node first;
private int size;
public MySimpleLinkedList() {
this.first = null;
this.size = 0;
}
public void insertFront(int info) {
Node tmp = new Node(info,null);
tmp.setNext(this.first);
this.first = tmp;
size++;
}
public Integer extractFront() {
if (this.first != null) {
Node tmp = this.first;
this.first = this.first.getNext();
this.size--;
return tmp.getInfo();
} else {
return null;
}
}
public boolean isEmpty() {
return this.first == null;
}
public int get(int index) {
int contador = 0;
Node tmp = this.first;
while(contador < index) {
tmp = tmp.getNext();
contador++;
}
return tmp.getInfo();
}
public int size() {
return this.size;
}
@Override
public String toString() {
String aux = "";
int contador = 0;
Node tmp = this.first;
while(contador < this.size) {
aux += tmp.toString() + " - ";
tmp = tmp.getNext();
contador++;
}
return aux;
}
@Override
public Iterator<Integer> iterator(){
return new MyIterator(this.first);
}
public void ordenarLista(MySimpleLinkedList lista) {
if(size > 1) {
boolean cambio;
do {
Node actual = this.first;
Node anterior = null;
Node siguiente = first.getNext();
cambio = false;
while (siguiente != null) {
if(actual.getInfo() > siguiente.getInfo()) {
cambio = true;
if(anterior != null) {
Node sig = siguiente.getNext();
anterior.setNext(siguiente);
siguiente.setNext(actual);
actual.setNext(sig);
} else {
Node sig = siguiente.getNext();
first = siguiente;
siguiente.setNext(actual);
actual.setNext(sig);
}
anterior = siguiente;
siguiente = actual.getNext();
} else {
anterior = actual;
actual = siguiente;
siguiente = siguiente.getNext();
}
}
} while (cambio);
}
}
public boolean buscar(Integer e, MySimpleLinkedList l2) {
boolean esta = false;
for (Integer el: l2) {
if(el == e) {
esta = true;
}
}
return esta;
}
public MySimpleLinkedList buscarComun(MySimpleLinkedList l1, MySimpleLinkedList l2) {
MySimpleLinkedList aux = new MySimpleLinkedList();
for (Integer el1: l1) {
if(l1.buscar(el1, l2)) {
aux.insertFront(el1);
}
}
aux.ordenarLista(aux);
return aux;
}
public MySimpleLinkedList primeraSiSegundaNo(MySimpleLinkedList l1, MySimpleLinkedList l2) {
MySimpleLinkedList aux = new MySimpleLinkedList();
for (Integer el1: l1) {
if(!l1.buscar(el1, l2)) {
aux.insertFront(el1);
}
}
aux.ordenarLista(aux);
return aux;
}
} |
const express = require('express');
const cors = require('cors');
const { default: mongoose } = require('mongoose');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const cookieParser = require('cookie-parser');
const User = require('./models/User.js');
require('dotenv').config();
const app = express();
const bcryptSalt = bcrypt.genSaltSync(10);
const jwtSecret = 'fhjakkbatjaLnbcbjlksbsln46kb6hc';
// Parses JSON from the Request
// Password: Q7uuCFXnVX4PxjHe
app.use(express.json());
app.use(cookieParser());
app.use(cors({
credentials: true,
origin: 'http://127.0.0.1:5173',
}));
mongoose.connect(process.env.MONGO_URL)
.then(() => {
console.log('Connected to MongoDB');
})
.catch((error) => {
console.error('MongoDB connection error:', error);
});
// mongoose.connect(process.env.MONGO_URL)
console.log(process.env.MONGO_URL)
app.get('/test', (req, res) => {
res.json('test ok');
});
app.post('/register', async (req, res) => {
try {
const { name, email, password } = req.body;
const userDoc = await User.create({
name,
email,
password: bcrypt.hashSync(password, bcryptSalt),
});
res.json(userDoc);
} catch (error) {
console.error(error);
res.status(422).json({ error: 'unprocessable entity' });
}
});
app.post('/login', async(req,res) => {
const {email,password} = req.body
const userDoc = await User.findOne({email});
// console.log(userDoc)
if (userDoc){
const passOk = bcrypt.compareSync(password, userDoc.password);
if (passOk ){
jwt.sign({
email:userDoc.email,
id:userDoc._id,
// name:userDoc.name
}, jwtSecret, {}, (err,token) => {
if (err) throw err;
res.cookie('token', token).json(userDoc);
});
} else {
res.json('Pass not Okay')
}
// res.json('found');
} else {
res.status(422).json('Not Found')
}
})
app.get('/profile', (req, res) => {
const {token} = req.cookies;
if (token) {
jwt.verify(token,jwtSecret, {}, async(err, userData) => {
if (err) throw err;
const {name, email, _id} = await User.findById(userData.id);
res.json({name, email, _id});
})
}
})
app.post('/logout', (req, res) => {
res.cookie('token', '').json(true);
});
app.listen(4000); |
document.addEventListener('DOMContentLoaded', function () {
const recipeContainer = document.getElementById('recipes');
const searchForm = document.getElementById('searchForm');
const closeButton = document.querySelector('.recipe-modal-close');
const recipeModal = document.getElementById('recipe-modal');
// Función para obtener las recetas de la API
async function fetchRecipes(query = '') {
try {
let url = 'https://www.themealdb.com/api/json/v1/1/search.php?s=';
if (query) {
url += query; // Si hay una consulta, se agrega al final de la URL
}
const response = await fetch(url);
const data = await response.json();
displayRecipes(data.meals); // Llama a la función para mostrar las recetas
} catch (error) {
console.error('Error fetching recipes:', error);
}
}
// Función para mostrar las recetas en la página
function displayRecipes(recipes) {
recipeContainer.innerHTML = ''; // Limpia el contenedor antes de agregar las nuevas recetas
if (recipes) {
recipes.forEach(recipe => {
const recipeCard = document.createElement('div');
recipeCard.classList.add('recipe-card');
recipeCard.innerHTML = `
<img src="${recipe.strMealThumb}" alt="${recipe.strMeal}">
<h3>${recipe.strMeal}</h3>
`;
recipeContainer.appendChild(recipeCard);
// Agregar evento de clic a la tarjeta de receta
recipeCard.addEventListener('click', () => {
showRecipeDetails(recipe);
});
});
} else {
recipeContainer.innerHTML = '<p>No se encontraron recetas. Intenta una nueva búsqueda.</p>';
}
}
// Función para mostrar los detalles de una receta en el modal
function showRecipeDetails(recipe) {
const recipeDetails = document.getElementById('recipe-details');
// Limpiar el contenido del modal antes de mostrar los nuevos detalles
recipeDetails.innerHTML = '';
// Crear el contenido HTML con los detalles de la receta
const recipeHTML = `
<h2>${recipe.strMeal}</h2>
<img src="${recipe.strMealThumb}" alt="${recipe.strMeal}">
<h3>Ingredientes:</h3>
<ul>
${getIngredientsList(recipe)}
</ul>
<h3>Instrucciones:</h3>
<p>${recipe.strInstructions}</p>
`;
// Agregar el contenido HTML al modal
recipeDetails.innerHTML = recipeHTML;
// Mostrar el modal
recipeModal.style.display = 'block';
}
// Función auxiliar para obtener la lista de ingredientes
function getIngredientsList(recipe) {
let ingredientsList = '';
for (let i = 1; i <= 20; i++) {
const ingredient = recipe[`strIngredient${i}`];
const measure = recipe[`strMeasure${i}`];
if (ingredient && measure) {
ingredientsList += `<li>${ingredient} - ${measure}</li>`;
}
}
return ingredientsList;
}
// Evento para el envío del formulario de búsqueda
searchForm.addEventListener('submit', function (event) {
event.preventDefault(); // Evita el envío del formulario
const query = document.getElementById('query').value.trim();
fetchRecipes(query); // Realiza la búsqueda con la consulta ingresada
});
// Evento para cerrar el modal al hacer clic en la cruz
closeButton.addEventListener('click', function() {
recipeModal.style.display = 'none';
});
// Obtener las recetas iniciales sin consulta
fetchRecipes();
}); |
#include "glad.h"
#include <vector>
#include "Shader.h"
#include "Debug.h"
#include "File.h"
static Debugger *debug = new Debugger("Shader", DEBUG_ALL);
Shader::Shader(){
};
void Shader::CreateComputeShader(const char* comp_path){
debug->Info("Load and compile: %s ...\n",comp_path);
size_t comp_data_sz = 0;
uint8_t* comp_data = LoadFile(comp_path,&comp_data_sz);
if (!comp_data){
return;
}
int compid = -1;
debug->Info("Compiling compute shader : %s\n", comp_path);
compid = CompileCompute((char*)comp_data,comp_data_sz);
debug->Info("Linking program\n");
progid = LinkProgram(1,compid);
//TODO: Figure out if loaded from file or from memory.
//free(comp_data);
};
Shader::Shader(const char* vert_path,const char* frag_path):Shader(){
debug->Info("Load and compile: %s, %s ...\n",vert_path,frag_path);
size_t vert_data_sz = 0;
uint8_t* vert_data = LoadFile(vert_path,&vert_data_sz);
if (!vert_data){
return;
}
size_t frag_data_sz = 0;
uint8_t* frag_data = LoadFile(frag_path,&frag_data_sz);
if (!frag_data){
return;
}
int vertid = -1;
int fragid = -1;
debug->Info("Compiling vertex shader : %s\n", vert_path);
vertid = CompileVertex((char*)vert_data,vert_data_sz);
debug->Info("Compiling fragment shader : %s\n", frag_path);
fragid = CompileFragment((char*)frag_data,frag_data_sz);
debug->Info("Linking program\n");
progid = LinkProgram(2,vertid,fragid);
//TODO: Figure out if loaded from file or from memory.
//free(vert_data);
//free(frag_data);
}
Shader::~Shader(){
};
int Shader::CompileVertex(char* vert_data, size_t size){
int id = glCreateShader(GL_VERTEX_SHADER);
GLint result = GL_FALSE;
int infolen = 0;
GLint sz = size;
glShaderSource(id, 1, (const char**)&vert_data , &sz);
glCompileShader(id);
glGetShaderiv(id, GL_COMPILE_STATUS, &result);
glGetShaderiv(id, GL_INFO_LOG_LENGTH, &infolen);
if (!result){
char* errormsg = (char*)malloc(infolen+1);
glGetShaderInfoLog(id, infolen, NULL, errormsg);
debug->Fatal("CompileVertex: error: %s\n", errormsg);
free(errormsg);
return 0;
}else{
debug->Ok("Vertex shader compiled\n");
}
return id;
}
int Shader::CompileFragment(char* frag_data, size_t size){
int id = glCreateShader(GL_FRAGMENT_SHADER);
GLint result = GL_FALSE;
int infolen = 0;
GLint sz = size;
glShaderSource(id, 1, (const char**)&frag_data , &sz);
glCompileShader(id);
glGetShaderiv(id, GL_COMPILE_STATUS, &result);
glGetShaderiv(id, GL_INFO_LOG_LENGTH, &infolen);
if (!result){
char* errormsg = (char*)malloc(infolen+1);
glGetShaderInfoLog(id, infolen, NULL, errormsg);
debug->Fatal("CompileFragment: error: %s\n", errormsg);
free(errormsg);
return 0;
}else{
debug->Ok("Fragment shader compiled\n");
}
return id;
}
int Shader::CompileCompute(char* comp_data, size_t size){
int id = glCreateShader(GL_COMPUTE_SHADER);
GLint result = GL_FALSE;
int infolen = 0;
GLint sz = size;
glShaderSource(id, 1, (const char**)&comp_data , &sz);
glCompileShader(id);
glGetShaderiv(id, GL_COMPILE_STATUS, &result);
glGetShaderiv(id, GL_INFO_LOG_LENGTH, &infolen);
if (!result){
char* errormsg = (char*)malloc(infolen+1);
glGetShaderInfoLog(id, infolen, NULL, errormsg);
debug->Fatal("CompileFragment: error: %s\n", errormsg);
free(errormsg);
return 0;
}else{
debug->Ok("Compute shader compiled\n");
}
return id;
}
int Shader::LinkProgram(int count, ...){
GLint result = GL_FALSE;
int infolen = 0;
GLuint programid = glCreateProgram();
va_list arglist;
va_start(arglist,count);
std::vector<int>ids;
for (int i = 0; i < count; ++i) {
int id = va_arg(arglist, int);
glAttachShader(programid, id);
ids.push_back(id);
debug->Info("LinkProgram: Attaching ID %i\n",id);
}
va_end(arglist);
glLinkProgram(programid);
// Check the program
glGetProgramiv(programid, GL_LINK_STATUS, &result);
glGetProgramiv(programid, GL_INFO_LOG_LENGTH, &infolen);
if (!result){
char* errormsg = (char*)malloc(infolen+1);
glGetProgramInfoLog(programid, infolen, NULL, errormsg);
debug->Fatal("LinkProgram: error: %s\n", errormsg);
free(errormsg);
return 0;
}else{
debug->Info("LinkProgram: Linked! ID: %i\n",programid);
}
for (int id:ids){
glDetachShader(programid, id);
glDeleteShader(id);
}
//The data may now be deleted.
return programid;
}
void Shader::Use(){
glUseProgram(progid);
}
//Set a uniform int
void Shader::Setint(const char* name, int value){
GLuint intid = glGetUniformLocation(progid, name);
if (intid == -1){
//Warn once.
debug->Fatal("Could not set %i's int %s\n",progid,name);
return;
}
glUniform1i(intid,(GLint)value);
}
void Shader::Setvec3(const char* name, const vec3& value){
GLuint fid = glGetUniformLocation(progid, name);
if (fid == -1){
debug->Warn("Could not set %i's vec3 %s\n",progid,name);
return;
}
glUniform3fv(fid,1,(GLfloat*)&value);
}
void Shader::Setmat3(const char* name, const fmat3& matrix){
GLuint matid = glGetUniformLocation(progid, name);
if (matid == -1){
debug->Fatal("Could not set %i's mat4 %s\n",progid,name);
return;
}
glUniformMatrix3fv(matid,1,GL_FALSE,(GLfloat*)&matrix);
}
void Shader::Setmat4(const char* name, const fmat4& matrix){
GLuint matid = glGetUniformLocation(progid, name);
if (matid == -1){
debug->Fatal("Could not set %i's mat4 %s\n",progid,name);
return;
}
glUniformMatrix4fv(matid,1,GL_FALSE,(GLfloat*)&matrix);
} |
import React, { lazy, Suspense } from 'react';
import { Route, BrowserRouter as Router, Switch } from 'react-router-dom';
import './App.scss';
import { Nav } from './nav/nav';
import { Loading } from './loading/loading';
import { Footer } from './footer/footer';
function RouteWithSubRoutes(route) {
return (
<Route
path={route.path}
render={props => (
// pass the sub-routes down to keep nesting
<route.component {...props} routes={route.routes} />
)}
/>
);
}
function App() {
const routes = [
{
path: '/game/:gameId',
component: lazy(() => import('./pages/game/game-page'))
},
{
path: '/game/',
component: lazy(() => import('./pages/game/game-splash-page'))
},
{
path: '/retro/:retroId',
component: lazy(() => import('./pages/retro/retro-page'))
},
{
path: '/retro',
component: lazy(() => import('./pages/retro/retro-splash-page'))
},
{
path: '/',
component: lazy(() => import('./pages/home/home-page'))
}
];
return (
<Router>
<Nav />
<div className="page-content">
<Suspense fallback={<Loading />}>
<div className="container is-fluid">
<Switch>
{routes.map((route, i) => (
<RouteWithSubRoutes key={i} {...route} />
))}
</Switch>
</div>
</Suspense>
</div>
<Footer />
</Router>
);
}
export default App; |
import action from "../../assets/action.png";
import drama from "../../assets/drama.png";
import fantasy from "../../assets/fantasy.png";
import fiction from "../../assets/fiction.png";
import horror from "../../assets/horror.png";
import music from "../../assets/music.png";
import romance from "../../assets/romance.png";
import thriller from "../../assets/thriller.png";
import western from "../../assets/western.png";
import Category from "./Category";
import styles from "./Categories.module.css";
import CategorySidebar from "./CategorySidebar";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
const categoriesList = [
{
id: "Action",
color: "#FF5209",
src: action,
},
{
id: "Drama",
color: "#D7A4FF",
src: drama,
},
{
id: "Fantasy",
color: " #FF4ADE",
src: fantasy,
},
{
id: "Fiction",
color: "#6CD061",
src: fiction,
},
{
id: "Horror",
color: "#7358FF",
src: horror,
},
{
id: "Music",
color: "#E61E32",
src: music,
},
{
id: "Romance",
color: "#11B800",
src: romance,
},
{
id: "Thriller",
color: "#84C2FF",
src: thriller,
},
{
id: "Western",
color: "#912500",
src: western,
},
];
const KEY = "Categories";
function Categories() {
const [categories, setCategories] = useState([]);
const [error, setError] = useState();
const navigate = useNavigate();
function handelSubmit() {
if (categories.length < 3) {
setError("Minimum 3 category required");
return;
}
localStorage.setItem(KEY, JSON.stringify([...categories]));
navigate("/home");
}
return (
<>
<CategorySidebar
categories={categories}
setCategories={setCategories}
error={error}
/>
<div className={styles.container}>
{categoriesList.map((item) => (
<Category
data={item}
key={item.id}
categories={categories}
setCategories={setCategories}
/>
))}
{categories.length !== 0 ? (
<button className={styles.next} onClick={handelSubmit}>
Next Page
</button>
) : null}
</div>
</>
);
}
export default Categories; |
using System.Text.Json;
using FluentAssertions;
using NSubstitute;
using RichardSzalay.MockHttp;
using Taxjar;
using Taxjar.Tests.Infrastructure;
using Taxjar.Tests.Fixtures;
using Microsoft.Extensions.Options;
namespace TaxJar.Tests;
public class Transactions
{
protected IHttpClientFactory httpClientFactory;
protected IOptions<TaxjarApiOptions> options = Substitute.For<IOptions<TaxjarApiOptions>>();
protected string apiToken;
protected string transactionOrdersEndpoint;
protected string refundOrdersEndpoint;
protected Dictionary<string, string> defaultHeaders;
[SetUp]
public void Init()
{
apiToken = TaxjarFakes.Faker.Internet.Password();
httpClientFactory = Substitute.For<IHttpClientFactory>();
options.Value.Returns(new TaxjarApiOptions
{
JsonSerializerOptions = TaxjarConstants.TaxJarDefaultSerializationOptions,
ApiToken = TaxjarFakes.Faker.Internet.Password(),
ApiUrl = TaxjarFakes.Faker.Internet.UrlWithPath(protocol: "https", domain: "api.taxjartest.com"),
ApiVersion = "v2",
UseSandbox = false
});
transactionOrdersEndpoint = $"{options.Value.ApiUrl}/{TaxjarConstants.TransactionOrdersEndpoint}";
refundOrdersEndpoint = $"{options.Value.ApiUrl}/{TaxjarConstants.TransactionRefundsEndpoint}";
defaultHeaders = new Dictionary<string, string>{
{"Authorization", $"Bearer {options.Value.ApiToken}" },
{"Accept", "application/json"}
};
}
[Test]
public async Task when_listing_order_transactions_by_transaction_date_async()
{
//arrange
var taxJarOrderFilter = new OrderFilter{
TransactionDate = TaxjarFakes.Faker.Date.Past(1),
};
var expected = TaxjarFakes.FakeOrdersResponse().Generate();
var jsonResponseBody = JsonSerializer.Serialize(expected, options.Value.JsonSerializerOptions);
var handler = new MockHttpMessageHandler();
handler
.When(HttpMethod.Get, transactionOrdersEndpoint)
.WithQueryString($"transaction_date={taxJarOrderFilter.TransactionDate:yyyy/MM/dd}")
.WithHeaders(defaultHeaders)
.Respond("application/json", jsonResponseBody);
httpClientFactory.CreateClient(nameof(TaxjarApi))
.Returns(new HttpClient(handler));
var sut = new TaxjarApi(httpClientFactory, options);
//act
var result = await sut.ListOrdersAsync(taxJarOrderFilter);
//assert
result.Should().NotBeNull();
result.Should().BeEquivalentTo(expected.Orders);
}
[Test]
public async Task when_listing_order_transactions_by_date_range_async()
{
//arrange
var taxJarOrderFilter = new OrderFilter
{
FromTransactionDate = TaxjarFakes.Faker.Date.Past(1),
ToTransactionDate = DateTime.UtcNow
};
var expected = TaxjarFakes.FakeOrdersResponse().Generate();
var jsonResponseBody = JsonSerializer.Serialize(expected, options.Value.JsonSerializerOptions);
var handler = new MockHttpMessageHandler();
handler
.When(HttpMethod.Get, transactionOrdersEndpoint)
.WithQueryString($"from_transaction_date={taxJarOrderFilter.FromTransactionDate:yyyy/MM/dd}&to_transaction_date={taxJarOrderFilter.ToTransactionDate:yyyy/MM/dd}")
.WithHeaders(defaultHeaders)
.Respond("application/json", jsonResponseBody);
httpClientFactory.CreateClient(nameof(TaxjarApi))
.Returns(new HttpClient(handler));
var sut = new TaxjarApi(httpClientFactory, options);
//act
var result = await sut.ListOrdersAsync(taxJarOrderFilter);
//assert
result.Should().NotBeNull();
result.Should().BeEquivalentTo(expected.Orders);
}
[Test]
public async Task when_listing_order_transactions_by_provider_async()
{
//arrange
var taxJarOrderFilter = new OrderFilter
{
Provider = "api"
};
var expected = TaxjarFakes.FakeOrdersResponse().Generate();
var jsonResponseBody = JsonSerializer.Serialize(expected, options.Value.JsonSerializerOptions);
var handler = new MockHttpMessageHandler();
handler
.When(HttpMethod.Get, transactionOrdersEndpoint)
.WithQueryString($"provider={taxJarOrderFilter.Provider}")
.WithHeaders(defaultHeaders)
.Respond("application/json", jsonResponseBody);
httpClientFactory.CreateClient(nameof(TaxjarApi))
.Returns(new HttpClient(handler));
var sut = new TaxjarApi(httpClientFactory, options);
//act
var result = await sut.ListOrdersAsync(taxJarOrderFilter);
//assert
result.Should().NotBeNull();
result.Should().BeEquivalentTo(expected.Orders);
}
[Test]
public async Task when_showing_an_order_transaction_async()
{
//arrange
var jsonData = TaxjarFixture.GetJSON("orders/show.json");
var expected = JsonSerializer.Deserialize<OrderResponse>(jsonData, options.Value.JsonSerializerOptions);
var expectedTransactionId = expected!.Order!.TransactionId;
var jsonResponseBody = JsonSerializer.Serialize(expected, options.Value.JsonSerializerOptions);
var endpoint = $"{transactionOrdersEndpoint}/{expectedTransactionId}";
var handler = new MockHttpMessageHandler();
handler
.When(HttpMethod.Get, endpoint)
.WithHeaders(defaultHeaders)
.Respond("application/json", jsonResponseBody);
httpClientFactory.CreateClient(nameof(TaxjarApi))
.Returns(new HttpClient(handler));
var sut = new TaxjarApi(httpClientFactory, options);
//act
var result = await sut.ShowOrderAsync(expectedTransactionId);
//assert
result.Should().NotBeNull();
result.Should().BeEquivalentTo(expected.Order);
}
[Test]
public async Task when_showing_an_order_transaction_with_provider_async()
{
//arrange
var expected = TaxjarFakes.FakeOrderResponse().Generate();
var expectedTransactionId = expected!.Order!.TransactionId;
var expectedProvider = expected!.Order!.Provider;
var jsonResponseBody = JsonSerializer.Serialize(expected, options.Value.JsonSerializerOptions);
var endpoint = $"{transactionOrdersEndpoint}/{expectedTransactionId}?provider={expectedProvider}";
var handler = new MockHttpMessageHandler();
handler
.When(HttpMethod.Get, endpoint)
.WithHeaders(defaultHeaders)
.Respond("application/json", jsonResponseBody);
httpClientFactory.CreateClient(nameof(TaxjarApi))
.Returns(new HttpClient(handler));
var sut = new TaxjarApi(httpClientFactory, options);
//act
var result = await sut.ShowOrderAsync(expectedTransactionId, expectedProvider);
//assert
result.Should().NotBeNull();
result.Should().BeEquivalentTo(expected.Order);
}
[Test]
public async Task when_showing_an_order_without_transaction_throws_async()
{
//arrange
var sut = new TaxjarApi(httpClientFactory, options);
//act
Func<Task> act = async () => await sut.ShowOrderAsync(string.Empty);
//assert
await act.Should().ThrowAsync<ArgumentException>()
.WithMessage("*Transaction ID cannot be null or an empty string.*");
}
[Test]
public async Task when_creating_an_order_transaction_with_line_items_async()
{
//arrange
var request = TaxjarFakes.FakeTaxjarCreateOrderRequest(generateLineItems: true, generateCustomerId: true).Generate();
var jsonRequestBody = JsonSerializer.Serialize(request, options.Value.JsonSerializerOptions);
var expected = TaxjarFakes.FakeOrderResponse(generateLineItems: true).Generate();
var jsonResponseBody = JsonSerializer.Serialize(expected, options.Value.JsonSerializerOptions);
var handler = new MockHttpMessageHandler();
handler
.When(HttpMethod.Post, transactionOrdersEndpoint)
.WithHeaders(defaultHeaders)
.WithContent(jsonRequestBody)
.Respond("application/json", jsonResponseBody);
httpClientFactory.CreateClient(nameof(TaxjarApi))
.Returns(new HttpClient(handler));
var sut = new TaxjarApi(httpClientFactory, options);
//act
var result = await sut.CreateOrderAsync(request);
//assert
result.Should().NotBeNull();
result.Should().BeEquivalentTo(expected!.Order);
}
[Test]
public async Task when_creating_an_order_transaction_async()
{
//arrange
var request = TaxjarFakes.FakeTaxjarCreateOrderRequest().Generate();
var jsonRequestBody = JsonSerializer.Serialize(request, options.Value.JsonSerializerOptions);
var jsonData = TaxjarFixture.GetJSON("orders/show.json");
var expected = JsonSerializer.Deserialize<OrderResponse>(jsonData, options.Value.JsonSerializerOptions);
var jsonResponseBody = JsonSerializer.Serialize(expected, options.Value.JsonSerializerOptions);
var handler = new MockHttpMessageHandler();
handler
.When(HttpMethod.Post, transactionOrdersEndpoint)
.WithHeaders(defaultHeaders)
.WithContent(jsonRequestBody)
.Respond("application/json", jsonResponseBody);
httpClientFactory.CreateClient(nameof(TaxjarApi))
.Returns(new HttpClient(handler));
var sut = new TaxjarApi(httpClientFactory, options);
//act
var result = await sut.CreateOrderAsync(request);
//assert
result.Should().NotBeNull();
result.Should().BeEquivalentTo(expected!.Order);
}
[TestCaseSource(typeof(TaxjarTestCaseData), nameof(TaxjarTestCaseData.TaxjarCreateOrderRequestTestCases))]
public async Task when_creating_an_order_transaction_with_missing_required_throws_async((TaxjarOrderRequest taxjarCreateOrderRequest, string expectedMessage) testCase)
{
//arrange
var sut = new TaxjarApi(httpClientFactory, options);
//act
Func<Task> act = async () => await sut.CreateOrderAsync(testCase.taxjarCreateOrderRequest);
//assert
await act.Should().ThrowAsync<ArgumentException>()
.WithMessage(testCase.expectedMessage);
}
[Test]
public async Task when_updating_an_order_transaction_async()
{
//arrange
var request = TaxjarFakes.FakeTaxjarCreateOrderRequest(generateLineItems: true, generateCustomerId: true).Generate();
var jsonRequestBody = JsonSerializer.Serialize(request, options.Value.JsonSerializerOptions);
var expected = TaxjarFakes.FakeOrderResponse(generateLineItems: true).Generate();
var jsonResponseBody = JsonSerializer.Serialize(expected, options.Value.JsonSerializerOptions);
var endpoint = $"{transactionOrdersEndpoint}/{request.TransactionId}";
var handler = new MockHttpMessageHandler();
handler
.When(HttpMethod.Put, endpoint)
.WithHeaders(defaultHeaders)
.WithContent(jsonRequestBody)
.Respond("application/json", jsonResponseBody);
httpClientFactory.CreateClient(nameof(TaxjarApi))
.Returns(new HttpClient(handler));
var sut = new TaxjarApi(httpClientFactory, options);
//act
var result = await sut.UpdateOrderAsync(request);
//assert
result.Should().NotBeNull();
result.Should().BeEquivalentTo(expected!.Order);
}
[Test]
public async Task when_updating_an_order_transaction_throws_async()
{
//arrange
var request = TaxjarFakes.FakeTaxjarCreateOrderRequest().Generate() with { TransactionId = string.Empty};
var sut = new TaxjarApi(httpClientFactory, options);
var expectedMessage = $"Invalid TaxjarOrderRequest.*TransactionId*";
//act
Func<Task> act = async () => await sut.CreateOrderAsync(request);
//assert
await act.Should().ThrowAsync<ArgumentException>()
.WithMessage(expectedMessage);
}
[Test]
public async Task when_deleting_an_order_transaction_async()
{
//arrange
var deleteResponse = TaxjarFakes.FakeDeleteOrderResponse().Generate();
var jsonResponseBody = JsonSerializer.Serialize(deleteResponse, options.Value.JsonSerializerOptions);
var transactionId = deleteResponse!.Order!.TransactionId;
var expected = JsonSerializer.Deserialize<OrderResponse>(jsonResponseBody, options.Value.JsonSerializerOptions);
var endpoint = $"{transactionOrdersEndpoint}/{transactionId}";
var handler = new MockHttpMessageHandler();
handler
.When(HttpMethod.Delete, endpoint)
.WithHeaders(defaultHeaders)
.Respond("application/json", jsonResponseBody);
httpClientFactory.CreateClient(nameof(TaxjarApi))
.Returns(new HttpClient(handler));
var sut = new TaxjarApi(httpClientFactory, options);
//act
var result = await sut.DeleteOrderAsync(transactionId);
//assert
result.Should().NotBeNull();
result.Should().BeEquivalentTo(expected!.Order);
}
[Test]
public async Task when_deleting_an_order_transaction_by_provider_async()
{
//arrange
var deleteResponse = TaxjarFakes.FakeDeleteOrderResponse().Generate();
var jsonResponseBody = JsonSerializer.Serialize(deleteResponse, options.Value.JsonSerializerOptions);
var transactionId = deleteResponse!.Order!.TransactionId;
var provider = TaxjarFakes.Faker.Random.AlphaNumeric(7);
var expected = JsonSerializer.Deserialize<OrderResponse>(jsonResponseBody, options.Value.JsonSerializerOptions);
var endpoint = $"{transactionOrdersEndpoint}/{transactionId}";
var handler = new MockHttpMessageHandler();
handler
.When(HttpMethod.Delete, endpoint)
.WithQueryString($"provider={provider}")
.WithHeaders(defaultHeaders)
.Respond("application/json", jsonResponseBody);
httpClientFactory.CreateClient(nameof(TaxjarApi))
.Returns(new HttpClient(handler));
var sut = new TaxjarApi(httpClientFactory, options);
//act
var result = await sut.DeleteOrderAsync(transactionId, provider);
//assert
result.Should().NotBeNull();
result.Should().BeEquivalentTo(expected!.Order);
}
[Test]
public async Task when_deleting_an_order_transaction_with_missing_transaction_id_throws_async()
{
//arrange
var transactionId = string.Empty;
var sut = new TaxjarApi(httpClientFactory, options);
var expectedMessage = "*Transaction ID cannot be null or an empty string*";
//act
Func<Task> act = async () => await sut.DeleteOrderAsync(transactionId);
//assert
await act.Should().ThrowAsync<ArgumentException>()
.WithMessage(expectedMessage);
}
[Test]
public async Task when_listing_refund_transactions_by_transaction_date_async()
{
//arrange
var taxJarOrderFilter = new RefundFilter
{
TransactionDate = TaxjarFakes.Faker.Date.Past(1),
};
var expected = TaxjarFakes.FakeRefundsResponse().Generate();
var jsonResponseBody = JsonSerializer.Serialize(expected, options.Value.JsonSerializerOptions);
var handler = new MockHttpMessageHandler();
handler
.When(HttpMethod.Get, refundOrdersEndpoint)
.WithQueryString($"transaction_date={taxJarOrderFilter.TransactionDate:yyyy/MM/dd}")
.WithHeaders(defaultHeaders)
.Respond("application/json", jsonResponseBody);
httpClientFactory.CreateClient(nameof(TaxjarApi))
.Returns(new HttpClient(handler));
var sut = new TaxjarApi(httpClientFactory, options);
//act
var result = await sut.ListRefundsAsync(taxJarOrderFilter);
//assert
result.Should().NotBeNull();
result.Should().BeEquivalentTo(expected.Refunds);
}
[Test]
public async Task when_listing_refund_transactions_by_date_range_async()
{
//arrange
var taxJarRefundFilter = new RefundFilter
{
FromTransactionDate = TaxjarFakes.Faker.Date.Past(1),
ToTransactionDate = DateTime.UtcNow
};
var expected = TaxjarFakes.FakeRefundsResponse().Generate();
var jsonResponseBody = JsonSerializer.Serialize(expected, options.Value.JsonSerializerOptions);
var handler = new MockHttpMessageHandler();
handler
.When(HttpMethod.Get, refundOrdersEndpoint)
.WithQueryString($"from_transaction_date={taxJarRefundFilter.FromTransactionDate:yyyy/MM/dd}&to_transaction_date={taxJarRefundFilter.ToTransactionDate:yyyy/MM/dd}")
.WithHeaders(defaultHeaders)
.Respond("application/json", jsonResponseBody);
httpClientFactory.CreateClient(nameof(TaxjarApi))
.Returns(new HttpClient(handler));
var sut = new TaxjarApi(httpClientFactory, options);
//act
var result = await sut.ListRefundsAsync(taxJarRefundFilter);
//assert
result.Should().NotBeNull();
result.Should().BeEquivalentTo(expected.Refunds);
}
[Test]
public async Task when_showing_a_refund_transaction_async()
{
//arrange
var jsonData = TaxjarFixture.GetJSON("refunds/show.json");
var expected = JsonSerializer.Deserialize<RefundResponse>(jsonData, options.Value.JsonSerializerOptions);
var expectedTransactionId = expected!.Refund!.TransactionId;
var jsonResponseBody = JsonSerializer.Serialize(expected, options.Value.JsonSerializerOptions);
var endpoint = $"{refundOrdersEndpoint}/{expectedTransactionId}";
var handler = new MockHttpMessageHandler();
handler
.When(HttpMethod.Get, endpoint)
.WithHeaders(defaultHeaders)
.Respond("application/json", jsonResponseBody);
httpClientFactory.CreateClient(nameof(TaxjarApi))
.Returns(new HttpClient(handler));
var sut = new TaxjarApi(httpClientFactory, options);
//act
var result = await sut.ShowRefundAsync(expectedTransactionId);
//assert
result.Should().NotBeNull();
result.Should().BeEquivalentTo(expected.Refund);
}
[Test]
public async Task when_creating_a_refund_transaction_async()
{
//arrange
var request = TaxjarFakes.FakeTaxjarRefundRequest().Generate();
var jsonRequestBody = JsonSerializer.Serialize(request, options.Value.JsonSerializerOptions);
var jsonData = TaxjarFixture.GetJSON("refunds/show.json");
var expected = JsonSerializer.Deserialize<RefundResponse>(jsonData, options.Value.JsonSerializerOptions);
var jsonResponseBody = JsonSerializer.Serialize(expected, options.Value.JsonSerializerOptions);
var handler = new MockHttpMessageHandler();
handler
.When(HttpMethod.Post, refundOrdersEndpoint)
.WithHeaders(defaultHeaders)
.WithContent(jsonRequestBody)
.Respond("application/json", jsonResponseBody);
httpClientFactory.CreateClient(nameof(TaxjarApi))
.Returns(new HttpClient(handler));
var sut = new TaxjarApi(httpClientFactory, options);
//act
var result = await sut.CreateRefundAsync(request);
//assert
result.Should().NotBeNull();
result.Should().BeEquivalentTo(expected!.Refund);
}
[TestCaseSource(typeof(TaxjarTestCaseData), nameof(TaxjarTestCaseData.TaxjarRefundRequestTestCases))]
public async Task when_creating_a_refund_transaction_missing_required_throws_async((TaxjarRefundRequest taxjarRefundRequest, string expectedMessage) testCase)
{
//arrange
var sut = new TaxjarApi(httpClientFactory, options);
//act
Func<Task> act = async () => await sut.CreateRefundAsync(testCase.taxjarRefundRequest);
//assert
await act.Should().ThrowAsync<ArgumentException>()
.WithMessage(testCase.expectedMessage);
}
[Test]
public async Task when_updating_a_refund_transaction_async()
{
//arrange
var request = TaxjarFakes.FakeTaxjarRefundRequest(generateLineItems: true, generateCustomerId: true).Generate();
var jsonRequestBody = JsonSerializer.Serialize(request, options.Value.JsonSerializerOptions);
var expected = TaxjarFakes.FakeRefundResponse(generateLineItems: true).Generate();
var jsonResponseBody = JsonSerializer.Serialize(expected, options.Value.JsonSerializerOptions);
var endpoint = $"{refundOrdersEndpoint}/{request.TransactionId}";
var handler = new MockHttpMessageHandler();
handler
.When(HttpMethod.Put, endpoint)
.WithHeaders(defaultHeaders)
.WithContent(jsonRequestBody)
.Respond("application/json", jsonResponseBody);
httpClientFactory.CreateClient(nameof(TaxjarApi))
.Returns(new HttpClient(handler));
var sut = new TaxjarApi(httpClientFactory, options);
//act
var result = await sut.UpdateRefundAsync(request);
//assert
result.Should().NotBeNull();
result.Should().BeEquivalentTo(expected!.Refund);
}
[Test]
public async Task when_deleting_a_refund_transaction_async()
{
//arrange
var deleteResponse = TaxjarFakes.FakeDeleteRefundResponse().Generate();
var jsonResponseBody = JsonSerializer.Serialize(deleteResponse, options.Value.JsonSerializerOptions);
var transactionId = deleteResponse!.Refund!.TransactionId;
var expected = JsonSerializer.Deserialize<RefundResponse>(jsonResponseBody, options.Value.JsonSerializerOptions);
var endpoint = $"{refundOrdersEndpoint}/{transactionId}";
var handler = new MockHttpMessageHandler();
handler
.When(HttpMethod.Delete, endpoint)
.WithHeaders(defaultHeaders)
.Respond("application/json", jsonResponseBody);
httpClientFactory.CreateClient(nameof(TaxjarApi))
.Returns(new HttpClient(handler));
var sut = new TaxjarApi(httpClientFactory, options);
//act
var result = await sut.DeleteRefundAsync(transactionId);
//assert
result.Should().NotBeNull();
result.Should().BeEquivalentTo(expected!.Refund);
}
} |
import {
AfterContentInit,
Component,
ContentChildren,
ElementRef,
EventEmitter,
Inject,
Input,
Output,
PLATFORM_ID,
Renderer2,
ViewChild,
ViewEncapsulation,
QueryList,
OnDestroy,
} from '@angular/core';
import { MdbOptionComponent, MDB_OPTION_PARENT } from './mdb-option.component';
import { ISelectedOption } from '../interfaces/selected-option.interface';
import { Observable, Subject, merge } from 'rxjs';
import { isPlatformBrowser } from '@angular/common';
import { document, window } from '../../../free/utils/facade/browser';
import { Utils } from './../../../free/utils/utils.class';
import { startWith, switchMap, takeUntil } from 'rxjs/operators';
import { DOWN_ARROW, ENTER, ESCAPE, UP_ARROW } from '../../../free/utils/keyboard-navigation';
export type AutocompleteDropdownPosition = 'below' | 'above' | 'auto';
@Component({
selector: 'mdb-auto-completer',
templateUrl: 'mdb-auto-completer.component.html',
styleUrls: ['./../auto-completer-module.scss'],
encapsulation: ViewEncapsulation.None,
exportAs: 'mdbAutoCompleter',
providers: [{ provide: MDB_OPTION_PARENT, useExisting: MdbAutoCompleterComponent }],
})
export class MdbAutoCompleterComponent implements AfterContentInit, OnDestroy {
@Input() textNoResults: string;
@Input() clearButton = true;
@Input() clearButtonTabIndex = 0;
@Input() appendToBody: boolean;
@Input() dropdownPosition: AutocompleteDropdownPosition = 'auto';
@Input() disabled: boolean;
@Input()
get visibleOptions(): number {
return this._visibleOptions;
}
set visibleOptions(value: number) {
if (value !== 0) {
this._visibleOptions = value;
}
}
_visibleOptions: number;
@Input()
get optionHeight(): any {
return this._optionHeight;
}
set optionHeight(value: any) {
if (value !== 0) {
this._optionHeight = value;
}
}
_optionHeight = 45;
@Input()
get dropdownHeight(): number {
return this._dropdownHeight;
}
set dropdownHeight(value: number) {
if (value !== 0) {
this._dropdownHeight = value;
}
}
// equal to 4 * optionHeight (which is 45 by default)
_dropdownHeight = 180;
@Input() displayValue: ((value: any) => string) | null;
@Output() select: EventEmitter<{ text: string; element: any }> = new EventEmitter<{
text: string;
element: any;
}>();
@Output() selected: EventEmitter<{ text: string; element: any }> = new EventEmitter<{
text: string;
element: any;
}>();
@ContentChildren(MdbOptionComponent, { descendants: true, read: ElementRef })
optionList: Array<any>;
@ContentChildren(MdbOptionComponent, { descendants: true })
mdbOptions: QueryList<MdbOptionComponent>;
@ViewChild('dropdown') dropdown: ElementRef;
@ViewChild('noResults') noResultsEl: ElementRef;
private _destroy = new Subject<void>();
private utils: Utils = new Utils();
origin: ElementRef;
public parameters: {
left: number;
top: number;
width: number;
bottom: number;
inputHeight: number;
};
readonly _isDropdownOpen: Subject<any> = new Subject<any>();
private _allItems: Array<any> = [];
private _isOpen = false;
private _selectedItemIndex = -1;
private _selectedItem: ISelectedOption;
private _selectedItemChanged: Subject<any> = new Subject<any>();
private _isBrowser = false;
constructor(
private renderer: Renderer2,
private el: ElementRef,
@Inject(PLATFORM_ID) platformId: string
) {
this._isBrowser = isPlatformBrowser(platformId);
this.renderer.addClass(this.el.nativeElement, 'mdb-auto-completer');
}
private _listenToOptionClick() {
this.mdbOptions.changes
.pipe(
startWith(this.mdbOptions),
switchMap((options: QueryList<MdbOptionComponent>) => {
return merge(...options.map((option: MdbOptionComponent) => option.click$));
}),
takeUntil(this._destroy)
)
.subscribe((clickedOption: MdbOptionComponent) => this._handleOptionClick(clickedOption));
}
private _handleOptionClick(option: MdbOptionComponent) {
this.setSelectedItem({ text: option.value, element: option });
this.highlightRow(0);
this.select.emit({ text: option.value, element: option });
this.selected.emit({ text: option.value, element: option });
}
public setSelectedItem(item: ISelectedOption) {
this._selectedItem = item;
this._selectedItemChanged.next(this.getSelectedItem());
}
public getSelectedItem() {
return this._selectedItem;
}
public selectedItemChanged(): Observable<any> {
return this._selectedItemChanged;
}
public isOpen() {
return this._isOpen;
}
public _calculatePosition() {
const modalEl = this.utils.getClosestEl(this.el.nativeElement, '.modal-dialog');
const style = document.querySelector('.completer-dropdown')
? window.getComputedStyle(document.querySelector('.completer-dropdown'))
: null;
if (!style) {
return;
}
const height = ['height', 'padding-top', 'padding-bottom', 'margin-top', 'margin-bottom']
.map(key => parseInt(style.getPropertyValue(key), 10))
.reduce((prev, cur) => prev + cur);
const topRect = document.querySelector('.completer-dropdown').getBoundingClientRect().top;
const bottom = modalEl ? window.innerHeight - height - topRect : this.parameters.bottom;
const canOpenBelow = this.dropdown.nativeElement.clientHeight <= bottom;
const belowPosition = this.parameters.inputHeight + 3;
const abovePosition = `-${this.dropdown.nativeElement.clientHeight}`;
let top;
if (this.dropdownPosition === 'auto') {
top = canOpenBelow ? belowPosition : abovePosition;
} else if (this.dropdownPosition === 'below') {
top = belowPosition;
} else if (this.dropdownPosition === 'above') {
top = abovePosition;
}
this.renderer.setStyle(this.dropdown.nativeElement, 'top', top + 'px');
this.renderer.setStyle(this.dropdown.nativeElement, 'left', 0 + 'px');
this.renderer.setStyle(this.dropdown.nativeElement, 'width', this.parameters.width + 'px');
}
private _calculateAppendPosition() {
if (this._isBrowser) {
setTimeout(() => {
const originRect: ClientRect = this.origin.nativeElement.getBoundingClientRect();
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
const offsetTop = originRect.top + scrollTop;
const height = originRect.height;
const dropdownHeight = this.dropdown.nativeElement.offsetHeight;
const inputMargin = 8;
let top = 0;
let left = 0;
left = originRect.left;
const canOpenBelow =
offsetTop + dropdownHeight + height + inputMargin <=
scrollTop + document.documentElement.clientHeight;
const belowPosition = offsetTop + height + inputMargin;
const abovePosition = (top = offsetTop - dropdownHeight - inputMargin);
if (this.dropdownPosition === 'auto') {
top = canOpenBelow ? belowPosition : abovePosition;
} else if (this.dropdownPosition === 'below') {
top = belowPosition;
} else if (this.dropdownPosition === 'above') {
top = abovePosition;
}
this.renderer.setStyle(this.dropdown.nativeElement, 'top', top + 'px');
this.renderer.setStyle(this.dropdown.nativeElement, 'left', left + 'px');
this.renderer.setStyle(this.dropdown.nativeElement, 'width', this.parameters.width + 'px');
}, 0);
}
}
public show() {
if (!this.disabled) {
this._isOpen = true;
this._isDropdownOpen.next(this.isOpen());
}
setTimeout(() => {
if (this.dropdown && !this.appendToBody) {
this._calculatePosition();
}
if (this.dropdown && this.appendToBody) {
this._calculateAppendPosition();
}
}, 0);
}
public hide() {
if (!this.disabled) {
this._isOpen = false;
this._isDropdownOpen.next(this.isOpen());
}
}
public isDropdownOpen(): Observable<any> {
return this._isDropdownOpen;
}
removeHighlight(index: number) {
setTimeout(() => {
this.optionList.forEach((el: any, i: number) => {
const completerRow = el.nativeElement.querySelectorAll('.completer-row');
if (i === index) {
this.renderer.addClass(el.nativeElement.firstElementChild, 'highlight-row');
} else if (i !== index) {
completerRow.forEach((elem: any) => {
this.renderer.removeClass(elem, 'highlight-row');
});
}
});
}, 0);
}
highlightRow(index: number) {
this._allItems = this.optionList
.filter(el => el.nativeElement.firstElementChild.classList.contains('completer-row'))
.map(elem => elem.nativeElement);
if (this._allItems[index]) {
this.optionList.forEach((el: any, i: number) => {
const completerRow = el.nativeElement.querySelectorAll('.completer-row');
if (index === i) {
this.removeHighlight(index);
this.renderer.addClass(completerRow[completerRow.length - 1], 'highlight-row');
}
});
}
this._selectedItemIndex = index;
}
navigateUsingKeyboard(event: any) {
if (this.dropdown) {
switch (event.keyCode) {
case DOWN_ARROW:
event.preventDefault();
this.moveHighlightedIntoView(event.key);
if (!this.isOpen()) {
this.show();
}
if (this._selectedItemIndex + 1 <= this._allItems.length - 1) {
this.highlightRow(++this._selectedItemIndex);
} else if (this._selectedItemIndex + 1 === this._allItems.length) {
this.highlightRow(0);
}
if (this._selectedItemIndex === 0) {
this.highlightRow(0);
}
const selectedElement: any = this.mdbOptions.find(
(el: any, index: number) => el && index === this._selectedItemIndex
);
if (selectedElement) {
this.select.emit({ text: selectedElement.value, element: selectedElement });
}
break;
case UP_ARROW:
event.preventDefault();
this.moveHighlightedIntoView(event.key);
if (this._selectedItemIndex === -1 || this._selectedItemIndex === 0) {
const lastItemIndex = this.mdbOptions.length;
this.highlightRow(lastItemIndex);
}
this.highlightRow(--this._selectedItemIndex);
const selectedItem: any = this.mdbOptions.find(
(el: any, index: number) => el && index === this._selectedItemIndex
);
if (selectedItem) {
this.select.emit({ text: selectedItem.value, element: selectedItem });
}
break;
case ESCAPE:
event.preventDefault();
this.hide();
break;
case ENTER:
event.preventDefault();
const selectedOption = this.mdbOptions.map(el => el)[this._selectedItemIndex];
if (selectedOption) {
this.setSelectedItem({ text: selectedOption.value, element: selectedOption });
this.select.emit({ text: selectedOption.value, element: selectedOption });
this.selected.emit({ text: selectedOption.value, element: selectedOption });
}
this.hide();
break;
}
}
}
moveHighlightedIntoView(type: string) {
let listHeight = 0;
let itemIndex = this._selectedItemIndex;
this.optionList.forEach((el: any) => {
listHeight += el.nativeElement.offsetHeight;
});
if (itemIndex > -1) {
let itemHeight = 0;
this.optionList.forEach((el: ElementRef, i: number) => {
if (i === itemIndex + 1) {
itemHeight = el.nativeElement.firstElementChild.clientHeight;
}
});
const itemTop = (itemIndex + 1) * itemHeight;
const viewTop = this.dropdown.nativeElement.scrollTop;
const viewBottom = viewTop + listHeight;
if (type === 'ArrowDown') {
this.renderer.setProperty(this.dropdown.nativeElement, 'scrollTop', itemTop - itemHeight);
} else if (type === 'ArrowUp') {
if (itemIndex === 0) {
itemIndex = this.optionList.length - 1;
} else {
itemIndex--;
}
if (itemIndex === this._allItems.length - 2) {
this.renderer.setProperty(
this.dropdown.nativeElement,
'scrollTop',
viewBottom - itemHeight
);
} else {
this.renderer.setProperty(
this.dropdown.nativeElement,
'scrollTop',
itemIndex * itemHeight
);
}
}
}
}
updatePosition(parameters: { left: number; top: number; width: number; bottom: number }) {
setTimeout(() => {
if (this.dropdown) {
const top =
this.dropdown.nativeElement.clientHeight > parameters.bottom
? parameters.top - this.dropdown.nativeElement.clientHeight
: parameters.top;
this.renderer.setStyle(this.dropdown.nativeElement, 'top', top + 'px');
this.renderer.setStyle(this.dropdown.nativeElement, 'left', parameters.left + 'px');
this.renderer.setStyle(this.dropdown.nativeElement, 'width', parameters.width + 'px');
}
}, 0);
}
public appendDropdown() {
if (this._isBrowser && this.appendToBody) {
const body = document.querySelector('body');
const dropdown = this.el.nativeElement;
if (body) {
this.renderer.appendChild(body, dropdown);
this._calculateAppendPosition();
}
}
}
public setSingleOptionHeight() {
this.mdbOptions.forEach(option => {
option._optionHeight = this._optionHeight;
});
}
ngAfterContentInit() {
this._listenToOptionClick();
this.highlightRow(0);
}
ngOnDestroy() {
this._destroy.next();
this._destroy.complete();
}
} |
package kr.or.ddit.basic;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import kr.or.ddit.member.vo.MemberVO;
public class MybatisTest {
// myBatis를 이용하여 DB자료를 처리하는 작업 순서
// 1.myBatis의 환경 설정파일을 읽어와 실행시킨다.
public static void main(String[] args) {
SqlSession sqlSession = null;
try
{
// 1-1. xml설정문서 읽어오기
// 설정파일의 인코딩정보 설정(한글처리를 위해서)
Charset charset = Charset.forName("UTF-8");
Resources.setCharset(charset);
Reader rd = Resources.getResourceAsReader("config/mybatis-config.xml");
// 1-2. 위에서 읽어온 Reader 객체를 이용하여 실제 작업을 진행할 객체 생성하기
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(rd);
// 오토커밋 여부설정
sqlSession = sessionFactory.openSession(true);
rd.close(); // 자원반납
}catch(
IOException ex)
{
ex.printStackTrace();
}
//2.실행할 SQL 문에 맞는 쿼리문을 호출해서 원하는 작업을 수행한다.
//2-1. Insert 작업 연습
System.out.println("insert 작업 시작...");
//1) 저장할 데이터를 VO에 담는다.
MemberVO mv = new MemberVO();
mv.setMemId("d001");
mv.setMemName("김효정");
mv.setMemTel("1111-1111");
mv.setMemAddr("대전시 서구 탄방동");
//2) SqlSession객체 변수를 이용하여 해당 쿼리문을 실행
// 형식) sqlSession.insert("namespace값.id값",파라미터 객체)
// 반환값 : 성공한 레코드 수
int cnt = sqlSession.insert("memberTest.insertMember",mv);
if(cnt > 0) {
System.out.println("insert 성공!");
}else {
System.out.println("insert 실패!!!");
}
//2-2. update 연습
System.out.println("update 작업 시작 ...");
MemberVO mv2 = new MemberVO();
mv2.setMemId("d001");
mv2.setMemName("윤다영");
mv2.setMemTel("6666-6666");
mv2.setMemAddr("부산시 해운대구");
//update()메서드의 반환값도 성공한 레코드 수이다
cnt = sqlSession.update("memberTest.updateMember",mv2);
if(cnt > 0) {
System.out.println("update 성공!");
}else {
System.out.println("update 실패!!!");
}
//2-3. delete 연습
// System.out.println("delete 작업 시작...");
//
// //delete 메서드 반환값 : 성공한 레코드 수
//
// cnt = sqlSession.delete("memberTest.deleteMember","d001");
//
// if(cnt > 0) {
// System.out.println("delete 성공!");
// }else {
// System.out.println("delete 실패!!!");
// }
//2-4. select 연습
//1) 응답결과가 여러개일 경우 ...
// System.out.println("select 연습 시작(결과가 여러개일 경우..)");
//응답 결과가 여러개 일 경우네느 selectList()메서드를 사용한다.
//이 메서드는 여러개의 레코드를 VO에 담은 후 이 VO 데이터를 List에
//추가해주는 작업을 자동으로 수행한다.
// List<MemberVO> memList
// = sqlSession.selectList("memberTest.memberAllList");
// for(MemberVO mv : memList) {
// System.out.println("ID : "+ mv.getMemId());
// System.out.println("이름 : "+ mv.getMemName());
// System.out.println("전화 : "+ mv.getMemTel());
// System.out.println("주소 : "+ mv.getMemAddr());
// }
// System.out.println("출력 끝...");
//2)응답 결과가 1개일 경우
System.out.println("select 연습 시작(결과가 1인 경우)...");
//응답결과가 1개인 확실할 경우에는 selectOne() 메서드를 사용한다.
MemberVO mv3 = sqlSession.selectOne("memberTest.getMember","d001");
System.out.println("ID : "+ mv3.getMemId());
System.out.println("이름 : "+ mv3.getMemName());
System.out.println("전화 : "+ mv3.getMemTel());
System.out.println("주소 : "+ mv3.getMemAddr());
}} |
package com.example.mkt.service;
import com.example.mkt.dto.product.ProductInputDTO;
import com.example.mkt.dto.product.ProductOutputDTO;
import com.example.mkt.dto.product.ProductUpdateDTO;
import com.example.mkt.entity.ProductEntity;
import com.example.mkt.exceptions.EntitiesNotFoundException;
import com.example.mkt.exceptions.BussinessRuleException;
import com.example.mkt.repository.ProductRepository;
import com.example.mkt.util.ConversorMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
@RequiredArgsConstructor
public class ProductService {
private final ProductRepository produtoRepository;
public List<ProductOutputDTO> findAll(){
return produtoRepository.findAll().stream()
.map(ProductOutputDTO::new)
.toList();
}
public ProductOutputDTO findById(Integer idProduto){
return ConversorMapper.converter(produtoRepository.findById(idProduto)
.orElseThrow(() -> new EntitiesNotFoundException("Produto não encontrado.")),
ProductOutputDTO.class);
}
public ProductOutputDTO save(ProductInputDTO produtoInputDTO) throws BussinessRuleException {
ProductEntity novoProduto = new ProductEntity();
BeanUtils.copyProperties(produtoInputDTO, novoProduto);
ProductEntity produtoSalvo = produtoRepository.save(novoProduto);
if(produtoSalvo == null){
throw new BussinessRuleException("Produto inválido");
}
return ConversorMapper.converter(produtoSalvo, ProductOutputDTO.class);
}
public ProductOutputDTO update(Integer idProduto, ProductUpdateDTO produtoUpdateDTO) throws BussinessRuleException {
if(produtoUpdateDTO == null){
throw new BussinessRuleException("Insira as informações a serem atualizadas.");
}
ProductEntity produtoAtualizar = produtoRepository.findById(idProduto)
.orElseThrow(() -> new EntitiesNotFoundException("Produto não encontrado."));
if(produtoUpdateDTO.getNomeProduto() != null){
produtoAtualizar.setNomeProduto(produtoUpdateDTO.getNomeProduto());
}
if(produtoUpdateDTO.getPreco() != null){
produtoAtualizar.setPreco(produtoUpdateDTO.getPreco());
}
if(produtoUpdateDTO.getDescricao() != null){
produtoAtualizar.setDescricao(produtoUpdateDTO.getDescricao());
}
ProductEntity produtoAtualizado = produtoRepository.save(produtoAtualizar);
return ConversorMapper.converter(produtoAtualizado, ProductOutputDTO.class);
}
public void delete(Integer idProduto){
Optional<ProductEntity> produtoDeletar = produtoRepository.findById(idProduto);
if(produtoDeletar.isPresent()){
produtoRepository.delete(produtoDeletar.get());
}
}
} |
package com.xiaoma1.one.exer3;
import java.util.Scanner;
/**
* ClassName: ArrayExer3_1
* Description:
* 从键盘读入学生成绩,找出最高分,并输出学生成绩等级。
* 成绩>=最高分-10 等级为’A’
* 成绩>=最高分-20 等级为’B’
* 成绩>=最高分-30 等级为’C’
* 其余 等级为’D’
* 提示:先读入学生人数,根据人数创建
* @Author Mabuyao
* @Create 2023/7/28 14:36
* @Version 1.0
*/
public class ArrayExer3_1 {
public static void main(String[] args) {
//从键盘输入人数,根据人数创建数组
Scanner scan = new Scanner(System.in);
System.out.println("请输入学生人数:");
int count = scan.nextInt();
int[] scores = new int[count];
//根据提示依次输入学生的成绩,并将成绩保存在数组元素中
int maxScore = scores[0];
System.out.println("请输入" + count + "个成绩");
for (int i = 0; i < scores.length; i++) {
scores[i] = scan.nextInt();
//获取学生成绩的最大值
if(maxScore < scores[i]){
maxScore = scores[i];
}
}
System.out.println("最高分是:" + maxScore);
//遍历数组元素,根据学生成绩与最高分的差值,得到每个学生的等级,并输出成绩和等级
char grade = 0;
for (int i = 0; i < scores.length; i++) {
if(scores[i] >= maxScore - 10){
grade = 'A';
}else if(scores[i] >= maxScore - 20){
grade = 'B';
}else if(scores[i] >= maxScore - 30){
grade = 'C';
}else{
grade = 'D';
}
System.out.println("student " + i + " score is " + scores[i] + " grade is " + grade);
}
scan.close();
}
} |
package com.example.parksproject.service;
import com.example.parksproject.domain.User;
import com.example.parksproject.payload.CreatedStudyResponse;
import com.example.parksproject.payload.InfoResponse;
import com.example.parksproject.payload.MyStudyResponse;
import com.example.parksproject.payload.UserResponse;
import com.example.parksproject.repository.UserRepository;
import com.example.parksproject.security.UserPrincipal;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Collectors;
@Service
@Transactional
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
public UserResponse getMyInfo(Long id) {
User user = userRepository.findById(id).get();
UserResponse userResponse = new UserResponse(user.getId(), user.getName(),user.getEmail(),user.getImageUrl(),user.getRole(),user.getEmailVerified(),user.getAuthProvider(),user.getProviderId(),user.getBio(),user.getOccupation(),user.getLocation());
return userResponse;
}
public ResponseEntity<?> modifyUserInfo(UserPrincipal userPrincipal, InfoResponse infoResponse) {
User user = userRepository.findById(userPrincipal.getId()).get();
User modifyUser = User.builder()
.id(user.getId())
.name(user.getName())
.email(user.getEmail())
.imageUrl(user.getImageUrl())
.role(user.getRole())
.emailVerified(user.getEmailVerified())
.password(user.getPassword())
.authProvider(user.getAuthProvider())
.providerId(user.getProviderId())
.bio(infoResponse.getBio())
.occupation(infoResponse.getOccupation())
.location(infoResponse.getLocation()).build();
userRepository.save(modifyUser);
return ResponseEntity.ok("수정 완료");
}
public List<MyStudyResponse> findMyStudy(Long id) {
User user = userRepository.findById(id).get();
List<MyStudyResponse> collect = user.getApplyStudies().stream().map(applyStudy -> new MyStudyResponse(applyStudy.getStudy().getId(), applyStudy.getApplyState().toString(), applyStudy.getStudy().getTitle(), applyStudy.getStudy().getImage(), applyStudy.getStudy().isRecruiting(), applyStudy.getStudy().isPublished(), applyStudy.getStudy().isClosed())).collect(Collectors.toList());
return collect;
}
public List<CreatedStudyResponse> getCreatedStudy(Long id) {
User user = userRepository.findById(id).get();
List<CreatedStudyResponse> collect = user.getManagers().stream().map(manager -> new CreatedStudyResponse(manager.getStudy().getId(), manager.getStudy().getImage(), manager.getStudy().getTitle(), manager.getStudy().getMaxMember(), manager.getStudy().getApplies())).collect(Collectors.toList());
return collect;
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="node_modules/vue/dist/vue.js"></script>
<style>
* {
margin: 0%;
padding: 0%;
}
.outer {
width: 300px;
height: 300px;
background-color: aqua;
margin: 150px auto;
position: relative;
}
.inner {
width: 150px;
height: 150px;
background-color: yellow;
position: absolute;
top: 50%;
left: 50%;
margin-top: -75px;
margin-left: -75px;
text-align: center;
}
.inner input {
margin-top: 70px;
}
</style>
</head>
<body>
<div id="app">
<!-- 使用 .stop 阻止冒泡 -->
<!-- <div class="outer" @click='outerHandler'>
<div class="inner" @click.stop='innerHandler'>
<input type="button" value="按钮" @click='btnHandler'>
</div>
</div> -->
<!-- 使用 .capture 实现捕获触发的机制 -->
<!-- <div class="outer" @click.capture='outerHandler'>
<div class="inner" @click='innerHandler'>
<input type="button" value="按钮" @click='btnHandler'>
</div>
</div> -->
<!-- 使用 .prevent 阻止默认行为 -->
<!-- <a href="https://www.baidu.com" @click.prevent='linkHandler'> 跳转垃圾百度</a> -->
<!-- 使用 .once 只触发一次事件处理函数 -->
<!-- <a href="https://www.baidu.com" @click.prevent.once='linkHandler'> 跳转垃圾百度</a> -->
<!-- .self 只有点击当前元素时候,才会触发事件处理函数 只会阻止自己身上冒泡行为的触发,并不会真正阻止 冒泡的行为 -->
<div class="outer" @click='outerHandler'>
<div class="inner" @click.self='innerHandler'>
<input type="button" value="按钮" @click='btnHandler'>
</div>
</div>
</div>
</body>
<script>
let app = new Vue({
el: '#app',
methods: {
outerHandler() {
console.log('这是外层outer的事件')
},
innerHandler() {
console.log('这是内层inner的事件')
},
btnHandler() {
console.log('这是按钮的事件')
},
linkHandler() {
console.log('这是链接的事件')
}
}
})
</script>
</html> |
import { useState } from 'react';
import Card from './shared/Card';
import Button from './shared/Button';
function FeedbackForm() {
const [text, setText] = useState('');
const [btnDisabled, setBtnDisabled] = useState(true);
const [message, setMessage] = useState('');
const handleTextChange = (e) => {
if (text === '') {
setBtnDisabled(true);
setMessage(null);
} else if (text !== '' && text.trim().length <= 10) {
setBtnDisabled(true);
setMessage('Review must be atleast 10 characters');
} else {
setBtnDisabled(false);
setMessage(null);
}
setText(e.target.value);
};
return (
<Card>
<form>
<h2>How would you rate your service with us?</h2>
<div className="input-group">
<input
type="text"
onChange={handleTextChange}
placeholder="Write a review"
value={text}
/>
<Button type="submit" isDisabled={btnDisabled}>
Send
</Button>
</div>
{message && (
<div className="message" style={{ color: 'red', fontSize: '13px' }}>
{message}
</div>
)}
</form>
</Card>
);
}
export default FeedbackForm; |
import cx from 'classnames';
import React from 'react';
import { Caption } from '#components/typography/Caption';
import styles from './index.module.scss';
interface Props extends React.HTMLAttributes<HTMLButtonElement> {
disabled?: boolean;
infotext?: string;
selected?: boolean;
}
export function RoundedGlass(props: Props) {
const { children, className, disabled, infotext, selected, ...rest } = props;
return (
<button
{...rest}
className={cx(styles.container, className, {
[styles.disabled]: !!disabled,
[styles.selected]: !!selected,
})}
>
<div className={cx(styles.layer, styles.layer1)} />
<div className={cx(styles.layer, styles.layer2)} />
<div className={styles.children}>{children}</div>
{infotext && (
<div className={styles.infotext}>
<Caption>{infotext}</Caption>
</div>
)}
</button>
);
} |
%% sys id
clear
% here we are going to estimate two system parameters (mass and offset)
% from data (we are going to create this data)
%% data creation
mass = 4;
offset = 0.1;
p_true = [mass;offset]; % these are the truth values
% simulate dynamics with true values
dt = 0.5;
N = 10;
X = zeros(4,N);
U = zeros(2,N-1);
x0 = [3;2;0.1;-0.3];
X(:,1) = x0;
for i = 1:N-1
U(:,i) = [sin(i);1.3*cos(i)];
X(:,i+1) = rk4(X(:,i),U(:,i),p_true,dt);
end
% plot trajectories
figure
hold on
title('positions')
plot(X(1:2,:)')
legend('px','py')
hold off
figure
hold on
title('velocities')
plot(X(3:4,:)')
legend('vx','vy')
hold off
%% check cost function
p1 = p_true*0.5;
% this should be 0 with the true p value
J = cost_function(p_true,X,U)
% but nonzero with an incorrect p value
J = cost_function(p1,X,U)
%% now we solve to p to see if we can converge on the true p
options = optimset('Display','iter','PlotFcns',@optimplotfval);
p_guess = randn(2,1);
p_solve = fminsearch(@(p)cost_function(p,X,U),p_guess,options)
%% supporting functions
function J = cost_function(p,X,U)
% Xtilde is experimental state history
% Utilde is experimental control history
% p contains system parameters (mass and offset) that we are trying to
% solve for.
J = 0;
N = size(X,2);
dt = 0.5;
for i = 1:N-1
% add the norm squared of the error between the two steps, as predicted
% given our dynamics model with current p values
J = J + norm(X(:,i+1) - rk4(X(:,i),U(:,i),p,dt))^2;
end
end
function xdot = dynamics(x,u,p)
% position
r = x(1:2);
% velocity
v = x(3:4);
% unpack p (this is where I put the system parameters i'm solving for)
mass = p(1); % mass of the particle
offset = p(2); % offset
% kinematics
rdot = v;
% dynamics
vdot = u/mass + offset;
xdot = [rdot;vdot];
end
function xkp1 = rk4(x,u,p,dt)
k1 = dt*dynamics(x,u,p);
k2 = dt*dynamics(x + k1/2,u,p);
k3 = dt*dynamics(x + k2/2,u,p);
k4 = dt*dynamics(x + k3,u,p);
xkp1 = x + (1/6)*(k1 + 2*k2 + 2*k3 + k4);
end |
import React from 'react';
import clsx from 'clsx';
import Link from '@docusaurus/Link';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import Layout from '@theme/Layout';
import Translate, {translate} from '@docusaurus/Translate';
import styles from './index.module.css';
function HomepageHeader() {
const {siteConfig} = useDocusaurusContext();
return (
<header className={clsx('hero hero--primary', styles.heroBanner)}>
<div className="container">
<h1 className="hero__title">
<Translate
id="homePage.siteconfig.title"
description="Guides and tutorials">
My Documentation
</Translate>
</h1>
<p className="hero__subtitle">
<Translate
id="homePage.siteconfig.tagline"
description="CI & CD at its best">
This is m-m-my mmm-mmy mmmmmy documentation!
</Translate></p>
<div className={styles.buttons}>
<Link className="button button--secondary button--lg"
to="/docs/intro">
<Translate
id="homePage.goToDocumentation">
Start reading the doc now! 💻
</Translate>
</Link>
</div>
</div>
</header>
);
}
function Hello() {
return (
<div className={styles.aboutDiv}>
<h2 className="text-3xl leading-9 font-extrabold md:text-4xl md:leading-10"
align='center'>
<Translate
id="homePage.aboutSectionTitle">
About this documentation
</Translate>
</h2>
<div className={styles.textDiv}>
<p>
L’année 1866 fut marquée par un événement bizarre, un phénomène inexpliqué et inexplicable que personne n’a sans doute oublié. Sans parler des rumeurs qui agitaient les populations des ports et surexcitaient l’esprit public à l’intérieur des continents, les gens de mer furent particulièrement émus. Les négociants, armateurs, capitaines de navires, skippers et masters de l’Europe et de l’Amérique, officiers des marines militaires de tous pays, et, après eux, les gouvernements des divers États des deux continents, se préoccupèrent de ce fait au plus haut point.
</p>
<p>
En effet, depuis quelque temps, plusieurs navires s’étaient rencontrés sur mer avec « une chose énorme, » un objet long, fusiforme, parfois phosphorescent, infiniment plus vaste et plus rapide qu’une baleine.
</p>
<p>
Les faits relatifs à cette apparition, consignés aux divers livres de bord, s’accordaient assez exactement sur la structure de l’objet ou de l’être en question, la vitesse inouïe de ses mouvements, la puissance surprenante de sa locomotion, la vie particulière dont il semblait doué. Si c’était un cétacé, il surpassait en volume tous ceux que la science avait classés jusqu’alors. Ni Cuvier, ni Lacépède, ni M. Dumeril, ni M. de Quatrefages n’eussent admis l’existence d’un tel monstre — à moins de l’avoir vu, ce qui s’appelle vu de leurs propres yeux de savants.
</p>
</div>
</div>
);
}
export default function Home() {
const {siteConfig} = useDocusaurusContext();
return (
<Layout
title={`${siteConfig.title}`}
description={`${siteConfig.title}`}>
<HomepageHeader />
<Hello/>
</Layout>
);
} |
!
!------------------------------------------------------------------------------
! Author : Vikas sharma
! Position : Doctral Student
! Institute : Kyoto Univeristy, Japan
! Program name: Addition.part
! Last Update : Dec-30-2017
!
!------------------------------------------------------------------------------
! Details of Program
!
! TYPE :: Part of the program
!
! DESCRIPTION
! - Addition Operator is defined
! HOSTING FILE
! - MaterialJacobian_Class.F90
!------------------------------------------------------------------------------
! obj_Add_obj
!------------------------------------------------------------------------------
FUNCTION obj_Add_obj( obj, obj2 )
!. . . . . . . . . . . . . . . . . . . .
! 1. obj + obj2
!. . . . . . . . . . . . . . . . . . . .
! Define intent of dummy variables
CLASS( MaterialJacobian_ ), INTENT( IN ) :: obj
CLASS( MaterialJacobian_ ), INTENT( IN ) :: obj2
REAL( DFP ), ALLOCATABLE :: obj_Add_obj( :, : )
! Define internal variables
INTEGER( I4B ) :: N1, N2
IF( .NOT. ALLOCATED( obj%C ) &
.OR. .NOT. ALLOCATED( obj2%C ) ) THEN
CALL Err_Msg( &
"MaterialJacobian_Class.F90>>Addition.part", &
"obj + obj2", &
"obj or obj2 is/are not initiated, Program Stopped!!!"&
)
STOP
END IF
N1 = .SIZE. obj
N2 = .SIZE. obj2
IF( N1 .NE. N2 ) THEN
CALL Err_Msg( &
"MaterialJacobian_Class.F90>>Addition.part", &
"obj + obj2", &
"The Shape of obj%C and obj2%C are not Compatible, &
Program Stopped!!!"&
)
STOP
END IF
ALLOCATE( obj_Add_obj( N1, N1 ) )
obj_Add_obj = obj%C + obj2%C
END FUNCTION obj_Add_obj
!------------------------------------------------------------------------------
! obj_Add_Mat
!------------------------------------------------------------------------------
FUNCTION obj_Add_Mat( obj, Mat )
!. . . . . . . . . . . . . . . . . . . .
! 1. obj + Mat
!. . . . . . . . . . . . . . . . . . . .
! Define intent of dummy variables
CLASS( MaterialJacobian_ ), INTENT( IN ) :: obj
REAL( DFP ), INTENT( IN ) :: Mat( :, : )
REAL( DFP ), ALLOCATABLE :: obj_Add_Mat( :, : )
! Define internal variables
INTEGER( I4B ) :: N1, N2
IF( .NOT. ALLOCATED( obj%C ) ) THEN
CALL Err_Msg( &
"MaterialJacobian_Class.F90>>Addition.part", &
"obj + Mat", &
"obj is not initiated, Program Stopped!!!"&
)
STOP
END IF
N1 = .SIZE. obj
N2 = SIZE( Mat, 1 )
IF( N1 .NE. N2 ) THEN
CALL Err_Msg( &
"MaterialJacobian_Class.F90>>Addition.part", &
"obj + Mat", &
"The Shape of obj%C and Mat are not Compatible, &
Program Stopped!!!"&
)
STOP
END IF
ALLOCATE( obj_Add_Mat( N1, N1 ) )
obj_Add_Mat = obj%C + Mat
END FUNCTION obj_Add_Mat
!------------------------------------------------------------------------------
! Mat_Add_obj
!------------------------------------------------------------------------------
FUNCTION Mat_Add_obj( Mat, obj )
!. . . . . . . . . . . . . . . . . . . .
! 1. Mat + obj
!. . . . . . . . . . . . . . . . . . . .
! Define intent of dummy variables
CLASS( MaterialJacobian_ ), INTENT( IN ) :: obj
REAL( DFP ), INTENT( IN ) :: Mat( :, : )
REAL( DFP ), ALLOCATABLE :: Mat_Add_obj( :, : )
Mat_Add_obj = obj_Add_Mat( obj, Mat )
END FUNCTION Mat_Add_obj
!------------------------------------------------------------------------------
! obj_Add_Scalar
!------------------------------------------------------------------------------
FUNCTION obj_Add_Scalar( obj, Scalar )
!. . . . . . . . . . . . . . . . . . . .
! 1. obj + Scalar
!. . . . . . . . . . . . . . . . . . . .
! Define intent of dummy variables
CLASS( MaterialJacobian_ ), INTENT( IN ) :: obj
REAL( DFP ), INTENT( IN ) :: Scalar
REAL( DFP ), ALLOCATABLE :: obj_Add_Scalar( :, : )
! Define internal variables
INTEGER( I4B ) :: N
IF( .NOT. ALLOCATED( obj%C ) ) THEN
CALL Err_Msg( &
"MaterialJacobian_Class.F90>>Addition.part", &
"obj + Mat", &
"obj is not initiated, Program Stopped!!!"&
)
STOP
END IF
N = .SIZE. obj
ALLOCATE( obj_Add_Scalar( N, N ) )
obj_Add_Scalar = obj%C + Scalar
END FUNCTION obj_Add_Scalar
!------------------------------------------------------------------------------
! Scalar_Add_obj
!------------------------------------------------------------------------------
FUNCTION Scalar_Add_obj( Scalar, obj )
!. . . . . . . . . . . . . . . . . . . .
! 1. Scalar + obj
!. . . . . . . . . . . . . . . . . . . .
! Define intent of dummy variables
CLASS( MaterialJacobian_ ), INTENT( IN ) :: obj
REAL( DFP ), INTENT( IN ) :: Scalar
REAL( DFP ), ALLOCATABLE :: Scalar_Add_obj( :, : )
Scalar_Add_obj = obj_Add_Scalar( obj, Scalar )
END FUNCTION Scalar_Add_obj |
import { checkFieldAndPost } from '../functions/checkFieldsAndPost.js';
import { selectDoctorListener } from '../functions/selectDoctorListener.js';
export class ModalCreate {
constructor() {
this.body = document.querySelector('body');
this.modalBackground = document.createElement('div');
this.container = document.createElement('div');
this.divButton = document.createElement('div');
this.closeButton = document.createElement('button');
this.submitButton = document.createElement('button');
this.papagraph = document.createElement('p');
this.select = document.createElement('select');
this.optionDefault = document.createElement('option');
this.optionDentist = document.createElement('option');
this.optionTherapist = document.createElement('option');
this.optionCardiologist = document.createElement('option');
this.wrapper = document.createElement('div');
this.chooseDoctorParagraph = document.createElement('p');
}
deleteModal() {
this.modalBackground.remove();
}
createElement() {
this.chooseDoctorParagraph.innerText =
"Select the doctor you'd like to visit:";
this.chooseDoctorParagraph.classList.add('choose-doctor');
this.optionDefault.innerText = 'Choose a doctor';
this.select.id = 'select-doctor';
this.select.classList.add('form-select');
this.optionDentist.innerText = 'Dentist';
this.optionTherapist.innerText = 'Therapist';
this.optionCardiologist.innerText = 'Cardiologist';
this.optionDentist.value = 'Dentist';
this.optionTherapist.value = 'Therapist';
this.optionCardiologist.value = 'Cardiologist';
this.select.append(
this.optionDefault,
this.optionDentist,
this.optionTherapist,
this.optionCardiologist
);
this.select.addEventListener('change', (e) => {
selectDoctorListener(e.target.value, this);
});
this.modalBackground.classList.add('visit__modal-background');
this.container.classList.add('visit__modal');
this.modalBackground.append(this.container);
this.closeButton.innerText = 'CANCEL';
this.closeButton.classList.add('btn', 'btn-outline-danger');
this.submitButton.type = 'submit';
this.submitButton.classList.add('btn', 'btn-success');
this.submitButton.disabled = true;
this.modalBackground.addEventListener('click', (e) => {
if (e.target === this.modalBackground) {
this.modalBackground.remove();
}
});
this.closeButton.addEventListener('click', (e) => {
this.container.innerHTML = '';
this.container.classList.remove('visit__modal');
this.modalBackground.classList.remove('visit__modal-background');
});
this.submitButton.addEventListener('click', () => {
checkFieldAndPost();
});
this.submitButton.innerText = 'CREATE VISIT';
this.wrapper.append(this.chooseDoctorParagraph, this.select);
this.wrapper.insertAdjacentHTML(
'beforeend',
`
<form class="visit__modal--form ">
<div>
<label
for="input-name-dentist"
class="form-label"
>
Name
</label>
<input
type="email"
class="form-control"
id="input-name-dentist"
placeholder="Enter your name here"
>
</div>
<div>
<label
for="input-worries-dentist"
class="form-label"
>
Purpose of visit
</label>
<input
type="text"
class="form-control"
id="input-worries-dentist"
placeholder="What worries you?"
>
</div>
<div>
<label
for="input-description-dentist"
class="form-label"
>
Description of the visit</label>
<input
type="text"
class="form-control"
id="input-description-dentist"
placeholder="Briefly describe your complaints"
>
</div>
<div>
<label
for="input-priority-dentist"
class="form-label"
>
priority
</label>
<select
id="input-priority-dentist"
class="form-select"
>
<option selected>Choose...</option>
<option>Low</option>
<option>Normal</option>
<option>High</option>
</select>
</div>
</form>
`
);
this.divButton.classList.add('div-button');
this.divButton.append(this.submitButton);
this.divButton.append(this.closeButton);
this.container.append(this.wrapper);
this.container.append(this.divButton);
}
render() {
this.createElement();
document.querySelector('body').append(this.modalBackground);
}
}
export class VisitDentist extends ModalCreate {
constructor() {
super();
this.dentistContainer = document.createElement('div');
}
deleteModal() {
super.deleteModal();
}
createElement() {
super.createElement();
this.submitButton.removeAttribute('disabled');
this.optionDentist.setAttribute('selected', 'selected');
this.dentistContainer.classList.add('dentist-container');
this.dentistContainer.insertAdjacentHTML(
'beforeend',
`
<div id="dentist">
<label
for="input-last-visit-dentist"
class="form-label"
>
Date of last visit to doctor:
</label>
<input
type="text"
class="form-control"
id="input-last-visit-dentist"
placeholder="01.01.2023"
>
</div>
`
);
this.wrapper.append(this.dentistContainer);
}
render() {
super.render();
}
}
export class VisitCardiologist extends ModalCreate {
constructor() {
super();
this.cardiologistContainer = document.createElement('div');
}
deleteModal() {
super.deleteModal();
}
createElement() {
super.createElement();
this.submitButton.removeAttribute('disabled');
this.optionCardiologist.setAttribute('selected', 'selected');
this.cardiologistContainer.classList.add('cardiologist-container');
this.cardiologistContainer.insertAdjacentHTML(
'afterbegin',
`
<div>
<label
for="input-pressure-cardiologist"
class="form-label"
>
Normal pressure
</label>
<input
type="text"
class="form-control"
id="input-pressure-cardiologist"
placeholder="120/80"
>
</div>
<div>
<label
for="input-index-cardiologist"
class="form-label"
>
Body mass index
</label>
<input
type="text"
class="form-control"
id="input-index-cardiologist"
placeholder="26,64 kg/m²"
>
</div>
<div>
<label
for="input-diseases-cardiologist"
class="form-label"
>
Describe your previous diseases (if applicable):
</label>
<input
type="text"
class="form-control"
id="input-diseases-cardiologist"
>
</div>
<div>
<label
for="input-age"
class="form-label"
>
Your Age
</label>
<input
type="text"
class="form-control"
id="input-age"
>
</div>
`
);
this.wrapper.append(this.cardiologistContainer);
}
render() {
super.render();
}
}
export class VisitTherapist extends ModalCreate {
constructor() {
super();
}
deleteModal() {
super.deleteModal();
}
createElement() {
super.createElement();
this.submitButton.removeAttribute('disabled');
this.therapistContainer = document.createElement('div');
this.optionTherapist.setAttribute('selected', 'selected');
this.therapistContainer.classList.add('therapist-container');
this.therapistContainer.insertAdjacentHTML(
'afterbegin',
`
<div>
<label
for="input-age"
class="form-label"
>
Your age:
</label>
<input
type="text"
class="form-control"
id="input-age"
>
</div>
`
);
this.wrapper.append(this.therapistContainer);
}
render() {
super.render();
}
} |
import dotenv from "dotenv";
import express, { json, urlencoded } from "express";
import cors from "cors";
import { createServer } from "http";
import { Server } from "socket.io";
import router from "./routes/index.js";
import { placeBid } from "./controllers/bidController.js";
dotenv.config();
const app = express();
const server = createServer(app);
const io = new Server(server);
app.use(urlencoded({ extended: true }));
app.use(cors());
app.use(json());
app.use("/", router);
// Socket.io setup
io.on("connection", (socket) => {
console.log("New client connected");
socket.on("disconnect", () => {
console.log("Client disconnected");
});
// Bid event
socket.on("bid", async (bidData) => {
try {
await placeBid(
{ params: { itemId: bidData.itemId }, user: { id: bidData.userId }, body: { bidAmount: bidData.bidAmount } },
null,
socket
);
} catch (error) {
socket.emit("error", error.message);
}
});
// Notify event
socket.on("notify", (notification) => {
io.emit("notify", notification); // Send notification to all connected clients
});
});
// Error handling middleware
app.use((err, req, res, next) => {
res.status(err.status || 500).json({
message: err.message || "Internal Server Error",
});
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
}); |
import {
Folder,
LogoMarkdown,
FileTraySharp,
LogoHtml5,
LogoCss3,
LogoWindows,
} from '@vicons/ionicons5';
import {
DocumentTextExtract20Regular,
DocumentChevronDouble20Regular,
DocumentJavascript20Regular,
DocumentPercent20Regular,
DocumentPdf32Filled,
DocumentBulletList20Regular,
MusicNote2Play20Regular,
Document20Regular,
DocumentBulletListClock20Regular,
DocumentLink24Regular,
DocumentSettings20Regular,
} from '@vicons/fluent';
import { shallowRef } from 'vue';
import { EXTENDS_MAP } from '@/constants';
import { FileIconType } from '@/models/file';
export const generate_file_icon = (ext: string): [type: string, icon: FileIconType | string] => {
const _ext = ext.slice(1).toLowerCase();
if (_ext === '') {
return ['文件夹', { style: 'text-primary', icon: shallowRef(Folder) }];
} else if (EXTENDS_MAP.IMAGE.includes(_ext)) {
return ['图片', 'media'];
} else if (EXTENDS_MAP.WORD.includes(_ext)) {
return ['文档', { style: 'text-gray-500', icon: shallowRef(DocumentTextExtract20Regular) }];
} else if (EXTENDS_MAP.CSV.includes(_ext)) {
return ['CSV', { style: 'text-gray-500', icon: shallowRef(DocumentBulletListClock20Regular) }];
} else if (EXTENDS_MAP.HTML.includes(_ext)) {
return ['HTML', { style: 'text-red-400', icon: shallowRef(LogoHtml5) }];
} else if (EXTENDS_MAP.CSS.includes(_ext)) {
return ['样式文件', { style: 'text-blue-500', icon: shallowRef(LogoCss3) }];
} else if (EXTENDS_MAP.CODE_SOURCE.includes(_ext)) {
return [
`${_ext}源文件`,
{ style: 'text-green-600', icon: shallowRef(DocumentChevronDouble20Regular) },
];
} else if (EXTENDS_MAP.JSON.includes(_ext)) {
return ['json', { style: 'text-yellow-500', icon: shallowRef(DocumentJavascript20Regular) }];
} else if (EXTENDS_MAP.JAVASCRIPT.includes(_ext)) {
return [
'js源文件',
{ style: 'text-yellow-500', icon: shallowRef(DocumentJavascript20Regular) },
];
} else if (EXTENDS_MAP.EXCEL.includes(_ext)) {
return ['表格', { style: 'text-gray-500', icon: shallowRef(DocumentPercent20Regular) }];
} else if (EXTENDS_MAP.PPT.includes(_ext)) {
return ['幻灯片', { style: 'text-red-400', icon: shallowRef(DocumentTextExtract20Regular) }];
} else if (EXTENDS_MAP.PDF.includes(_ext)) {
return ['PDF', { style: 'text-orange-300', icon: shallowRef(DocumentPdf32Filled) }];
} else if (EXTENDS_MAP.ZIP.includes(_ext)) {
return ['压缩文件', { style: 'text-primary', icon: shallowRef(FileTraySharp) }];
} else if (EXTENDS_MAP.TXT.includes(_ext)) {
return ['文本文件', { style: 'text-gray-500', icon: shallowRef(DocumentBulletList20Regular) }];
} else if (EXTENDS_MAP.AUDIO.includes(_ext)) {
return ['音频文件', { style: 'text-primary', icon: shallowRef(MusicNote2Play20Regular) }];
} else if (EXTENDS_MAP.VIDEO.includes(_ext)) {
return ['视频文件', 'media'];
} else if (EXTENDS_MAP.MARKDOWN.includes(_ext)) {
return ['markdown', { style: 'text-secondary', icon: shallowRef(LogoMarkdown) }];
} else if (EXTENDS_MAP.LINK.includes(_ext)) {
return ['link', { style: 'text-secondary', icon: shallowRef(DocumentLink24Regular) }];
} else if (EXTENDS_MAP.BAT.includes(_ext)) {
return [
'Windows批处理文件',
{ style: 'text-gray-500', icon: shallowRef(DocumentSettings20Regular) },
];
} else if (EXTENDS_MAP.EXE.includes(_ext)) {
return ['Windows应用程序', { style: 'text-secondary', icon: shallowRef(LogoWindows) }];
} else {
return [_ext, { style: 'text-gray-500', icon: shallowRef(Document20Regular) }];
}
}; |
/*******************************************************************************
* May 2022
** PUBLIC-USE LINKED MORTALITY FOLLOW-UP THROUGH DECEMBER 31, 2019 **
* The following Stata code can be used to read the fixed-width format ASCII
* public-use Linked Mortality Files (LMFs) from a stored location into a
* Stata dataset. Basic frequencies are also produced.
NOTE: The format definitions given below will result in procedure output
showing values that have been grouped as they are shown in the file layout
documentation.
To download and save the public-use LMFs to your hard drive, follow these steps:
*Step 1: Designate a folder on your hard drive to download the public-use LMF.
In this example, the data will be saved to: 'C:\PUBLIC USE DATA'
*Step 2: To download the public-use LMF, go to the web site:
https://ftp.cdc.gov/pub/health_statistics/nchs/datalinkage/linked_mortality/.
Right click on the desired survey link and select "Save target as...".
A "Save As" screen will appear where you will need to select and input
a location where to save the data file on your hard drive.
Also note that the "Save as type:" box should read "DAT File (*.dat)".
This will ensure that the data file is saved to your hard drive in the
correct format.
In this example, the data file is saved in the folder, "C:\PUBLIC USE DATA",
and the data file is saved as "<SURVEY>_MORT_2019_PUBLIC.DAT".
*/
cd "/Users/jiahejingzi/Desktop" // SET DIRECTORY WHERE DATA ARE LOCATED, E.G. "C:\PUBLIC USE DATA"
global SURVEY SURVEY_MORT_2019_PUBLIC // REPLACE <SURVEY> WITH RELEVANT SURVEY NAME (IN ALL CAPS)
* example syntax:
* global SURVEY NHIS_2018
* or
* global SURVEY NHANES_2017_2018
clear all
**************
*NHIS VERSION*
**************
// DEFINE VALUE LABELS FOR REPORTS
label define eligfmt 1 "Eligible" 2 "Under age 18, not available for public release" 3 "Ineligible"
label define mortfmt 0 "Assumed alive" 1 "Assumed deceased" .z "Ineligible or under age 18"
label define flagfmt 0 "No - Condition not listed as a multiple cause of death" 1 "Yes - Condition listed as a multiple cause of death" .z "Assumed alive, under age 18, ineligible for mortality follow-up, or MCOD not available"
label define qtrfmt 1 "January-March" 2 "April-June" 3 "July-September" 4 "October-December" .z "Ineligible, under age 18, or assumed alive"
label define dodyfmt .z "Ineligible, under age 18, or assumed alive"
label define ucodfmt 1 "Diseases of heart (I00-I09, I11, I13, I20-I51)"
label define ucodfmt 2 "Malignant neoplasms (C00-C97)" , add
label define ucodfmt 3 "Chronic lower respiratory diseases (J40-J47)" , add
label define ucodfmt 4 "Accidents (unintentional injuries) (V01-X59, Y85-Y86)" , add
label define ucodfmt 5 "Cerebrovascular diseases (I60-I69)" , add
label define ucodfmt 6 "Alzheimer's disease (G30)" , add
label define ucodfmt 7 "Diabetes mellitus (E10-E14)" , add
label define ucodfmt 8 "Influenza and pneumonia (J09-J18)" , add
label define ucodfmt 9 "Nephritis, nephrotic syndrome and nephrosis (N00-N07, N17-N19, N25-N27)" , add
label define ucodfmt 10 "All other causes (residual)" , add
label define ucodfmt .z "Ineligible, under age 18, assumed alive, or no cause of death data" , add
// READ IN THE FIXED-WIDTH FORMAT ASCII PUBLIC-USE LMF
infix str publicid 1-14 eligstat 15 mortstat 16 ucod_leading 17-19 diabetes 20 hyperten 21 dodqtr 22 dodyear 23-26 wgt_new 27-34 sa_wgt_new 35-42 using ${SURVEY}.dat
// REPLACE MISSING VALUES TO .z FOR LABELING
replace mortstat = .z if mortstat >=.
replace ucod_leading = .z if ucod_leading >=.
replace diabetes = .z if diabetes >=.
replace hyperten = .z if hyperten >=.
replace dodqtr = .z if dodqtr >=.
replace dodyear = .z if dodyear >=.
// DEFINE VARIABLE LABELS
label var publicid "NHIS Public-ID Number"
label var eligstat "Eligibility Status for Mortality Follow-up"
label var mortstat "Final Mortality Status"
label var ucod_leading "Underlying Cause of Death: Recode"
label var diabetes "Diabetes flag from Multiple Cause of Death"
label var hyperten "Hypertension flag from Multiple Cause of Death"
label var dodqtr "Quarter of Death"
label var dodyear "Year of Death"
label var wgt_new "Weight Adjusted for Ineligible Respondents: Person-level Sample Weight"
label var sa_wgt_new "Weight Adjusted for Ineligible Respondents: Sample Adult Sample Weight"
// ASSOCIATE VARIABLES WITH FORMAT VALUES
label values eligstat eligfmt
label values mortstat mortfmt
label values ucod_leading ucodfmt
label values dodqtr qtrfmt
label values diabetes flagfmt
label values hyperten flagfmt
label values dodyear dodyfmt
// DISPLAY OVERALL DESCRIPTION OF FILE
describe
// ONE-WAY FREQUENCIES (UNWEIGHTED)
tab1 eligstat mortstat ucod_leading diabetes hyperten dodqtr dodyear, missing
// SAVE DATA FILE IN DIRECTORY DESIGNATED AT TOP OF PROGRAM AS **SURVEY**_PUF.DTA
// replace option allows Stata to overwrite an existing .dta file
save ${SURVEY}_PUF , replace
******************
****************
*NHANES VERSION*
****************
clear all
// DEFINE VALUE LABELS FOR REPORTS
label define premiss .z "Missing"
label define eligfmt 1 "Eligible" 2 "Under age 18, not available for public release" 3 "Ineligible"
label define mortfmt 0 "Assumed alive" 1 "Assumed deceased" .z "Ineligible or under age 18"
label define flagfmt 0 "No - Condition not listed as a multiple cause of death" 1 "Yes - Condition listed as a multiple cause of death" .z "Assumed alive, under age 18, ineligible for mortality follow-up, or MCOD not available"
label define qtrfmt 1 "January-March" 2 "April-June" 3 "July-September" 4 "October-December" .z "Ineligible, under age 18, or assumed alive"
label define dodyfmt .z "Ineligible, under age 18, or assumed alive"
label define ucodfmt 1 "Diseases of heart (I00-I09, I11, I13, I20-I51)"
label define ucodfmt 2 "Malignant neoplasms (C00-C97)" , add
label define ucodfmt 3 "Chronic lower respiratory diseases (J40-J47)" , add
label define ucodfmt 4 "Accidents (unintentional injuries) (V01-X59, Y85-Y86)" , add
label define ucodfmt 5 "Cerebrovascular diseases (I60-I69)" , add
label define ucodfmt 6 "Alzheimer's disease (G30)" , add
label define ucodfmt 7 "Diabetes mellitus (E10-E14)" , add
label define ucodfmt 8 "Influenza and pneumonia (J09-J18)" , add
label define ucodfmt 9 "Nephritis, nephrotic syndrome and nephrosis (N00-N07, N17-N19, N25-N27)" , add
label define ucodfmt 10 "All other causes (residual)" , add
label define ucodfmt .z "Ineligible, under age 18, assumed alive, or no cause of death data" , add
// READ IN THE FIXED-WIDTH FORMAT ASCII PUBLIC-USE LMF
infix seqn 1-6 eligstat 15 mortstat 16 ucod_leading 17-19 diabetes 20 hyperten 21 permth_int 43-45 permth_exm 46-48 using ${SURVEY}.dat
// REPLACE MISSING VALUES TO .z FOR LABELING
replace mortstat = .z if mortstat >=.
replace ucod_leading = .z if ucod_leading >=.
replace diabetes = .z if diabetes >=.
replace hyperten = .z if hyperten >=.
replace permth_int = .z if permth_int >=.
replace permth_exm = .z if permth_exm >=.
// DEFINE VARIABLE LABELS
label var seqn "NHANES Respondent Sequence Number"
label var eligstat "Eligibility Status for Mortality Follow-up"
label var mortstat "Final Mortality Status"
label var ucod_leading "Underlying Cause of Death: Recode"
label var diabetes "Diabetes flag from Multiple Cause of Death"
label var hyperten "Hypertension flag from Multiple Cause of Death"
label var permth_int "Person-Months of Follow-up from NHANES Interview date"
label var permth_exm "Person-Months of Follow-up from NHANES Mobile Examination Center (MEC) Date"
// ASSOCIATE VARIABLES WITH FORMAT VALUES
label values eligstat eligfmt
label values mortstat mortfmt
label values ucod_leading ucodfmt
label values diabetes flagfmt
label values hyperten flagfmt
label value permth_int premiss
label value permth_exm premiss
// DISPLAY OVERALL DESCRIPTION OF FILE
describe
// ONE-WAY FREQUENCIES (UNWEIGHTED)
tab1 eligstat mortstat ucod_leading diabetes hyperten, missing
tab permth_int if permth_int==.z, missing
tab permth_exm if permth_exm==.z, missing
// SAVE DATA FILE IN DIRECTORY DESIGNATED AT TOP OF PROGRAM AS **SURVEY**_PUF.DTA
// replace option allows Stata to overwrite an existing .dta file
save ${SURVEY}_PUF, replace |
<template>
<div>
<h1>Registration Form</h1>
<form @submit.prevent="register">
<div>
<label for="nama">Nama:</label>
<input type="text" id="nama" v-model="nama" required>
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email" v-model="email" required>
</div>
<div>
<label for="Asal_Sekolah">Asal Sekolah:</label>
<input type="text" id="Asal_Sekolah" v-model="Asal_Sekolah" required>
</div>
<button type="submit">Submit</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
nama: '',
email: '',
Asal_Sekolah: ''
}
},
methods: {
async register() {
const data = {
nama: this.nama,
email: this.email,
Asal_Sekolah: this.Asal_Sekolah
}
try {
const response = await fetch('http://localhost:3100/api/pendaftaran', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
if (!response.ok) {
const errorMsg = (await response.json())?.errors[0].message
throw new Error(errorMsg)
}
alert('Pendaftaran berhasil!')
} catch (error) {
alert('Pendaftaran gagal ' + error.message)
}
}
}
}
</script> |
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { PageNotFoundComponent } from './modules/shared/page-not-found/page-not-found.component';
const routes: Routes = [
{
path: '',
pathMatch: 'full',
loadChildren: () =>
import('./modules/splash/splash.module').then((m) => m.SplashModule),
},
{
path: 'home',
redirectTo: '',
},
{
path: '**',
component: PageNotFoundComponent,
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {} |
"use client";
import UploadFileButton from "@/app/components/File/UploadFileButton";
import UploadUrlItem from "@/app/components/Urls/UploadUrlItem";
import { useSession } from "next-auth/react";
import { redirect, useSearchParams } from "next/navigation";
import React, { useEffect, useLayoutEffect, useState } from "react";
import { useThemeContext } from "../../context/theme";
import { app } from "../../../../firebase/FirebaseConfig";
import {
collection,
getDocs,
getFirestore,
query,
where,
} from "firebase/firestore";
import UrlItems from "@/app/components/Urls/UrlItems";
import FileItems from "@/app/components/File/FileItems";
import SideNavBar from "@/app/components/SideNavBar";
const KitDetails = ({ params }) => {
const searchParams = useSearchParams();
const [fileList, setFileList] = useState([]);
const [urlList, setUrlList] = useState([]);
const { showToast, setShowToast } = useThemeContext();
const id = params.kitId;
const db = getFirestore(app);
const { data: session, status } = useSession();
useLayoutEffect(() => {
if (session) {
getUrlList();
getFileList();
console.log(session.user.email);
} else {
redirect("/Login");
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [session, showToast]);
// fetch firebase and get files of the resource and user
const getFileList = async () => {
try {
new Promise((resolve, reject) => {
setFileList([]);
const q = query(
collection(db, "files"),
where("resourceId", "==", id),
);
getDocs(q)
.then(async (querySnapshot) => {
const fileList = [];
querySnapshot.forEach((doc) => {
fileList.push(doc.data());
});
resolve(fileList);
})
.catch(reject);
}).then((fileList) => {
setFileList(fileList);
});
} catch (e) {
console.error("Error reading document: ", e);
}
};
// fetch firebase and get urls of the resource and user
const getUrlList = async () => {
try {
new Promise((resolve, reject) => {
setUrlList([]);
const q = query(
collection(db, "Urls"),
where("resourceId", "==", id),
);
getDocs(q)
.then(async (querySnapshot) => {
const urlList = [];
querySnapshot.forEach((doc) => {
urlList.push(doc.data());
});
resolve(urlList);
})
.catch(reject);
}).then((urlList) => {
setUrlList(urlList);
});
} catch (e) {
console.error("Error reading document: ", e);
}
};
const name = searchParams.get("name");
// const urlElements = urlList.map((url) => <UrlItems url={url} key={url.id} />);
// console.log(`after urlList: ${JSON.stringify(urlList)}`);
return (
<div className="md:grid md:grid-cols-3 w-full min-h-screen md:gap-0 oveflow-auto overscroll-contain">
<SideNavBar />
<div className="w-full h-full col-span-2 p-8 bg-[#043547] sticky top-0 z-10">
<div className="flex justify-around items-center mb-10">
<h3 className="text-lg text-white">{name}</h3>
<UploadFileButton resourceId={params.kitId} />
</div>
<div className="flex flex-col gap-4">
<UploadUrlItem resourceId={params.kitId} />
</div>
<div className=" justify-around items-center mt-12">
{/* simple link */}
<div className="flex flex-col gap-4 mb-4">
{urlList.map((url, index) => (
<UrlItems url={url} key={index} />
))}
</div>
<div className="flex flex-col gap-4 text-left mt-12 text-gray-200">
<h3 className="text-lg">Files</h3>
{fileList.map((file, index) => (
<FileItems file={file} key={index} />
))}
</div>
</div>
</div>
</div>
);
};
export default KitDetails; |
import React, { useState } from "react";
import { useHistory } from "react-router-dom";
import { styled, alpha } from "@mui/material/styles";
import AppBar from "@mui/material/AppBar";
import Box from "@mui/material/Box";
import Toolbar from "@mui/material/Toolbar";
import IconButton from "@mui/material/IconButton";
import Typography from "@mui/material/Typography";
import InputBase from "@mui/material/InputBase";
import Badge from "@mui/material/Badge";
import MenuItem from "@mui/material/MenuItem";
import Menu from "@mui/material/Menu";
import SearchIcon from "@mui/icons-material/Search";
import HomeIcon from "@mui/icons-material/Home";
import GroupIcon from "@mui/icons-material/Group";
import WorkIcon from "@mui/icons-material/Work";
import TextsmsIcon from "@mui/icons-material/Textsms";
import NotificationsIcon from "@mui/icons-material/Notifications";
import MenuIcon from "@mui/icons-material/Menu";
import { Avatar } from "@mui/material";
import { logout, selectUser } from "../features/userSlice";
import { auth } from "../firebase";
import { useDispatch, useSelector } from "react-redux";
const StyledAppbar = styled(AppBar)(({ theme }) => ({
boxShadow: theme.shadows[1],
}));
const Search = styled("div")(({ theme }) => ({
position: "relative",
borderRadius: theme.shape.borderRadius,
backgroundColor: alpha(theme.palette.common.white, 0.15),
"&:hover": {
backgroundColor: alpha(theme.palette.common.white, 0.25),
},
marginRight: theme.spacing(2),
marginLeft: 0,
width: "100%",
[theme.breakpoints.up("sm")]: {
marginLeft: theme.spacing(3),
width: "auto",
},
}));
const Logo = styled("img")(({ theme }) => ({
objectFit: "contain",
height: "4rem",
padding: ".5rem",
}));
const SearchIconWrapper = styled("div")(({ theme }) => ({
padding: theme.spacing(0, 2),
height: "100%",
position: "absolute",
pointerEvents: "none",
display: "flex",
alignItems: "center",
justifyContent: "center",
zIndex: 10,
}));
const StyledInputBase = styled(InputBase)(({ theme }) => ({
color: "inherit",
"& .MuiInputBase-input": {
padding: theme.spacing(1, 1, 1, 0),
// vertical padding + font size from searchIcon
paddingLeft: `calc(1.2em + ${theme.spacing(4)})`,
transition: theme.transitions.create("width"),
width: "100%",
backgroundColor: theme.palette.grey[200],
[theme.breakpoints.up("md")]: {
width: "20ch",
},
},
}));
const StyledMenuItem = styled(IconButton)(({ theme }) => ({
display: "flex",
flexDirection: "column",
padding: "4px 8px",
transition: "all .3s",
"&:hover": {
color: theme.palette.text.primary,
},
}));
export default function Header() {
const [anchorEl, setAnchorEl] = useState(null);
const [mobileMoreAnchorEl, setMobileMoreAnchorEl] = useState(null);
const history = useHistory();
const dispatch = useDispatch();
const user = useSelector(selectUser);
const logoutApp = () => {
handleMenuClose();
dispatch(logout());
auth.signOut();
};
const MenuItems = [
{
icon: HomeIcon,
title: "Home",
badge: 0,
},
{
icon: GroupIcon,
title: "My Network",
badge: 0,
},
{
icon: WorkIcon,
title: "Jobs",
badge: 0,
},
{
icon: TextsmsIcon,
title: "Messaging",
badge: 0,
},
{
icon: NotificationsIcon,
title: "Notifications",
badge: 2,
},
];
const isMenuOpen = Boolean(anchorEl);
const isMobileMenuOpen = Boolean(mobileMoreAnchorEl);
const handleProfileMenuOpen = (event) => {
setAnchorEl(event.currentTarget);
};
const handleMobileMenuClose = () => {
setMobileMoreAnchorEl(null);
};
const handleMenuClose = () => {
setAnchorEl(null);
handleMobileMenuClose();
};
const handleMobileMenuOpen = (event) => {
setMobileMoreAnchorEl(event.currentTarget);
};
const menuId = "primary-search-account-menu";
const renderMenu = (
<Menu
anchorEl={anchorEl}
anchorOrigin={{
vertical: "top",
horizontal: "right",
}}
id={menuId}
keepMounted
transformOrigin={{
vertical: "top",
horizontal: "right",
}}
open={isMenuOpen}
onClose={handleMenuClose}
sx={{ padding: "2rem" }}
>
<MenuItem onClick={logoutApp}>Log out</MenuItem>
</Menu>
);
const mobileMenuId = "primary-search-account-menu-mobile";
const renderMobileMenu = (
<Menu
anchorEl={mobileMoreAnchorEl}
anchorOrigin={{
vertical: "top",
horizontal: "left",
}}
id={mobileMenuId}
keepMounted
transformOrigin={{
vertical: "top",
horizontal: "right",
}}
open={isMobileMenuOpen}
onClose={handleMobileMenuClose}
>
{MenuItems.map((item, idx) => (
<MenuItem key={idx}>
<IconButton
size="large"
aria-label="show 17 new notifications"
color="inherit"
>
<Badge badgeContent={item.badge} color="error">
<item.icon />
</Badge>
</IconButton>
<Typography variant="caption">{item.title}</Typography>
</MenuItem>
))}
</Menu>
);
return (
<Box sx={{ flexGrow: 1 }}>
<StyledAppbar position="sticky">
<Toolbar variant="dense">
<Logo src="./logo.png" alt="linkedin logo" />
<Search>
<SearchIconWrapper>
<SearchIcon color="default" size={10} />
</SearchIconWrapper>
<StyledInputBase
placeholder="Search…"
inputProps={{ "aria-label": "search" }}
/>
</Search>
<Box sx={{ flexGrow: 1 }} />
<Box
sx={{
display: { xs: "none", md: "flex" },
}}
>
{MenuItems.map((item, i) => (
<StyledMenuItem
size="medium"
color="default"
key={i}
disableRipple
style={{
backgroundColor: "transparent",
paddingBottom: "none",
}}
>
<Badge badgeContent={item.badge} color="error">
<item.icon sx={{ height: 20, width: 20 }} />
</Badge>
<Typography variant="caption">{item.title}</Typography>
</StyledMenuItem>
))}
<IconButton
size="large"
edge="end"
aria-label="account of current user"
aria-controls={menuId}
aria-haspopup="true"
onClick={handleProfileMenuOpen}
color="inherit"
>
<Avatar
alt="me"
src={user.photoUrl && user.photoUrl}
sx={{ width: 40, height: 40 }}
>
{user.displayName && user.displayName[0]}
</Avatar>
</IconButton>
</Box>
<Box sx={{ display: { xs: "flex", md: "none" } }}>
<IconButton
size="large"
aria-label="show more"
aria-controls={mobileMenuId}
aria-haspopup="true"
onClick={handleMobileMenuOpen}
color="inherit"
>
<MenuIcon />
</IconButton>
</Box>
</Toolbar>
</StyledAppbar>
{renderMobileMenu}
{renderMenu}
</Box>
);
} |
package com.example.exercise04
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.exercise04.databinding.ActivityProductAddBinding
class ProductAddActivity : AppCompatActivity() {
lateinit var binding: ActivityProductAddBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityProductAddBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.saveButton.setOnClickListener { _ ->
var productType = ProdType.FOOD
when (binding.radioGroup.checkedRadioButtonId) {
R.id.foodRadioButton -> productType = ProdType.FOOD
R.id.drinkRadioButton -> productType = ProdType.DRINK
R.id.cleaningRadioButton -> productType = ProdType.CLEANING
}
val product = ProductModel(
binding.editName.text.toString(),
binding.editTextTextMultiLine.text.toString(),
productType,
binding.editPrice.text.toString().toDouble(),
binding.ratingBar3.rating,
)
val intent = intent
intent.putExtra("product", product)
setResult(RESULT_OK, intent)
finish()
}
binding.cancelButton.setOnClickListener { _ ->
setResult(RESULT_CANCELED)
finish()
}
}
} |
package com.example.snwbackend.controller;
import com.example.snwbackend.request.ContactRequest;
import com.example.snwbackend.request.UpsertConversationRequest;
import com.example.snwbackend.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("api/chat")
public class ChatController {
@Autowired
private ChatService chatService;
@PostMapping("")
public ResponseEntity<?> createConversation(@RequestBody ContactRequest request) {
return new ResponseEntity<>(chatService.createSingleConversation(request), HttpStatus.CREATED);
}
@PostMapping("group-chat")
public ResponseEntity<?> createGroupChat(@RequestBody UpsertConversationRequest request) {
return new ResponseEntity<>(chatService.createGroupChat(request), HttpStatus.CREATED);
}
@GetMapping("")
public ResponseEntity<?> getAllConversation( @RequestParam(required = false, defaultValue = "0") Integer page,
@RequestParam(required = false, defaultValue = "10") Integer pageSize) {
return ResponseEntity.ok(chatService.getAllConversation(page, pageSize));
}
@GetMapping("archive")
public ResponseEntity<?> getAllArchiveConversation( @RequestParam(required = false, defaultValue = "0") Integer page,
@RequestParam(required = false, defaultValue = "10") Integer pageSize) {
return ResponseEntity.ok(chatService.getAllArchiveConversation(page, pageSize));
}
@GetMapping("{id}")
public ResponseEntity<?> getConversationById(@PathVariable Integer id) {
return ResponseEntity.ok(chatService.getConversationById(id));
}
@GetMapping("message/{conversationId}")
public ResponseEntity<?> getAllMessageByConversationId(@PathVariable Integer conversationId,
@RequestParam(required = false, defaultValue = "0") Integer page,
@RequestParam(required = false, defaultValue = "10") Integer pageSize) {
return ResponseEntity.ok(chatService.getAllMessageByConversationId(conversationId, page, pageSize));
}
@PutMapping("read/{conversationId}")
public ResponseEntity<?> resetUnreadCountByConversationId(@PathVariable Integer conversationId) {
return ResponseEntity.ok(chatService.resetUnreadCountByConversationId(conversationId));
}
@GetMapping("unread-count")
public ResponseEntity<?> getAllUnreadCount() {
return ResponseEntity.ok((chatService.getAllUnreadCount()));
}
@PutMapping("archive-chat/{conversationId}")
public ResponseEntity<?> toggleSetArchiveChat(@PathVariable Integer conversationId) {
return ResponseEntity.ok(chatService.toggleSetArchiveChat(conversationId));
}
} |
//const canvas = document.getElemenyById("myc");
let canvas = document.getElementById("mycanvas")
const app = new PIXI.Application({
backgroundColor: 0x1099bb,
view: canvas,
width: window.innerWidth,
height: window.innerHeight,
});
// Below App Function
let loader = PIXI.Loader.shared;
let player, enemy, ball;
let floors = [];
let walls = [];
let image;
let up = keyboard('ArrowUp');
let down = keyboard('ArrowDown');
loader
.add('bar', 'images/bar.png')
.add('ball', 'images/ball.png')
.add('enemy', 'images/barenemy.png')
.add('wall', 'images/wall.png')
.load(setup);
function setup() {
// Loading each texture
let bar_texture = loader.resources.bar.texture;
let ball_texture = loader.resources.ball.texture;
let wall_texture = loader.resources.wall.texture;
let enemy_texture = loader.resources.enemy.texture;
// Creating container to set all our sprites inside.
let stage = new PIXI.Container();
app.stage.addChild(stage);
// Placing the stage container in the center of the screen
stage.x = app.screen.width / 2;
stage.y = app.screen.height / 2;
// Adding Player and Enemy Sprites and Positions
player = new PIXI.Sprite(bar_texture);
stage.addChild(player);
player.x = -300;
player.anchor.set(.5);
enemy = new PIXI.Sprite(enemy_texture);
stage.addChild(enemy);
enemy.x = 300;
enemy.anchor.set(.5);
// Adding the ball
ball = new PIXI.Sprite(ball_texture);
stage.addChild(ball);
ball.x = 0;
ball.anchor.set(.5);
// Setting up the walls
for (let i = 0; i < 68; i++) {
let new_wall = new PIXI.Sprite(wall_texture);
let new_floor = new PIXI.Sprite(wall_texture);
walls.push(new_wall);
stage.addChild(walls[i]);
walls[i].y = -200;
walls[i].x = -300 + i * 9;
walls[i].anchor.set(.5);
floors.push(new_floor);
stage.addChild(floors[i]);
floors[i].y = 200;
floors[i].x = -300 + i * 9;
floors[i].anchor.set(0.5);
}
// We will use this to keep track of the ball's direction
ball.vx = 1;
ball.vy = 0;
// Player and Enemy would just move up and down, so it'll just need vy.
player.vy = 0;
enemy.vy = 0;
// Controls
up.press = () => {
player.vy = -1;
};
up.release = () => {
player.vy = 0;
};
down.press = () => {
player.vy = 1;
};
down.release = () => {
player.vy = 0;
};
app.ticker.add(delta => game(delta));
}
function game(delta) {
// counter = 0
// console.log("Hello " + counter++);
let speed = 5 * delta;
// Check Collision of Ball with Player + Enemy
if (check_collid(ball, enemy) || check_collid(ball, player)) {
ball.vx *= -1;
}
// Movement for ball and players
ball.x += ball.vx * speed;
ball.y += ball.vy * speed;
player.y += player.vy * speed;
enemy.y += enemy.vy * speed;
}
function check_collid(r1, r2) {
// Define variables we'll use to calculate
let hit, combinedHalfWidths, combinedHalfHeights, vx, vy;
// hit will determine whether there's a collision
hit = false;
// Find the center points of each sprite
r1.centerX = r1.x;
r1.centerY = r1.y;
r2.centerX = r2.x;
r2.centerY = r2.y;
// Find the half-widths and half-heights of each sprite
r1.halfWidth = r1.width / 2;
r1.halfHeight = r1.height / 2;
r2.halfWidth = r2.width / 2;
r2.halfHeight = r2.height / 2;
// Calculate the distance vectors between sprites
vx = r1.centerX - r2.centerX;
vy = r1.centerY - r2.centerY;
// Figure out the combined half-widths and half-heights
combinedHalfWidths = r1.halfWidth + r2.halfWidth;
combinedHalfHeights = r1.halfHeight + r2.halfHeight;
// Check collision on x axis
if (Math.abs(vx) < combinedHalfWidths) {
// A collisoin might be occuring. Check for it on y axis
if (Math.abs(vy) < combinedHalfHeights) {
// There's definitely a collision happening
hit = true;
} else {
hit = false;
}
} else {
hit = false;
}
return hit;
}
function keyboard(value) {
let key = {};
key.value = value;
key.isDown = false;
key.isUp = true;
key.press = undefined;
key.release = undefined;
key.downHandler = event => {
if (event.key === key.value) {
if (key.isUp && key.press) key.press();
key.isDown = true;
key.isUp = false;
event.preventDefault();
}
};
key.upHandler = event => {
if (event.key === key.value) {
if (key.isDown && key.release) key.release();
key.isDown = false;
key.isUp = true;
event.preventDefault();
}
};
// Attach Event listeners
const downListener = key.downHandler.bind(key);
const upListener = key.upHandler.bind(key);
window.addEventListener("keydown", downListener, false);
window.addEventListener("keyup", upListener, false);
// Detach event listeners
key.unsubscribe = () => {
window.removeEventListener("keydown", downListener);
window.removeEventListener("keyup", upListener);
};
return key;
}; |
/*
* Copyright (C) 2017 Google 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.
*/
package com.mytown.sd.entry
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.mytown.sd.R
import com.mytown.sd.extension.toFormattedString
import com.mytown.sd.persistence.User
class UserListAdapter internal constructor(
context: Context
) : RecyclerView.Adapter<UserListAdapter.UserViewHolder>() {
private val inflater: LayoutInflater = LayoutInflater.from(context)
private var users = emptyList<User>() // Cached copy of words
inner class UserViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val nameTextView: TextView = itemView.findViewById(R.id.nameText)
val mobileTextView: TextView = itemView.findViewById(R.id.mobileText)
val temperatureTextView: TextView = itemView.findViewById(R.id.temperatureText)
val dateTextView: TextView = itemView.findViewById(R.id.dateText)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
val itemView = inflater.inflate(R.layout.recyclerview_item, parent, false)
return UserViewHolder(itemView)
}
override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
val context =holder.temperatureTextView.context
val current = users[position]
holder.nameTextView.text = current.name
holder.mobileTextView.text = current.mobileNumber
holder.dateTextView.text = current.timeStamp!!.toFormattedString()
if(current.temperature ==context.getString(R.string.empty)){
holder.temperatureTextView.text = "${current.temperature}"
}else {
holder.temperatureTextView.text =
"${current.temperature}${holder.temperatureTextView.context.getString(R.string.degree)}"
}
}
internal fun setUsers(words: List<User>) {
this.users = words
notifyDataSetChanged()
}
override fun getItemCount() = users.size
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Grafico Chart</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>
</head>
<body>
<canvas id="myChart" width="400" height="400"> </canvas>
<script>
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
type: "pie" /* tipo de grafico */,
data: {
labels: ["col1", "col2", "col3"] /* datos */,
datasets: [
{
label: "Num datos" /* label de titulo */,
data: [10, 9, 15] /* valores de los datos */,
backgroundColor: [
/* colores */
"rgb(66, 134, 244,0.5)",
"rgb(74, 135, 72,0.5)",
"rgb(229, 89, 50,0.5)"
]
}
]
},
options: {
/* esto lo hace visible en graficos tipo bar */
scales: {
yAxes: [
/* en el eje y */
{
ticks: {
beginAtZero: true /* que comienze desde cero */
}
}
]
}
}
});
</script>
</body>
</html> |
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.InputMismatchException;
/*
* Purpose: Contains the maian method, reads .txt files to import data,
* interprets data, creates a Party object, and hosts menu.
*/
/**
* Tester.java
* Author: Oliver Szabo
* Date: November 27, 2023, 11:59 PM
* Purpose: Contains the main method, reads .txt files to import data,
* interprets data, creates a Party object, and hosts menu.
*/
public class Tester
{
/*
* Main method which hosts ArrayLists of Persons corresponding to
* a party's unregistered and registered guests, an ArrayList of Companies
* for the companies in attendance, a Party object and its methods, and
* a menu from which the user can access the different methods of the
* declared Party object.
* Args: String[] args
* Returns: void
*/
public static void main(String[] args)
{
System.out.println("Welcome!");
System.out.println("If you haven't done so already, please load in the following files:");
System.out.println("partyguests.txt");
System.out.println("companies.txt"); // Inviting user to load in files.
System.out.println("------");
System.out.println("Beginning file import process.");
ArrayList<String> peopleString = new ArrayList<String>();
ArrayList<String> companiesString = new ArrayList<String>(); // Create ArrayLists for the raw Strings imported from .txt file
ArrayList<ArrayList<String>> peopleStringSeparated = new ArrayList<ArrayList<String>>();
ArrayList<ArrayList<String>> companiesStringSeparated = new ArrayList<ArrayList<String>>(); // 2D ArrayLists of Strings to separate values
Scanner scanInput = new Scanner(System.in);
// Credit for importing file methods: https://www.w3schools.com/java/java_files_read.asp
// Challenge: Decided on writing two separate data importing processes, because with the
// difference in formats between Company and Person, it was easier to import data separately
/*
* Loads data from "partyguests.txt" into an ArrayList<String>
*/
try
{
File partyGuests = new File("partyguests.txt");
Scanner scanGuests = new Scanner(partyGuests);
while (scanGuests.hasNextLine())
{
String scanned = scanGuests.nextLine();
if (!scanned.equals(""))
{
peopleString.add(scanned);
}
}
}
catch (FileNotFoundException e) // Challenge: FileNotFoundException needs to be imported for try/catch to work.
{
System.out.println("------");
System.out.println("File 'partyguests.txt' not found. Please place this file in the same directory as Tester.java.");
System.exit(1);
}
/*
* Loads data from "companies.txt" into an ArrayList<String>
*/
try
{
File companies = new File("companies.txt");
Scanner scanCompanies = new Scanner(companies);
while (scanCompanies.hasNextLine())
{
String scanned = scanCompanies.nextLine();
if (!scanned.equals("")) // Filtering out empty lines
{
companiesString.add(scanned);
}
}
}
catch (FileNotFoundException e)
{
System.out.println("------");
System.out.println("File 'companies.txt' not found. Please place this file in the same directory as Tester.java.");
System.exit(1);
}
/*
* Splits String of imported data into separate Strings for
* data imported from "partyguests.txt"
*/
for(int i = 0; i < peopleString.size(); i++)
{
for(int j = 0; j < 5; j++)
{
peopleStringSeparated.add(new ArrayList<String>());
}
peopleStringSeparated.get(0).add(peopleString.get(i)); // Challenge: Decided on numbering 1st column due to better organization
String[] arrPeople = peopleString.get(i).split(",",4);
peopleStringSeparated.get(1).add(arrPeople[0]);
peopleStringSeparated.get(2).add(arrPeople[1]);
peopleStringSeparated.get(3).add(arrPeople[2]);
peopleStringSeparated.get(4).add(arrPeople[3]);
}
/*
* Splits String of imported data into separate Strings for
* data imported from "companies.txt"
*/
for(int i = 0; i < companiesString.size(); i++)
{
for(int j = 0; j < 2; j++)
{
companiesStringSeparated.add(new ArrayList<String>());
}
String[] arrPeople = companiesString.get(i).split(",",2);
companiesStringSeparated.get(0).add(arrPeople[0]);
companiesStringSeparated.get(1).add(arrPeople[1]);
}
/*
* Creates two ArrayLists that represent the unregistered guests
* and the companies, importing data into new objects
*/
ArrayList<Person> unregistered = new ArrayList<Person>();
ArrayList<Company> companies = new ArrayList<Company>();
for(int i = 0; i < peopleString.size(); i++)
{
unregistered.add(new Person(Integer.parseInt(peopleStringSeparated.get(1).get(i)),
peopleStringSeparated.get(2).get(i), // Challenge: Had to do some more research about wrapper classes
peopleStringSeparated.get(3).get(i),
Integer.parseInt(peopleStringSeparated.get(4).get(i))));
}
for(int i = 0; i < companiesString.size(); i++)
{
companies.add(new Company(Integer.parseInt(companiesStringSeparated.get(0).get(i)),
companiesStringSeparated.get(1).get(i)));
}
/*
* Initializes a Party object and creates and initializes an
* array of ArrayLists, representing the different tables at which
* guests will sit
*/
Party ihrpsConference = new Party(100,10);
@SuppressWarnings("unchecked") // Credit: Marcus Twyford
ArrayList<Person>[] table = new ArrayList[ihrpsConference.getTables()]; // Created Array of ArrayLists to ensure number of tables is fixed
for (int i = 0; i < ihrpsConference.getTables(); i++)
{
table[i] = new ArrayList<Person>(); // Initially ran into problems initializing each individual array list
}
/*
* See Party.java for more information on these methods
*/
ihrpsConference.arrangeEmployeesAtTables(table, unregistered);
ihrpsConference.unregisteredError(unregistered);
/*
* Acts as the main "hub" for a user's actions when interacting
* with the Party object declared earlier
*/
while(true) // Inspired by Arduino to have an endless loop of menus so that user can simply close when finished
{
int input;
do
{
System.out.println("Please select an option from the menu.");
System.out.println("1. Register Guest");
System.out.println("2. Print roster by table number");
System.out.println("3. Print roster by company number");
System.out.println("4. Search Guest");
System.out.println("------");
input = 0;
try
{
input = scanInput.nextInt();
}
catch (InputMismatchException e) {} // Challenge: Decided to keep input as 0 if user input is invalid
System.out.println("------");
if (input < 1 || input > 4)
{
System.out.println("Invalid input.");
System.out.println("------");
scanInput.nextLine();
}
if (input == 1) ihrpsConference.registerGuest(table,unregistered,companies);
else if (input == 2) ihrpsConference.rosterByTable(table);
else if (input == 3) ihrpsConference.rosterByCompany(table,companies,unregistered);
else if (input == 4) ihrpsConference.searchGuest(table,unregistered);
}
while (input < 1 || input > 4);
}
}
} |
package get_requests;
import base_urls.JsonPlaceHolderBaseUrlK;
import io.restassured.response.Response;
import org.junit.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class Get08K extends JsonPlaceHolderBaseUrlK {
//De-Serialization: Json datayı Java objesine çevirme
//Serialization: Java objesini Json formatına çevirme.
//De-Serialization: Iki türlü yapacağız.
//Gson: Google tarafından üretilmiştir.
//Object Mapper: Daha popüler...
/*
Given
https://jsonplaceholder.typicode.com/todos/2
When
I send GET Request to the URL
Then
Status code is 200
And "completed" is false
And "userId" is 1
And "title" is "quis ut nam facilis et officia qui"
And header "Via" is "1.1 vegur"
And header "Server" is "cloudflare"
{
"userId": 1,
"id": 2,
"title": "quis ut nam facilis et officia qui",
"completed": false
}
*/
@Test
public void get08k() {
spec.pathParams("first","todos","second",2);
Response response=given().spec(spec).when().get("/{first}/{second}");
response.then().assertThat().statusCode(200).body("userId",equalTo(1)
,"title",equalTo("quis ut nam facilis et officia qui")
,"completed",equalTo(false));
response.header("Via").equals("1.1 vegur");
response.header("Server").equals("cloudflare");
response.prettyPrint();
}
} |
import os
import random
from collections import defaultdict
import numpy as np
import pandas as pd
import torch
from torch.utils.data import DataLoader
from embeding_dataset import CustomDataset
from model import H14_NSFW_Detector
train_ratio = 0.7
label_ind_dict = {'drawings': 0, 'hentai': 1, 'neutral': 2, 'porn': 3, 'sexy': 4}
bad_label_list = ["porn", "hentai"]
# trainfile https://drive.google.com/file/d/1yenil0R4GqmTOFQ_GVw__x61ofZ-OBcS/view?usp=sharing 据说没标注
# testfile https://github.com/LAION-AI/CLIP-based-NSFW-Detector/blob/main/nsfw_testset.zip 据说标注过
class ModelTrainer:
def __init__(self, data_dir: str, model_dir: str, dim=768, device="cuda",
additional_train_label_emb_dict=None,
additional_test_label_emb_dict=None):
# data
self.additional_train_label_emb_dict = additional_train_label_emb_dict
self.additional_test_label_emb_dict = additional_test_label_emb_dict
self.data_dir = data_dir
os.makedirs(data_dir, exist_ok=True)
self.model = H14_NSFW_Detector(dim, len(label_ind_dict)).to(device)
self.model_dir = model_dir
self.device = device
os.makedirs(self.model_dir, exist_ok=True)
def download_origin_data(self, ):
# 国内网络问题,未debug,可直接下载后放入文件夹
train_url = "https://drive.google.com/file/d/1yenil0R4GqmTOFQ_GVw__x61ofZ-OBcS/view?usp=sharing"
res = os.system(
f"wget --no-check-certificate '{train_url}' -O {self.data_dir}/train.zip")
assert res == 0
test_url = "https://github.com/LAION-AI/CLIP-based-NSFW-Detector/blob/main/nsfw_testset.zip"
res = os.system(
f"wget --no-check-certificate '{test_url}' -O {self.data_dir}/test.zip")
assert res == 0
os.system(f"unzip {self.data_dir}/train.zip -d {self.data_dir}/train")
os.system(f"unzip {self.data_dir}/test.zip -d {self.data_dir}/test")
def load_dataloader(self):
train_emb_dict = self.load_dir_emb_dict(os.path.join(self.data_dir, "train"))
test_emb_dict = self.load_dir_emb_dict(os.path.join(self.data_dir, "test/nsfw_testset"))
all_data_list = []
for k, v in train_emb_dict.items():
for i in range(len(v)):
all_data_list.append((v[i], k))
if self.additional_train_label_emb_dict is not None:
for k, v in self.additional_train_label_emb_dict.items():
for i in range(len(v)):
all_data_list.append((v[i], k))
random.shuffle(all_data_list)
train_data_len = int(len(all_data_list) * train_ratio)
train_data_list = all_data_list[:train_data_len]
val_data_list = all_data_list[train_data_len:]
train_dataset = CustomDataset(train_data_list, label_ind_dict)
val_dataset = CustomDataset(val_data_list, label_ind_dict)
train_dataloader = DataLoader(train_dataset, batch_size=256, shuffle=True)
val_dataloader = DataLoader(val_dataset, batch_size=256, shuffle=False)
test_data_list = []
for k, v in test_emb_dict.items():
label = k.split("-")[0]
for i in range(len(v)):
test_data_list.append((v[i], label))
if self.additional_test_label_emb_dict is not None:
for k, v in self.additional_test_label_emb_dict.items():
for i in range(len(v)):
test_data_list.append((v[i], k))
test_dataset = CustomDataset(test_data_list, label_ind_dict)
test_dataloader = DataLoader(test_dataset, batch_size=128, shuffle=False)
return train_dataloader, val_dataloader, test_dataloader
def load_dir_emb_dict(self, file_path):
dir_list = os.listdir(file_path)
dir_emb_dict = {}
for dir1 in dir_list:
emd_file_path = os.path.join(os.path.join(file_path, dir1), "img_emb/img_emb_0.npy")
if os.path.exists(emd_file_path):
dir_emb_dict[dir1] = np.load(emd_file_path)
return dir_emb_dict
def train(self, epoch_amount):
# 主函数,需要先下载数据之后就可以了
train_dataloader, val_dataloader, test_dataloader = self.load_dataloader()
optimizer = torch.optim.Adam(self.model.parameters(), lr=0.001)
loss_func = torch.nn.CrossEntropyLoss()
for epoch in range(epoch_amount):
self.model.train()
for i, (data, label) in enumerate(train_dataloader):
label = label.to(self.device)
optimizer.zero_grad()
output = self.model(data.to(self.device))
loss = loss_func(output, label)
loss.backward()
optimizer.step()
if i % 100 == 0:
print(f"epoch: {epoch}, step: {i}, loss: {loss.item()}")
print("val")
self.show_model_dataloader_result(self.model, val_dataloader)
print("test")
self.show_model_dataloader_result(self.model, test_dataloader)
torch.save(self.model.state_dict(), os.path.join(self.model_dir, f"model_{epoch}.pth"))
@staticmethod
def show_model_dataloader_result(model, dataloader):
# 测试集drawing效果较差,不确定是不是测试集数据or训练数据集问题,但是本身不影响nsfw的训练,
# 本身有展示bad 和good的ratio
model.eval()
label_count_dict = defaultdict(int)
label_acc_dict = defaultdict(int)
label_error_count_dict = defaultdict(lambda: defaultdict(int))
with torch.no_grad():
correct = 0
total = 0
for i, (data, label) in enumerate(dataloader):
output = model(data.to(self.device)).cpu()
_, predicted = torch.max(output, 1)
total += label.size(0)
correct += (predicted == label).sum().item()
for p, l in zip(predicted, label):
if p == l:
label_acc_dict[int(l)] += 1
else:
label_error_count_dict[int(l)][int(p)] += 1
label_count_dict[int(l)] += 1
print(f"accuracy: {correct / total}")
result = []
ind_label_dict = {v: k for k, v in label_ind_dict.items()}
for label, ind in label_ind_dict.items():
amount = label_count_dict[ind]
acc = label_acc_dict[ind]
acc_ratio = f"{round(acc / amount * 100, 1)}%"
new_error_count_dict = {}
for k, v in label_error_count_dict[ind].items():
new_error_count_dict[ind_label_dict[k]] = v
good_amount = 0
bad_amount = 0
if label in bad_label_list:
bad_amount = acc
else:
good_amount = acc
for k, v in label_error_count_dict[ind].items():
if ind_label_dict[k] in bad_label_list:
bad_amount += v
else:
good_amount += v
result.append(
dict(label=label, amount=amount, acc=acc, aac_ratio=acc_ratio,
good_ratio=round(good_amount / amount * 100, 1),
bad_ratio=round(bad_amount / amount * 100, 1), error_count_dict=new_error_count_dict, )
)
print(pd.DataFrame(result))
return result
self = ModelTrainer("./nsfw_data", "./tmp+model", 768) |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Promise</title>
</head>
<body>
<label for="zip">Zip Code:</label>
<input type="number" id="zip" /> <!-- 創建可以給使用者輸入的地方, type 是輸入類型-->
<button id="btnGetInfo">Get Info</button>
<div id="info"></div>
<script>
const btnGetInfo = document.getElementById('btnGetInfo');
btnGetInfo.onclick = () => getResponse();
// await: 在 Promise 結束前, 後面的 Code 都無法被執行.
// await 的錯誤會讓 async 拋出 error, 在正確執行下, 會 return resolved, 否則 return rejected 的狀態
async function getResponse() {
const zip = document.getElementById('zip').value;
const zipURL = `http://api.zippopotam.us/us/${zip}`;
const response = await fetch(zipURL);
const data = await response.json();
console.log(data);
displayResult(data);
}
displayResult = (data) => {
const city = data.places[0]["place name"];
const state = data.places[0].state;
document.getElementById("info").innerHTML = `<h1>${city}, ${state}</h1>`;
}
</script>
</body>
</html> |
/*
Two phrases are anagrams if they are permutations of each other, ignoring spaces and capitalization. For example, "Aaagmnrs" is an anagram of "anagrams", and "TopCoder" is an anagram of "Drop Cote". Given a String[] phrases, remove each phrase that is an anagram of an earlier phrase, and return the remaining phrases in their original order.
In writing code you'll need to return a new array whose elements aren't anagrams of each other.
phrases contains between 2 and 50 elements, inclusive.
Each element of phrases contains between 1 and 50 characters, inclusive.
Each element of phrases contains letters ('a'-'z' and 'A'-'Z') and spaces (' ') only.
Each element of phrases contains at least one letter.
*/
import java.util.*;
import java.util.Arrays;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;
public class Aaagmnrs {
public String[] anagrams(String[] phrases) {
Set<String> result = new HashSet<String>();
Map<String, String> map = new HashMap<String, String>();
for (String s : phrases) {
char[] c = s.toCharArray();
Arrays.sort(c);
String sorted = new String(c);
if (map.containsKey(sorted)) {
result.add(map.get(sorted));
}
map.put(sorted, s);
}
return result.toArray(new String[result.size()]);
}
} |
import { PrismaService } from './../prisma/prisma.service';
import { Injectable, NotFoundException } from '@nestjs/common';
import { HomeResponseDto, UpdateHomeDto } from './dto/home.dto';
import { PropertyType } from '@prisma/client';
interface GetHomeParams {
city?: string;
price?: {
gte?: number;
lte?: number;
};
propertyType?: string;
}
interface CreateHomeParams {
address: string;
numberOfBedrooms: number;
numberOfBathrooms: number;
city: string;
price: number;
landSize: number;
propertyType: PropertyType;
images: { url: string }[];
}
interface UpdateHomeParams {
address?: string;
numberOfBedrooms?: number;
numberOfBathrooms?: number;
city?: string;
price?: number;
landSize?: number;
propertyType?: PropertyType;
}
interface NavigationFilters {
skip?: number;
take?: number;
}
@Injectable()
export class HomeService {
constructor(private readonly PrismaService: PrismaService) {}
async getHomes(
filters: GetHomeParams,
navigation: NavigationFilters,
): Promise<HomeResponseDto[]> {
const homes = await this.PrismaService.home.findMany({
select: {
id: true,
address: true,
city: true,
listed_date: true,
price: true,
land_size: true,
property_type: true,
created_at: true,
updated_at: true,
realtor_id: true,
images: {
select: {
url: true,
},
},
},
where: filters,
...navigation,
});
return homes.map((home) => {
const fetchHome = {
...home,
...(home.images[0] && { image: home.images[0].url }),
};
delete fetchHome.images;
return new HomeResponseDto(fetchHome);
});
}
async getHome(id: number) {
const home = await this.PrismaService.home.findUnique({ where: { id } });
}
async createHome(
{
address,
numberOfBathrooms,
numberOfBedrooms,
city,
landSize,
price,
propertyType,
images,
}: CreateHomeParams,
realtor_id: number,
) {
const newHome = await this.PrismaService.home.create({
data: {
address,
city,
num_of_bath: numberOfBathrooms,
num_of_bed: numberOfBedrooms,
price,
property_type: propertyType,
realtor_id,
land_size: landSize,
},
});
const homeImages = images.map((image) => {
return { ...image, home_id: newHome.id };
});
await this.PrismaService.image.createMany({ data: homeImages });
return new HomeResponseDto(newHome);
}
async updateHomeById(id: number, data: UpdateHomeParams) {
const home = await this.PrismaService.home.findUnique({ where: { id } });
if (!home) throw new NotFoundException();
const updatedHome = await this.PrismaService.home.update({
where: { id },
data: {
address: data.address,
city: data.city,
price: data.price,
land_size: data.landSize,
num_of_bath: data.numberOfBathrooms,
num_of_bed: data.numberOfBedrooms,
property_type: data.propertyType,
},
});
return new HomeResponseDto(updatedHome);
}
async deleteHomeById(id: number) {
const home = await this.PrismaService.home.delete({ where: { id } });
return home;
}
async getRealtorByHomeId(id: number) {
const home = await this.PrismaService.home.findUnique({
where: { id },
select: {
realtor: {
select: {
id: true,
name: true,
email: true,
phone: true,
},
},
},
});
if (!home) throw new NotFoundException();
return home.realtor;
}
} |
---
title: जावा का उपयोग करके XMP में नामांकित मान जोड़ें
linktitle: जावा का उपयोग करके XMP में नामांकित मान जोड़ें
second_title: Aspose.Page जावा एपीआई
description: Aspose.Page का उपयोग करके जावा दस्तावेज़ हेरफेर में महारत हासिल करें! निर्बाध एकीकरण के लिए हमारी चरण-दर-चरण मार्गदर्शिका के साथ XMP मेटाडेटा में आसानी से नामित मान जोड़ें।
type: docs
weight: 12
url: /hi/java/xmp-metadata-manipulation/add-named-value/
---
## परिचय
जावा विकास के निरंतर विकसित होते परिदृश्य में, दस्तावेज़ की अखंडता बनाए रखने के लिए ईपीएस फ़ाइलों में मेटाडेटा को संभालना महत्वपूर्ण है। जावा के लिए Aspose.Page एक शक्तिशाली लाइब्रेरी है जो इस प्रक्रिया को सरल बनाती है। इस ट्यूटोरियल में, हम जावा का उपयोग करके एक्सएमपी मेटाडेटा में नामित मान जोड़ने के चरणों के बारे में विस्तार से जानेंगे, जिससे यह सुनिश्चित होगा कि आपके पास ईपीएस फ़ाइलों में हेरफेर करने के लिए एक मजबूत आधार है।
## आवश्यक शर्तें
इससे पहले कि हम ट्यूटोरियल में उतरें, सुनिश्चित करें कि आपके पास निम्नलिखित आवश्यक शर्तें हैं:
- जावा डेवलपमेंट किट (जेडीके): जावा के लिए Aspose.Page को एक कार्यशील जेडीके की आवश्यकता होती है। सुनिश्चित करें कि आपके पास नवीनतम संस्करण स्थापित है।
- जावा लाइब्रेरी के लिए Aspose.Page: जावा लाइब्रेरी के लिए Aspose.Page को डाउनलोड करें और अपने प्रोजेक्ट में शामिल करें। आप इसे यहां से प्राप्त कर सकते हैं[लिंक को डाउनलोड करें](https://releases.aspose.com/page/java/).
## पैकेज आयात करें
अपने जावा प्रोजेक्ट में आवश्यक पैकेज आयात करके शुरुआत करें। जावा कार्यात्मकताओं के लिए Aspose.Page का उपयोग करने के लिए ये पैकेज महत्वपूर्ण हैं। अपने कोड में निम्नलिखित शामिल करें:
```java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import com.aspose.eps.PsDocument;
import com.aspose.eps.xmp.XmpMetadata;
import com.aspose.eps.xmp.XmpValue;
import com.aspose.page.BaseExamplesTest;
```
अब, आइए जावा के लिए Aspose.Page का उपयोग करके XMP मेटाडेटा में नामित मान जोड़ने के लिए प्रक्रिया को विस्तृत चरणों में विभाजित करें।
## चरण 1: इनपुट ईपीएस फ़ाइल स्ट्रीम प्रारंभ करें
इनपुट ईपीएस फ़ाइल स्ट्रीम प्रारंभ करके प्रारंभ करें। यह चरण आपके जावा प्रोजेक्ट में ईपीएस दस्तावेज़ को लोड करने के लिए चरण निर्धारित करता है।
```java
// दस्तावेज़ निर्देशिका का पथ.
String dataDir = "Your Document Directory";
// इनपुट ईपीएस फ़ाइल स्ट्रीम प्रारंभ करें
FileInputStream psStream = new FileInputStream(dataDir + "xmp4.eps");
PsDocument document = new PsDocument(psStream);
FileInputStream psStream = new FileInputStream(dataDir + "xmp4.eps");
PsDocument document = new PsDocument(psStream);
```
## चरण 2: एक्सएमपी मेटाडेटा प्राप्त करें
ईपीएस फ़ाइल से मौजूदा एक्सएमपी मेटाडेटा पुनर्प्राप्त करें। यदि ईपीएस फ़ाइल में एक्सएमपी मेटाडेटा का अभाव है, तो पीएस मेटाडेटा टिप्पणियों से मूल्यों के साथ एक नया उत्पन्न किया जाएगा।
```java
XmpMetadata xmp = document.getXmpMetadata();
```
## चरण 3: नामांकित मान जोड़ें
XMP मेटाडेटा संरचना में एक नया नामित मान जोड़ें। इस उदाहरण में, हम "xmpTPg:MaxPageSize" संरचना में एक मान जोड़ रहे हैं।
```java
xmp.addNamedValue("xmpTPg:MaxPageSize", "stDim:newKey", new XmpValue("NewValue"));
```
## चरण 4: आउटपुट ईपीएस फ़ाइल स्ट्रीम प्रारंभ करें
संशोधित XMP मेटाडेटा के साथ दस्तावेज़ को सहेजने के लिए आउटपुट ईपीएस फ़ाइल स्ट्रीम तैयार करें।
```java
FileOutputStream outPsStream = new FileOutputStream(dataDir + "xmp4_changed.eps");
```
## चरण 5: दस्तावेज़ सहेजें
दस्तावेज़ को अद्यतन XMP मेटाडेटा के साथ सहेजें।
```java
try {
document.save(outPsStream);
} finally {
outPsStream.close();
}
```
## चरण 6: इनपुट ईपीएस स्ट्रीम बंद करें
अंत में, संसाधनों को मुक्त करने के लिए इनपुट ईपीएस स्ट्रीम को बंद करना सुनिश्चित करें।
```java
psStream.close();
```
इन चरणों का पालन करके, आप जावा के लिए Aspose.Page का उपयोग करके XMP मेटाडेटा में एक नामित मान सफलतापूर्वक जोड़ते हैं, जिससे आपकी EPS फ़ाइल हेरफेर क्षमताएं बढ़ती हैं।
## निष्कर्ष
इस ट्यूटोरियल में, हमने XMP मेटाडेटा में नामित मान जोड़ने के लिए आपके प्रोजेक्ट में जावा के लिए Aspose.Page को सहजता से एकीकृत करने के लिए आवश्यक चरणों का पता लगाया है। यह शक्तिशाली लाइब्रेरी जावा डेवलपर्स को सुचारू वर्कफ़्लो सुनिश्चित करते हुए ईपीएस फ़ाइलों को कुशलतापूर्वक संभालने में सक्षम बनाती है।
## पूछे जाने वाले प्रश्न
### क्या मैं अन्य जावा लाइब्रेरीज़ के साथ जावा के लिए Aspose.Page का उपयोग कर सकता हूँ?
हां, जावा के लिए Aspose.Page को अन्य जावा लाइब्रेरीज़ के साथ सहजता से काम करने के लिए डिज़ाइन किया गया है, जो आपके विकास वातावरण में लचीलापन प्रदान करता है।
### क्या जावा के लिए Aspose.Page का निःशुल्क परीक्षण उपलब्ध है?
हाँ, आप Java के लिए Aspose.Page का निःशुल्क परीक्षण प्राप्त कर सकते हैं[यहाँ](https://releases.aspose.com/).
### मैं जावा के लिए Aspose.Page के लिए अस्थायी लाइसेंस कैसे प्राप्त कर सकता हूं?
मिलने जाना[इस लिंक](https://purchase.aspose.com/temporary-license/) जावा के लिए Aspose.Page के लिए एक अस्थायी लाइसेंस प्राप्त करने के लिए।
### जावा के लिए Aspose.Page के लिए मुझे और अधिक ट्यूटोरियल और उदाहरण कहां मिल सकते हैं?
पता लगाएं[प्रलेखन](https://reference.aspose.com/page/java/)व्यापक ट्यूटोरियल और उदाहरणों के लिए।
### क्या जावा के लिए Aspose.Page बड़े पैमाने की परियोजनाओं के लिए उपयुक्त है?
बिल्कुल, जावा के लिए Aspose.Page को बड़े पैमाने की परियोजनाओं को कुशलतापूर्वक संभालने के लिए डिज़ाइन किया गया है, जो मजबूत दस्तावेज़ हेरफेर क्षमताएं प्रदान करता है। |
import React from 'react';
import PropTypes from 'prop-types';
import { useDefinedValueList } from 'hooks';
import { NotFound } from 'components';
import { Loader } from 'ui-kit';
function DefinedValueListProvider({ Component, options, ...props }) {
const { loading, error, values } = useDefinedValueList(options);
if (loading) {
return <Loader mt="xxl" mb="xxl" centered text="Loading" />;
}
if (!values) {
return <NotFound layout={false} />;
}
return <Component data={values} loading={loading} error={error} {...props} />;
}
DefinedValueListProvider.propTypes = {
Component: PropTypes.oneOfType([
PropTypes.node,
PropTypes.func,
PropTypes.object,
]),
options: PropTypes.object,
};
export default DefinedValueListProvider; |
<script setup>
import Footer from "@/components/Footer.vue";
import { useAccountStore } from "@/stores/account";
import { useRouter } from "vue-router";
import bootstrap from "bootstrap/dist/js/bootstrap";
const account = useAccountStore();
const router = useRouter();
function handleSubmit(event) {
event.preventDefault();
login();
}
function login() {
account.logIn();
const toast = new bootstrap.Toast("#toastSuccess");
toast.show();
setTimeout(() => {
window.location = '/';
}, 1250);
}
</script>
<template>
<div class="container-md mt-5">
<div class="row row-cols-1 row-cols-md-2">
<div class="col">
<div
class="d-none d-md-flex justify-content-center align-items-center h-100"
>
<img src="@/assets/images/beach.webp" alt="beach" class="img-fluid" />
</div>
</div>
<div class="col px-md-5">
<div class="text-center text-md-start">
<h1 class="h2 fw-semibold">Selamat Datang!</h1>
<h5>Silakan masuk untuk melanjutkan</h5>
</div>
<form @submit="handleSubmit" class="mt-5 mb-3">
<div class="mb-3">
<label for="email" class="form-label">Email</label>
<input
type="email"
class="form-control"
id="email"
placeholder="Masukkan email Anda"
required
/>
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input
type="password"
class="form-control"
id="password"
placeholder="Masukkan password Anda"
required
/>
</div>
<button type="submit" class="btn btn-primary w-100">Masuk</button>
</form>
<div class="mb-3 text-center">atau</div>
<button
@click="login"
class="btn btn-light d-flex flex-column flex-md-row justify-content-center align-items-center shadow w-100 mb-3"
>
<img
src="@/assets/images/google.png"
alt="google"
class="img-fluid mb-2 mb-md-0 me-md-2"
/>
Masuk Menggunakan Akun Google
</button>
<button
@click="login"
class="btn btn-light d-flex flex-column flex-md-row justify-content-center align-items-center shadow w-100"
>
<img
src="@/assets/images/facebook.png"
alt="facebook"
class="img-fluid mb-2 mb-md-0 me-md-2"
/>
Masuk Menggunakan Akun Facebook
</button>
</div>
</div>
</div>
<Footer />
<div class="toast-container position-fixed top-0 end-0 p-3">
<div
id="toastSuccess"
class="toast align-items-center text-bg-success border-0"
role="alert"
aria-live="assertive"
aria-atomic="true"
>
<div class="d-flex">
<div class="toast-body">Berhasil masuk</div>
<button
type="button"
class="btn-close btn-close-white me-2 m-auto"
data-bs-dismiss="toast"
aria-label="Close"
></button>
</div>
</div>
</div>
</template> |
import argparse
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(5927)
class KMeans():
def __init__(self, D, n_clusters):
self.n_clusters = n_clusters
self.cluster_centers = np.zeros((n_clusters, D))
def init_clusters(self, data):
### TODO
### Initialize cluster_centers using n_clusters points sampled from data
# D=self.cluster_centers.shape[1]
# self.cluster_centers=np.random.rand(self.n_clusters, D)
# self.memberships_one_hot=np.zeros((self.n_clusters,data.shape[0]),dtype=int)
# self.memberships_vec=np.zeros((data.shape[0],1),dtype=int)
# # print(self.memberships_one_hot.shape)
# for i in range(data.shape[0]):
# mem=np.argmin(np.linalg.norm(data[i]-self.cluster_centers,axis=1))
# self.memberships_vec[i]=mem
# # print(self.memberships_one_hot.shape)
# self.memberships_one_hot[mem][i]=1
# nums=np.random.uniform(0,data.shape[0],self.n_clusters)
t1=np.arange(data.shape[0])
np.random.shuffle(t1)
for i in range(self.n_clusters):
self.cluster_centers[i]=data[t1[i]]
# print(D)
### END TODO
def pred(self, x):
### TODO: Given a sample x, return id of closest cluster center
#edit begins
#assuming x is of shape (D,)
x.shape=(x.shape[0],)
return np.argmin(np.linalg.norm(x-self.cluster_centers,axis=1))
### END TODO
def train(self, data, max_iter=10000, epsilon=1e-4):
for it in range(max_iter):
### TODO
### Declare and initialize required variables
memberships_one_hot=np.zeros((self.n_clusters,data.shape[0]),dtype=int)
prev_cluster_centers=np.copy(self.cluster_centers)
### Update labels for each point
for i in range(data.shape[0]):
mem=np.argmin(np.linalg.norm(data[i]-self.cluster_centers,axis=1))
memberships_one_hot[mem][i]=1
### Update cluster centers
### Note: If some cluster is empty, do not update the cluster center
denom=np.sum(memberships_one_hot,axis=1)
for i in range(self.n_clusters):
if denom[i]!=0:
self.cluster_centers[i]=np.dot(data.T,memberships_one_hot[i])
self.cluster_centers[i]/=denom[i]
### Check for convergence
### Stop if distance between each of the old and new cluster centers is less than epsilon
temp=np.linalg.norm(self.cluster_centers-prev_cluster_centers,axis=1)
if np.max(temp)<epsilon:
break
# if np.linalg.norm(prev_cluster_centers-self.cluster_centers)<epsilon:
# break
### END TODO
# print(it)
return it
def replace_by_center(self, data):
out = np.zeros_like(data)
for i, x in enumerate(data):
out[i] = self.cluster_centers[self.pred(x)]
return out
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--image', default='1', choices=['1', '2', '3'])
parser.add_argument('--k', default=5, type=int)
args = parser.parse_args()
image = plt.imread(f'data/{args.image}.png')
x = image.reshape(-1, 3)
kmeans = KMeans(D=3, n_clusters=args.k)
kmeans.init_clusters(x)
kmeans.train(x)
out = kmeans.replace_by_center(x)
plt.imshow(out.reshape(image.shape))
plt.show() |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPoolPlayerProjectiles : MonoBehaviour
{
//Singleton
public static ObjectPoolPlayerProjectiles SharedInstance;
//Reference
[SerializeField] PlayerController _playerController;
//Event Channel
[SerializeField] GunTypeEventChannelSO _gunChangeVoidEventChannelSO;
//List of pooled objects
public List<GameObject> pooledObjects;
//Objects to pool
private GameObject _objectToPool;
private int _amountToPool;
void Awake()
{
if(SharedInstance == null)
{
SharedInstance = this;
}
}
void Start()
{
InitialPoolSetup();
_gunChangeVoidEventChannelSO.OnEventRaised += SetObjectAndAmount;
_gunChangeVoidEventChannelSO.OnEventRaised += SetupPool;
}
void OnDisable()
{
_gunChangeVoidEventChannelSO.OnEventRaised -= SetObjectAndAmount;
_gunChangeVoidEventChannelSO.OnEventRaised -= SetupPool;
}
private void InitialPoolSetup()
{
SetObjectAndAmount(_playerController.CurrentGunType);
SetupPool(_playerController.CurrentGunType);
}
void SetupPool(GunTypeEnum enumerator)
{
if(pooledObjects.Count > 0)
{
foreach(GameObject pooledObject in pooledObjects)
{
Destroy(pooledObject);
}
}
pooledObjects = new List<GameObject>();
GameObject tempPoolItem;
for (int i = 0; i < _amountToPool; i++)
{
tempPoolItem = Instantiate(_objectToPool);
tempPoolItem.SetActive(false);
tempPoolItem.transform.parent = this.transform;
pooledObjects.Add(tempPoolItem);
}
}
void SetObjectAndAmount(GunTypeEnum enumerator)
{
switch (enumerator)
{
case GunTypeEnum.singleShot:
_objectToPool = _playerController.SingleShotPrefab;
_amountToPool = 10;
break;
case GunTypeEnum.doubleShot:
_objectToPool = _playerController.DoubleShotPrefab;
_amountToPool = 10;
break;
case GunTypeEnum.tripleShot:
_objectToPool = _playerController.TripleShotPrefab;
_amountToPool = 10;
break;
case GunTypeEnum.quadShot:
_objectToPool = _playerController.QuadShotPrefab;
_amountToPool = 10;
break;
case GunTypeEnum.superTripleShot:
_objectToPool = _playerController.SuperTripleShotPrefab;
_amountToPool = 10;
break;
case GunTypeEnum.fireShot:
_objectToPool = _playerController.FireShotPrefab;
_amountToPool = 10;
break;
case GunTypeEnum.plasmaShot:
_objectToPool = _playerController.PlasmaShotPrefab;
_amountToPool = 10;
break;
case GunTypeEnum.laserShot:
_objectToPool = _playerController.LaserShotPrefab;
_amountToPool = 10;
break;
}
}
public GameObject GetPooledObject()
{
for(int i = 0; i < pooledObjects.Count; i++)
{
if (!pooledObjects[i].activeInHierarchy)
{
return pooledObjects[i];
}
}
return null;
}
} |
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.core import signing
from django.db import models
from utils.custom_manager import UserManager
class SystemUser(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=254, unique=True)
first_name = models.CharField(max_length=50, null=True, blank=True, default=None)
last_name = models.CharField(max_length=50, null=True, blank=True, default=None)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(null=True, blank=True, default=None)
objects = UserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = []
def get_signing_dumps(self):
return signing.dumps(self.pk)
def get_full_name(self):
return f'{self.first_name} {self.last_name}'
class Meta:
db_table = "system_user" |
import {Component, OnInit} from '@angular/core';
import {ModalController, NavParams} from '@ionic/angular';
import {NzMessageService} from 'ng-zorro-antd/message';
import {VoucherPrinter} from '../../../../@core/utils/voucher-printer';
import {CheckAuth} from '../../../../@core/utils/check-auth';
@Component({
selector: 'app-reprintview',
templateUrl: 'view.html',
styleUrls: ['view.scss'],
providers: [NzMessageService]
})
export class ReprintViewComponent implements OnInit {
params = this.navParams.data.params;
datas = [
{name: '销售交易小票', code: 'T00206', type: 'APPEND,SALE'},
{name: '会员支付凭证', code: 'T00205', type: 'MEMBER'},
{name: '卖品取货凭证', code: 'T00207', type: 'APPEND,SALE'},
{name: '退货交易小票', code: 'T00209', type: 'REJECT'},
{name: '会员开卡凭证', code: 'T00201', type: 'memCardCost,memCardNewRecharge'},
{name: '会员充值凭证', code: 'T00202', type: 'memCardRecharge,memCardSterilisation'},
{name: '会员销卡凭证', code: 'T00204', type: 'memCardReject'},
{name: '会员补卡凭证', code: 'T00210', type: 'memCardRepair'}
];
saleTypes = [];
selectSaleType = [];
memberType = [];
constructor(private modalController: ModalController,
private navParams: NavParams,
private message: NzMessageService,
private checkAuth: CheckAuth,
private voucherPrinter: VoucherPrinter) {
}
ngOnInit() {
this.params.payLabel = this.getPayModeNameLabel();
this.getVoucherType();
}
getPayModeNameLabel() {
const list = this.params.payModeList;
const type = this.params.billSaleType;
const arr = [];
// 判断是否为会员支付
let isMemberCard = false;
if (type === 'REJECT' || type === 'memCardSterilisation') {
list.forEach(it => {
if (it.payModeCode === 'MemberPoints') {
arr.push(it.payModeName + ':' + it.refundAmount + '分');
} else {
arr.push(it.payModeName + ':' + it.refundAmount + '元');
}
if (it.payModeCode === 'MemberCard' || it.payModeCode === 'MemberPoints') {
isMemberCard = true;
this.params.isMemberCardUid = it.uid;
}
});
} else {
list.forEach(it => {
if (it.payModeCode === 'MemberPoints') {
arr.push(it.payModeName + ':' + it.billPayAmount + '分');
} else {
arr.push(it.payModeName + ':' + it.billPayAmount + '元');
}
if (it.payModeCode === 'MemberCard' || it.payModeCode === 'MemberPoints') {
isMemberCard = true;
this.params.isMemberCardUid = it.uid;
}
});
}
this.params.isMemberCard = isMemberCard;
return arr.join(' ');
}
getVoucherType() {
this.datas.forEach(item => {
const arr = item.type.split(',');
let f = false;
if (this.params.billSaleType === 'SALE' || this.params.billSaleType === 'REJECT') {
if (this.params.isMemberCard) {
f = true;
}
}
if (arr.indexOf(this.params.billSaleType) !== -1 || (item.type === 'MEMBER' && f)) {
this.saleTypes.push(item);
}
});
}
askForReprint() {
const params = {
authFuctionCode: 'operRePrint',
uidAuthFuction: 'rePrint',
authFuctionName: '重打印',
authFuctionType: '4'
};
this.checkAuth.auth(params, null, (type) => {
this.reprint();
});
}
reprint() {
// todo:添加授权
if (this.selectSaleType.length === 0 && this.memberType.length === 0) {
this.message.warning('请选择重打印凭证');
return;
}
// 凭证除了会员支付凭证外
if (this.selectSaleType.length > 0) {
const params = {
typeCodeList: this.selectSaleType,
uidBill: this.params.uid,
uidComp: this.params.uidComp
};
this.invokePrint(params);
}
// 会员支付凭证
if (this.memberType.length > 0) {
const params = {
typeCodeList: this.memberType,
uidBill: this.params.uid,
uidComp: this.params.uidComp
};
this.invokePrint(params);
}
}
invokePrint(params) {
const methodName = '/printTempletService-api/templetPrint/printTemp';
this.voucherPrinter.print(params, methodName, (res) => {
this.message.remove();
if (res.status === '0') {
this.message.success(res.msg, {nzDuration: 2000});
} else {
this.message.error(res.msg, {nzDuration: 2000});
}
});
}
select(d, e) {
if (d.type === 'MEMBER') {
if (e.checked) {
this.memberType = [d.code];
} else {
this.memberType = [];
}
} else {
if (e.checked) {
this.selectSaleType.push(d.code);
} else {
const idx = this.selectSaleType.indexOf(d.code);
if (idx !== -1) {
this.selectSaleType.splice(idx, 1);
}
}
}
}
cancel() {
this.modalController.dismiss(null).then();
}
} |
---
title: "Set up TeamViewer"
description: "Teamviewer allows to remote-control your computer to solve technical issues. Learn how to install it."
keywords: "teamviewer, software, installation, remote"
weight: 4
#date: 2020-11-11T22:02:51+05:30
draft: false
aliases:
- /get/teamviewer
- /install/teamviewer
---
## What is Teamviewer
TeamViewer is a software application that facilitates remote access, desktop sharing, online meetings, and collaboration tools. With TeamViewer, users can connect to and control computers and devices remotely over the internet, making it valuable for technical support, troubleshooting, file sharing, and communication among users who work remotely.
This capability is especially significant when it comes to obtaining feedback on code or resolving technical issues, which are vital for enhancing your learning experience. When working remotely, you can leverage the power of **TeamViewer**. It empowers team members to *remotely control* your computer, enabling immediate assistance and collaboration to address your needs effectively.
## Installing Teamviewer
To install TeamViewer, go to the [TeamViewer homepage](https://www.teamviewer.com/en/download/windows/) and download the installer for your operating system.
We recommend you to install Teamviewer *permanently*. If you do not have administrator rights, it's fine to only select *run once*.
Please indicate you download Teamviewer for *private use*, unless your organization provides you with a site license.
{{% warning %}}
**Mac users need to change additional security settings.**
After installing TeamViewer, Mac users need to change a few security settings to grant access rights so that a team member may steer your mouse and type on your keyboard. Please [follow this guide](https://community.teamviewer.com/t5/Knowledge-Base/How-to-control-a-Mac-running-macOS-10-14-or-higher/ta-p/44699#toc-hId--1220346050).
{{% /warning %}}
## Starting a TeamViewer session
Open TeamViewer via the start menu, select **remote control** on the left side of your screen (it's the default), and share **your ID** and **your password** with your team member.

Also want to talk to your team member? Make sure you have a headset connected to your computer.
{{% warning %}}
**Remember to change your temporary password!**
Please change your temporary password as soon as the session has ended.
To do so,
- just hover over the password area with your mouse,
- click on the little blue icon appearing on the right of it, and
- select generate a new random password.
This will keep your computer safe!
{{% /warning %}} |
// @HEADER
// ***********************************************************************
//
// Moocho: Multi-functional Object-Oriented arCHitecture for Optimization
// Copyright (2003) Sandia Corporation
//
// Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
// license for use of this work by or on behalf of the U.S. Government.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact Roscoe A. Bartlett (rabartl@sandia.gov)
//
// ***********************************************************************
// @HEADER
#ifndef GENMATRIX_IN_FUNC_H
#define GENMATRIX_IN_FUNC_H
#include "DenseLinAlgPack_IOBasic.hpp"
namespace DenseLinAlgPack {
/* * @name DMatrix/DMatrixSlice input stream functions.
*
* These are functions that are used to read a DMatrix or DMatrixSlice object in from a
* formated input stream.
*
* The input format is diferent depending on the on whether the bit
* #LinAlgPackIO::ignore_dim_bit# is set.
* If #exta_flags & LinAlgPackIO::ignore_dim_bit != 0# then the input format is:
*
* Case 1\\
* #m n#\\
* #gm(1,1) gm(1,2) gm(1,3) ... gm(1,n)#\\
* #gm(2,1) gm(2,2) gm(2,3) ... gm(2,n)#\\
* # . . . .#\\
* #gm(m,1) gm(m,2) gm(m,3) ... gm(m,n)#\\
*
* If #exta_flags & LinAlgPackIO::ignore_dim_bit == 0# then the input format is:
*
* Case 2\\
* #gm(1,1) gm(1,2) gm(1,3) ... gm(1,n)#\\
* #gm(2,1) gm(2,2) gm(2,3) ... gm(2,n)#\\
* # . . . .#\\
* #gm(m,1) gm(m,2) gm(m,3) ... gm(m,n)#\\
*
* The numbers of the input must be seperated by white space (the line breaks are
* for looks only) and be valid C language numeric constants.
*
* In addition, comment lines may be inserted between rows of the input matrix.
* These comment lines take the form of Fortan comment lines in that they start on
* new lines (after a '\n' char) with a '*' char and end at the end of a line
* ('\n' terminated). After the elements for a row are read in the function
* #eat_comment_lines(is,'*');# is called.
*
* For example, the input format for the matrix {1.1 1.2; 2.1 2.2}
* with comments for case 1 is:
*
* #2 2#\\
* #* This is the first row#\\
* #1.1 1.2#\\
* #* This is the second row#\\
* #2.1 2.1#\\
*
* And for case 2 is:
*
* #* This is the first row#\\
* #1.1 1.2#\\
* #* This is the second row#\\
* #2.1 2.1#\\
*
* It is permisible for the dimension #m# and #n# in case 1 to be 0.
* In this case there will be no elements. So to input an empty matrix you would use:
*
* #0 0#\\
*
* If one of the dimenstions is zero but not the other then a #std::length_error#
* exception will be thrown.
* If any of the input operations fails then a LinAlgPackIO::InputException exception
* is thrown. In other words if #is.fail()# or #is.eof()# is true
* before all of the elements have been read in then the exception is thrown.
* Also if the stream becomes corrupted (#is.bad() == true#) then a #std::ios_base::failure#
* exception is thrown.
*/
// @{
/** \brief . */
/* * DMatrix input stream function.
*
* Inputs a DMatrix object from an input stream.
* If #exta_flags & LinAlgPackIO::ignore_dim_bit != 0# then #gm# is resized to #m# x #n#
* given in the file. If #exta_flags & LinAlgPackIO::ignore_dim_bit == 0#
* then the number of elements read in depends on the current dimension of #gm#.
*/
std::istream& input(std::istream& is, DMatrix* gm, LinAlgPackIO::fmtflags extra_flags);
/** \brief . */
/* * DMatrixSlice input stream function.
*
* Inputs a DMatrixSlice object from an input stream.
* If #exta_flags & LinAlgPackIO::ignore_dim_bit != 0# then the dimension (sized) of #gms#
* is compared to the #m# and #n# given in the file and if they are not equal
* then a #LinAlgPackIO::InputException# is thrown. If #gms# is unsized then it is resized
* to #m# x #n#. If #exta_flags & LinAlgPackIO::ignore_dim_bit == 0# then the number of
* elements read in depends on the current size of #gms#.
*/
std::istream& input(std::istream& is, DMatrixSlice* gms, LinAlgPackIO::fmtflags extra_flags);
// @}
} // end namespace DenseLinAlgPack
#endif // GENMATRIX_IN_FUNC_H |
package com.joeroble.android.travelwishlist
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
interface OnListItemClickedListener{
fun onListItemClicked(place:Place)
}
class PlaceRecyclerAdapter(private val places: List<Place>,
private val onListItemClickedListener: OnListItemClickedListener):
RecyclerView.Adapter<PlaceRecyclerAdapter.ViewHolder>() {
// manages one view - one list item - set the actual data in the view
// nested classes - this is one
// inner classes
inner class ViewHolder(private val view: View): RecyclerView.ViewHolder(view){
fun bind(place: Place){
val placeNameTextView: TextView = view.findViewById(R.id.place_name)
placeNameTextView.text = place.name
val dateCreatedOnTextView: TextView = view.findViewById(R.id.date_place_added)
val createdOnText = view.context.getString(R.string.created_on, place.formattedDate())
dateCreatedOnTextView.text = createdOnText
val mapIcon: ImageView = view.findViewById(R.id.map_icon)
mapIcon.setOnClickListener{
onListItemClickedListener.onListItemClicked(place)
}
}
}
// called by the recycler view to create as many view holders that are needed
// to display the list on screen
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.place_list_item, parent, false)
return ViewHolder(view)
}
// called by the recycler view to set the data for one list item by position
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val place = places[position]
holder.bind(place)
}
// what's the total number of items in the list?
override fun getItemCount(): Int {
return places.size
}
} |
<?php
declare(strict_types=1);
namespace App\Controller\Author;
use App\Model\Author\Entity\Author;
use App\Model\Author\UseCase\Delete\AuthorDeleteCommand;
use App\Model\Author\UseCase\Delete\AuthorDeleteHandler;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\Routing\Attribute\Route;
#[AsController]
final class DeleteController
{
#[Route('/author/{id}/delete', name: 'author_delete', methods: [Request::METHOD_POST])]
public function __invoke(Author $author, AuthorDeleteHandler $handler): JsonResponse
{
$command = new AuthorDeleteCommand($author);
try {
$handler->handle($command);
} catch (\Exception $e) {
return new JsonResponse(['error' => $e->getMessage()], Response::HTTP_BAD_REQUEST);
}
return new JsonResponse(['success' => true]);
}
} |
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { HomeComponent } from './components/home/home.component';
import { HeaderComponent } from './components/header/header.component';
import { FooterComponent } from './components/footer/footer.component';
import { HttpClientModule} from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { ConteudoComponent } from './components/conteudo/conteudo.component';
import { FormularioComponent } from './components/formulario/formulario.component';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
HeaderComponent,
FooterComponent,
ConteudoComponent,
FormularioComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
NgbModule,
HttpClientModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { } |
import React, { useState, useEffect } from "react";
import { db } from "../../firebase/firebase";
import SkeletonComp from "../skeleton";
import Heading from "../heading";
import Card from "../card";
const NewProducts = () => {
const [products, setProducts] = useState([]);
useEffect(() => {
const docRef = db.collection("products");
const query = docRef.where("info", "==", "new");
query.get().then((snapshot) => {
const data = snapshot.docs.map((doc) => doc.data());
setProducts(data);
});
}, []);
return (
<section className="py-5 sectionContainer">
<Heading
head="New Arrivals"
para="Summer Collection New Modern Design"
/>
<div className="row">
{products.length === 0 ? (
<>
<div className="col-md-3">
<SkeletonComp />
</div>
<div className="col-md-3">
<SkeletonComp />
</div>
<div className="col-md-3">
<SkeletonComp />
</div>
<div className="col-md-3">
<SkeletonComp />
</div>
</>
) : (
products.map((product) => {
return (
<div className="col-md-3" key={product.id}>
<Card
img={product.image}
category={product.category}
title={product.name}
price={product.price}
id={product.id}
/>
</div>
);
})
)}
</div>
</section>
)
}
export default NewProducts |
import { useEffect, useState } from 'react';
import { useMutation, useQuery } from 'react-query';
import { useNavigate } from 'react-router-dom';
import { IRoom } from '../containers/LobbyPage/components/GameList';
import { IInfo } from '../containers/LobbyPage/components/Info';
import { IUser } from '../containers/LobbyPage/LobbyPage';
import { axiosPrivate } from '../util/axios';
import useLogout from './useLogout';
const nothing = {
nickname: '이름없음',
win: 0,
lose: 0,
kill: 0,
death: 0,
};
export const useLobbyData = () => {
const [order, setOrder] = useState(false);
const [sort, setSort] = useState('id');
const [list, setList] = useState<IRoom[]>([]);
const [userList, setUserList] = useState<IUser[]>([]);
const [myInfo, setMyInfo] = useState<IInfo>(nothing);
const navigate = useNavigate();
const { logOut, deleteUserList } = useLogout();
const exitScreen = (e: BeforeUnloadEvent) => {
e.preventDefault();
// 창을 나갈 때 userList 삭제 + 로그아웃
logOut.mutate();
deleteUserList.mutate();
e.returnValue = '';
};
// 내 정보
useQuery('myInfo', () => axiosPrivate.get('/user'), {
onSuccess: (res) => setMyInfo(res.data),
});
// 게임룸 리스트
const { refetch: gameRoomRefetch } = useQuery(
'gameRoomList',
() =>
axiosPrivate.get(`/room?sort=${sort}&order=${!order ? 'desc' : 'asc'}`), // password는 order파라미터 없어야함
{
onSuccess: (res) => setList(res.data),
}
);
// 접속자 리스트
useQuery('lobbyUserList', () => axiosPrivate.get('/room/lobby/users'), {
onSuccess: (res) => setUserList(res.data),
refetchInterval: 1000,
// 최종 배포 시에는 적용!! 백엔드쪽에서 에러코드를 볼 수 없다고 함..
});
// 로그인(토큰) 체크
const loginCheck = useMutation(() => axiosPrivate.post('/auth/validate'), {
onSuccess: (res) => {
!res && navigate('/');
enterUserList.mutate();
},
onError: (err) => console.log(err),
});
// 접속자 리스트에 자신 추가
const enterUserList = useMutation(
() => axiosPrivate.post('/room/lobby/users'),
{ onSuccess: () => console.log('접속자 리스트에 추가 완료') }
);
useEffect(() => {
(async () => {
window.addEventListener('unload', exitScreen);
loginCheck.mutate();
return () => {
window.removeEventListener('unload', exitScreen);
};
})();
}, []);
return {
sort,
order,
setOrder,
setSort,
list,
userList,
myInfo,
loginCheck,
enterUserList,
gameRoomRefetch,
};
}; |
import { DepartmentEntity } from 'src/department/infrastructure/sql/entities/department.entity';
import {
Column,
CreateDateColumn,
Entity,
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
@Entity({ name: 'city' })
export class CityEntity {
@PrimaryGeneratedColumn()
id: number;
@Column({ type: 'boolean', default: true })
active: boolean;
@Column({ type: 'varchar', length: 100 })
name: string;
@ManyToOne(() => DepartmentEntity, { nullable: false, eager: true })
@JoinColumn({ name: 'departmentId' })
department: DepartmentEntity;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
} |
import { faCircleXmark, faMagnifyingGlass, faSpinner } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { useState, useEffect, useRef } from 'react';
import * as searchService from '~/Services/searchServices';
import HeadlessTippy from '@tippyjs/react/headless';
import AccountItem from '~/components/AccountItem/AccountItem';
import classNames from 'classnames/bind';
import styles from './Search.module.scss';
import { Wrapper as PopperWrapper } from '~/components/Popper';
import { useDebounce } from '~/hooks';
const cx = classNames.bind(styles);
function Search() {
const [SearchValue, SearchValueResult] = useState('');
const inputRef = useRef();
const debounce = useDebounce(SearchValue, 500);
const [searchResult, setSearchResult] = useState([]);
const [showResult, setShowResult] = useState(true);
const [loading, setLoading] = useState(false);
useEffect(() => {
if (!debounce.trim()) {
setSearchResult([]);
return;
}
const fetchApi = async () => {
setLoading(true);
const result = await searchService.search(debounce);
setSearchResult(result);
setLoading(false);
};
fetchApi();
}, [debounce]);
const handleClear = () => {
SearchValueResult('');
inputRef.current.focus();
setSearchResult([]);
};
const HandleHidenResult = () => {
setShowResult(false);
};
const handleOnchange = (e) => {
const seachValue = e.target.value;
if (!seachValue.startsWith(' ')) SearchValueResult(seachValue);
};
return (
<div>
<HeadlessTippy
onClickOutside={HandleHidenResult}
interactive
visible={showResult && searchResult.length > 0}
render={(attrs) => (
<div className={cx('search-result')} tabIndex="-1" {...attrs}>
<PopperWrapper>
<h4 className={cx('search-title')}>Accounts</h4>
{searchResult.map((result) => (
<AccountItem key={result.id} data={result} />
))}
</PopperWrapper>
</div>
)}
>
<div className={cx('search')}>
<input
ref={inputRef}
value={SearchValue}
placeholder="Search accounts and videos"
spellCheck={false}
onChange={handleOnchange}
onFocus={() => {
setShowResult(true);
}}
/>
{!!SearchValue && !loading && (
<button className={cx('clear')} onClick={handleClear}>
<FontAwesomeIcon icon={faCircleXmark} />
</button>
)}
{loading && <FontAwesomeIcon className={cx('loading')} icon={faSpinner} />}
<button
className={cx('search-btn')}
onMouseDown={(e) => {
e.preventDefault();
}}
>
<FontAwesomeIcon icon={faMagnifyingGlass} />
</button>
</div>
</HeadlessTippy>
</div>
);
}
export default Search; |
'use client';
import { useContext, useEffect } from 'react';
import {
Checkbox,
FormControl,
FormErrorMessage,
HStack,
IconButton,
Input,
useColorMode,
useToast,
} from '@chakra-ui/react';
import { yupResolver } from '@hookform/resolvers/yup';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { FaSave, FaTimes, FaEdit, FaTrash } from 'react-icons/fa';
import { TodoContext } from '@/contexts/todo';
import { todoSchema } from '@/utils/schema';
import type { InferType } from 'yup';
import type { Todo } from '@/types/todo';
type TodoCardProps = {
mode: 'read' | 'create' | 'update';
data?: Todo;
isEditable?: boolean;
onUpdate?: () => void;
onDelete?: () => void;
onClose: () => void;
};
const TodoCard = ({ mode, data, isEditable, onUpdate, onDelete, onClose }: TodoCardProps) => {
const { colorMode } = useColorMode();
const { createTodo, updateTodo, isLoading } = useContext(TodoContext);
const {
register,
reset,
handleSubmit,
formState: { errors, isDirty, isSubmitting, isValid },
} = useForm<InferType<typeof todoSchema>>({
mode: 'onChange',
defaultValues: {
title: data?.title || '',
},
resolver: yupResolver(todoSchema),
});
const router = useRouter();
const toast = useToast();
const onSubmitTodo = async (payload: InferType<typeof todoSchema>) => {
try {
switch (mode) {
case 'create': {
await createTodo({ title: payload.title });
toast({
title: 'Todo has been created!',
description: 'You have successfully created a new todo.',
status: 'success',
duration: 2000,
});
break;
}
case 'update': {
if (!data) break;
await updateTodo(data._id, { title: payload.title });
toast({
title: 'Todo has been updated!',
description: 'You have successfully updated a todo.',
status: 'success',
duration: 2000,
});
}
}
onClose();
} catch (err) {
if (err instanceof Error) {
toast({
title: `Failed to ${mode === 'create' ? 'create' : 'update'} todo!`,
description: err.message,
status: 'error',
duration: 2000,
});
if (err.message.toLowerCase().includes('expired')) {
router.replace('/auth/sign-in');
}
}
}
};
const onSwitchTodo = () => {
if (!data) return;
const response: Promise<void | Error> = new Promise((resolve, reject) => {
updateTodo(data._id, { isCompleted: !data.isCompleted })
.then(() => resolve())
.catch((err) => reject(err));
});
toast.promise(response, {
loading: {
title: 'Switching todo...',
},
success: {
title: 'Todo has been switched!',
description: `You have successfully switched a todo to ${
data.isCompleted ? 'uncompleted' : 'completed'
}.`,
duration: 2000,
},
error: {
title: 'Failed to switch todo!',
description: response.catch((err) => err.message),
duration: 2000,
},
});
response.catch((err) => {
if (err.message.toLowerCase().includes('expired')) {
router.replace('/auth/sign-in');
}
});
};
useEffect(() => {
if (!data) return;
reset({ title: data.title });
}, [data, reset]);
return mode === 'read' && !!data ? (
<HStack
justifyContent="space-between"
borderWidth={1}
borderRadius={6}
gap={4}
backgroundColor={colorMode === 'light' ? 'white' : 'gray.800'}>
<Checkbox
textDecoration={data.isCompleted ? 'line-through' : 'none'}
wordBreak="break-word"
width="full"
height="full"
paddingX={4}
paddingY={6}
isChecked={data.isCompleted}
isDisabled={isLoading || isSubmitting}
onChange={onSwitchTodo}>
{data.title}
</Checkbox>
{isEditable && (
<HStack padding={4}>
<IconButton
aria-label="Edit todo"
colorScheme="yellow"
icon={<FaEdit />}
isDisabled={isLoading || isSubmitting}
onClick={onUpdate}
/>
<IconButton
aria-label="Delete todo"
colorScheme="red"
icon={<FaTrash />}
isDisabled={isLoading || isSubmitting}
onClick={onDelete}
/>
</HStack>
)}
</HStack>
) : (
<HStack
as="form"
justifyContent="space-between"
padding={4}
borderWidth={1}
borderRadius={6}
onSubmit={handleSubmit(onSubmitTodo)}>
<FormControl isInvalid={!!errors.title} isRequired>
<Input
type="text"
placeholder="Title"
isDisabled={isLoading || isSubmitting}
{...register('title')}
/>
{errors.title && <FormErrorMessage>{errors.title.message}</FormErrorMessage>}
</FormControl>
<HStack>
<IconButton
type="submit"
aria-label="Save todo"
colorScheme="green"
icon={<FaSave />}
isLoading={isLoading || isSubmitting}
isDisabled={!isDirty || !isValid}
/>
<IconButton
aria-label="Cancel todo"
icon={<FaTimes />}
onClick={onClose}
isDisabled={isLoading || isSubmitting}
/>
</HStack>
</HStack>
);
};
export default TodoCard; |
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\DB;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable,HasRoles;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'username',
'password',
];
public function purchases()
{
return $this->hasMany(Purchase::class);
}
public function offorders()
{
return $this->hasMany(OffOrder::class);
}
public function userRoles()
{
return $this->hasMany(UserRole::class);
}
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
public static function getpermissionGroups()
{
$permission_groups = DB::table('permissions')
->select('group_name as name')
->groupBy('group_name')
->get();
return $permission_groups;
}
public static function getpermissionsByGroupName($group_name)
{
$permissions = DB::table('permissions')
->select('name', 'id')
->where('group_name', $group_name)
->get();
return $permissions;
}
public static function roleHasPermissions($role, $permissions)
{
$hasPermission = true;
foreach ($permissions as $permission) {
if (!$role->hasPermissionTo($permission->name)) {
$hasPermission = false;
return $hasPermission;
}
}
return $hasPermission;
}
} |
@extends('layouts.app2')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-12">
<div class="card">
<div class="card-header" style="">Cadastrar Usuário</div>
<div class="card-body">
@if(session('success'))
<div class="alert alert-success" role="alert">
{{ session('success') }}
</div>
@endif
@if(session('error'))
<div class="alert alert-danger" role="alert">
{{ session('error') }}
</div>
@endif
<form method="POST" action="{{ route('usuarios.store') }}">
@csrf
<div class="mb-3">
<label for="nome" class="form-label">Nome</label>
<input id="nome" type="text" class="form-control" name="nome" required>
</div>
<div class="mb-3">
<label for="email" class="form-label">Email</label>
<input id="email" type="email" class="form-control" name="email" required>
</div>
<div class="mb-3">
<label for="password" class="form-label">Senha</label>
<input id="password" type="password" class="form-control" name="password" required>
</div>
<div class="mb-3">
<label for="permissions" class="form-label">Permissões</label>
@foreach($roles as $role)
<div class="form-check">
<input class="form-check-input" type="radio" value="{{$role->id}}" name="roles[]" id="{{$role->name}}">
<label class="form-check-label" for="{{$role->name}}">{{$role->name}}</label>
</div>
@endforeach
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary w-100">Cadastrar</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection |
// backend/services/advertisement_service.go
package services
import (
"fmt"
"time"
"github.com/golang-jwt/jwt"
"github.com/shuttlersit/service-desk/backend/models"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)
type LoginInfo struct {
Email string `json:"email"`
Password string `json:"password"`
}
// AuthServiceInterface provides methods for managing auth.
type AuthServiceInterface interface {
Registration(user *models.Users) (*models.Users, string, error)
Login(login *LoginInfo) (string, error)
}
// DefaultAuthService is the default implementation of AuthService
type DefaultAuthService struct {
DB *gorm.DB
AuthDBModel *models.AuthDBModel
UserDBModel *models.UserDBModel
// Add any dependencies or data needed for the service
}
// NewDefaultAuthService creates a new DefaultAuthService.
func NewDefaultAuthService(authDBModel *models.AuthDBModel) *DefaultAuthService {
return &DefaultAuthService{
AuthDBModel: authDBModel,
}
}
// User registration
func (a *DefaultAuthService) Registration(user *models.Users) (*models.Users, string, error) {
// Hash the user's password before storing it in the database
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(user.Credentials.Password), bcrypt.DefaultCost)
if err != nil {
return nil, "", fmt.Errorf("failed to hash password")
}
user.Credentials.Password = string(hashedPassword)
erro := a.UserDBModel.CreateUser(user)
if erro != nil {
return nil, "", fmt.Errorf("failed to create users")
}
er := a.AuthDBModel.CreateUserCredentials(&user.Credentials)
if er != nil {
return nil, "", fmt.Errorf("failed to create users credentials")
}
// Generate a JWT token for successful login
token, err := generateJWTToken(user.ID)
if err != nil {
return nil, "", err
}
return user, token, nil
}
// User login
func (a *DefaultAuthService) Login(login *LoginInfo) (string, error) {
loginInfo := login
var user models.Users
if err := a.DB.Where("email = ?", loginInfo.Email).First(&user).Error; err != nil {
return "", err
}
if err := bcrypt.CompareHashAndPassword([]byte(user.Credentials.Password), []byte(loginInfo.Password)); err != nil {
return "", fmt.Errorf("invalid email or password")
}
// Generate a JWT token for successful login
token, err := generateJWTToken(user.ID)
if err != nil {
return "", err
}
return token, nil
}
// Define a function to generate JWT token
func generateJWTToken(userID uint) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"userID": userID,
"exp": time.Now().Add(time.Hour * 24).Unix(), // Token expires in 24 hours
})
return token.SignedString([]byte("your-secret-key"))
} |
<div>{{CSSRef}}</div>
<p>La propriété <strong><code>list-style</code></strong> est une <a href="/fr/docs/Web/CSS/Propriétés_raccourcies">propriété raccourcie</a> qui permet de définir {{cssxref("list-style-type")}}, {{cssxref("list-style-image")}} et {{cssxref("list-style-position")}}.</p>
<div>{{EmbedInteractiveExample("pages/css/list-style.html")}}</div>
<p class="hidden">Le code source de cet exemple interactif est disponible dans un dépôt GitHub. Si vous souhaitez contribuez à ces exemples, n'hésitez pas à cloner <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> et à envoyer une <em>pull request</em> !</p>
<div class="note">
<p><strong>Note :</strong> Cette propriété s'applique aux éléments d'une liste (c'est-à-dire aux éléments pour lesquels {{cssxref("display")}}<code>: list-item</code><code>;</code>}}). Par défaut, cela inclut les éléments {{HTMLElement("li")}}. Cette propriété peut être héritée par les éléments et si on veut donc gérer une liste de façon uniforme, on pourra appliquer la propriété à l'élément parent (qui correspond en général à {{HTMLElement("ol")}} ou à {{HTMLElement("ul")}}).</p>
</div>
<h2 id="Syntaxe">Syntaxe</h2>
<pre class="brush:css no-line-numbers">/* Type */
list-style: square;
/* Image */
list-style: url('../img/etoile.png');
/* Position */
list-style: inside;
/* type | position */
list-style: georgian inside;
/* type | image | position */
list-style: lower-roman url('../img/etoile.png') outside;
list-style: none;
/* Valeurs globales */
list-style: inherit;
list-style: initial;
list-style: unset;
</pre>
<h3 id="Valeurs">Valeurs</h3>
<p>Cette propriété raccourcie peut prendre un, deux ou trois mots-clés, dans n'importe quel ordre. Si {{cssxref("list-style-type")}} et {{cssxref("list-style-image")}} sont tous les deux définis, <code>list-style-type</code> sera utilisé si l'image est indisponible.</p>
<dl>
<dt><code><'list-style-type'></code></dt>
<dd>Voir {{cssxref("list-style-type")}}</dd>
<dt><code><'list-style-image'></code></dt>
<dd>Voir {{cssxref("list-style-image")}}</dd>
<dt><code><'list-style-position'></code></dt>
<dd>Voir {{cssxref("list-style-position")}}</dd>
<dt><code>none</code></dt>
<dd>Aucun style n'est utilisé.</dd>
</dl>
<h3 id="Syntaxe_formelle">Syntaxe formelle</h3>
<pre class="syntaxbox">{{csssyntax}}</pre>
<h2 id="Exemples">Exemples</h2>
<h3 id="CSS">CSS</h3>
<pre class="brush: css">.un {
list-style: circle;
}
.deux {
list-style: square inside;
}</pre>
<h3 id="HTML">HTML</h3>
<pre class="brush: html">Liste 1
<ul class="un">
<li>Élément 1</li>
<li>Élément 2</li>
<li>Élément 3</li>
</ul>
Liste 2
<ul class="deux">
<li>Élément A</li>
<li>Élément B</li>
<li>Élément C</li>
</ul>
</pre>
<h3 id="Résultat">Résultat</h3>
<p>{{EmbedLiveSample('Exemples','auto', 220)}}</p>
<h2 id="Accessibilité">Accessibilité</h2>
<p>Safari ne reconnait pas (incorrectement) les listes non ordonnées lorsque <code>list-style:none</code> leur est appliqué et ne les ajoute pas dans l'arbre d'accessibilité (utilisé par les lecteurs d'écrans). Pour pallier ce problème, on peut ajouter un <a href="https://fr.wikipedia.org/wiki/Espace_sans_chasse">espace sans chasse</a> comme <a href="/fr/docs/Web/CSS/content">pseudo-contenu</a> avant chaque élément de liste afin que la liste soit correctement annoncée.</p>
<pre class="brush: css">ul {
list-style: none;
}
ul li::before {
content: "\200B";
}
</pre>
<ul>
<li><a href="https://unfetteredthoughts.net/2017/09/26/voiceover-and-list-style-type-none/">VoiceOver et <code>list-style-type: none</code> – Unfettered Thoughts (en anglais)</a></li>
<li><a href="/fr/docs/Web/Accessibility/Understanding_WCAG/Perceivable#Guideline_1.3_%E2%80%94_Create_content_that_can_be_presented_in_different_ways">Comprendre les règles WCAG 1.3</a></li>
<li><em><a href="https://www.w3.org/TR/UNDERSTANDING-WCAG20/content-structure-separation-programmatic.html" rel="noopener">Understanding Success Criterion 1.3.1, W3C Understanding WCAG 2.0 </a></em><a href="https://www.w3.org/TR/UNDERSTANDING-WCAG20/content-structure-separation-programmatic.html" rel="noopener">(en anglais)</a></li>
</ul>
<h2 id="Spécifications">Spécifications</h2>
<table class="standard-table">
<thead>
<tr>
<th scope="col">Spécification</th>
<th scope="col">État</th>
<th scope="col">Commentaires</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{SpecName('CSS3 Lists', '#list-style-property', 'list-style')}}</td>
<td>{{Spec2('CSS3 Lists')}}</td>
<td>Aucun changement.</td>
</tr>
<tr>
<td>{{SpecName('CSS2.1', 'generate.html#propdef-list-style', 'list-style')}}</td>
<td>{{Spec2('CSS2.1')}}</td>
<td>Définition initiale.</td>
</tr>
</tbody>
</table>
<p>{{cssinfo}}</p>
<h2 id="Compatibilité_des_navigateurs">Compatibilité des navigateurs</h2>
<div class="hidden">Ce tableau de compatibilité a été généré à partir de données structurées. Si vous souhaitez contribuer à ces données, n'hésitez pas à envoyer une <em>pull request</em> sur <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>.</div>
<p>{{Compat("css.properties.list-style")}}</p>
<h2 id="Voir_aussi">Voir aussi</h2>
<ul>
<li>{{cssxref("list-style-type")}}</li>
<li>{{cssxref("list-style-image")}}</li>
<li>{{cssxref("list-style-position")}}</li>
</ul> |
import express from "express";
import { uploadFileToMulter } from "../middleware/multer";
import { validateUser } from "../middleware/validateUser";
import { uploadFileToS3 } from "../utils/s3Buket";
import { prisma } from "../server";
const router = express.Router();
router.post(
"/upload",
validateUser,
uploadFileToMulter.fields([{ name: "book" }, { name: "cover" }]),
async (req, res) => {
const { bookName, author } = req.body;
if (!req.decoded?.userId)
return {
status: "fail",
message: "user not logged in",
};
try {
const book = (req.files as any).book[0];
const cover = (req.files as any).cover[0];
const bookKey = `uploaded-pdfs/${Date.now().toString()}-${
book.originalname
}`;
const coverKey = `uploaded-images/${Date.now().toString()}-${
cover.originalname
}`;
await uploadFileToS3(bookKey, book.buffer);
await uploadFileToS3(coverKey, cover.buffer);
const bookURL = `https://s3.tebi.io/luminex/${encodeURIComponent(
bookKey
)}`;
const coverURL = `https://s3.tebi.io/luminex/${encodeURIComponent(
coverKey
)}`;
await prisma.book.create({
data: {
author,
name: bookName,
bookURL,
coverURL,
user: {
connect: {
id: req.decoded.userId,
},
},
},
});
return res.json({
status: "ok",
message: "uploaded successful",
});
} catch (e) {
console.log(e);
return res.json({
status: "fail",
message: "upload failed",
});
}
}
);
router.get("/getBooksByUser", validateUser, async (req, res) => {
const uid = req.decoded?.userId;
try {
const books = await prisma.book.findMany({
where: {
userId: uid,
},
});
res.json({
status: "ok",
message: "books found",
books,
});
} catch (e) {
res.json({
status: "fail",
message: "failed to retrieve book",
});
}
});
router.get("/getBook", validateUser, async (req, res) => {
const payload = req.query as { bookId: string };
try {
const book = await prisma.book.findUnique({
where: {
id: payload.bookId,
},
});
if (book) {
return res.json({
status: "ok",
message: "book url retried",
book,
});
} else {
return res.json({
status: "fail",
message: "book not found",
});
}
} catch {
return res.json({
status: "fail",
message: "failed to retrieve book url",
});
}
});
router.post("/updateProgress", validateUser, async (req, res) => {
const payload = req.body as {
bookId: string;
location: string;
progress: number;
};
try {
await prisma.book.update({
where: {
id: payload.bookId,
},
data: {
location: payload.location,
progress: payload.progress,
},
});
res.json({
status: "ok",
message: "progress updated",
});
} catch (e) {
res.json({
status: "fail",
message: "failed to update progress",
});
}
});
router.post("/addFavourite", validateUser, async (req, res) => {
const payload = req.body as { bookId: string };
const decodedToken = req.decoded;
try {
await prisma.book.update({
where: {
id: payload.bookId,
userId: decodedToken?.userId,
},
data: {
isFavourited: true,
},
});
res.json({
status: "ok",
message: "book added to favourite",
});
} catch {
res.json({
status: "fail",
message: "failed to find book",
});
}
});
router.post("/removeFavourite", validateUser, async (req, res) => {
const payload = req.body as { bookId: string };
const decodedToken = req.decoded;
try {
await prisma.book.update({
where: {
id: payload.bookId,
userId: decodedToken?.userId,
},
data: {
isFavourited: false,
},
});
res.json({
status: "ok",
message: "book removed from favourite",
});
} catch {
res.json({
status: "fail",
message: "failed to find book",
});
}
});
router.get("/getFavourites", validateUser, async (req, res) => {
try {
const books = await prisma.book.findMany({
where: {
userId: req.decoded?.userId,
isFavourited: true,
},
});
res.json({
status: "ok",
message: "books found",
books,
});
} catch {
res.json({
status: "fail",
message: "failed to find favourite books",
});
}
});
router.get("/search", validateUser, async (req, res) => {
const { searchTerm } = req.query as { searchTerm: string };
try {
const books = await prisma.book.findMany({
where: {
userId: req.decoded?.userId,
name: {
contains: searchTerm,
mode: "insensitive",
},
},
});
res.json({
status: "ok",
message: "books found",
books,
});
} catch (e) {
res.json({
status: "fail",
message: "failed to retrieve books",
});
}
});
export default router; |
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Lector;
use App\Traits\MessageTrait;
use Illuminate\Support\Facades\DB;
class LectorController extends Controller
{
use MessageTrait;
private $lector;
public function __construct(Lector $lector){
$this->lector = $lector;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$lectors = $this->lector::with('borrowed_books')->get();
return $this->successResponse($lectors);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
try{
DB::beginTransaction();
$this->lector::create($request->all());
DB::commit();
return $this->showMessage("Lector Creado Correctamente");
}catch(\Exception $e){
return $this->errorResponse("Error al crear lector", 500);
DB::rollback();
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$lector = $this->lector::with('borrowed_books')
->where('id', $id)->first();
try{
return $this->successResponse($lector);
}catch(\Exception $e){
return $this->errorResponse("Lector no existe");
}
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
} |
import React, { useState } from "react";
import Skils from "../utils/Skils";
import Container from "react-bootstrap/Container";
import Nav from "react-bootstrap/Nav";
import Navbar from "react-bootstrap/Navbar";
import NavDropdown from "react-bootstrap/NavDropdown";
import Carousel from "react-bootstrap/Carousel";
import { Button, Typography } from "@mui/material";
import Typical from "react-typical";
import "./Home.css";
const Home = () => {
const allCategories = Skils.skils.map(
(skillCategory) => skillCategory.category
);
const [mySlider, setmySlider] = useState("Programming");
const category = Skils.skils.find(
(category) => category.category === "Programming"
);
const [myiIthemList, setmyIthemList] = useState(category);
const onCat = (e) => {
setmySlider(e);
const category = Skils.skils.find((category) => category.category === e);
setmyIthemList(category);
};
return (
<div>
<div className="home-container">
<h1>About Me</h1>
<div className="animated_text">
<h6>
I am a{" "}
<Typical
loop={Infinity}
wrapper="b"
steps={[
"full stack developer",
3000,
"React/React native developer",
3000,
"Bachelor of Computer Science",
3000,
"Freelancer",
3000,
]}
></Typical>
</h6>
</div>
<div className="about me">
{Skils.aboutme.map((item) => {
return (
<div>
{" "}
<h6>{item.title}</h6>
<p>{item.info}</p>{" "}
</div>
);
})}
</div>
<div>
<div>
<Navbar expand="lg" className="navbar">
<Container>
<p>Technical Skills:</p>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="mx-auto">
{allCategories.map((item) => {
return (
<h6>
<Nav.Link
onClick={() => {
onCat(item);
}}
>
{item}
</Nav.Link>
</h6>
);
})}
</Nav>
</Navbar.Collapse>
</Container>
</Navbar>
</div>
<div className="carousel-container">
<Carousel data-bs-theme="dark" className="my-carousel">
{myiIthemList.items.map((item) => {
return (
<Carousel.Item>
<img
src={item.image}
style={{
height: "300px",
width: "300px",
display: "block",
margin: "0 auto",
}}
></img>
<Carousel.Caption>
<Typography className="item_name">{item.name}</Typography>
</Carousel.Caption>
</Carousel.Item>
);
})}
</Carousel>
</div>
</div>
</div>
</div>
);
};
export default Home; |
%%
%% Copyright (C) 2010-2014 by krasnop@bellsouth.net (Alexei Krasnopolski)
%%
%% 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.
%%
@author Alexei Krasnopolski <krasnop@bellsouth.net> [http://krasnopolski.org]
@copyright 2010-2014 Alexei Krasnopolski
@doc
<h3>Introduction</h3>
The client allows to connect to MySQL server and execute SQL query. It provides connection pooling
mechanizm for concurrency efficience.
The client is written on Erlang and very closely follows MySQL Connector/C interface.
It can be called MySQL Connector/Erlang but has some restrictions in functionality (recent version has no SSL support).
Design is based on protocol description from [http://mysql.timesoft.cc/doc/internals/en/index.html].
The client was tested on MySQL server version 5.1.51, 5.5.9 and 5.6.2 on Windows/Linux/MacOSX boxes.
<h3>Architecture</h3>
MySQL client is an OTP application. Top level component is datasource supervisor (<code>datasource_sup</code> Erlang module)
that is monitoring a child datasource processes (datasource is a connection pool in other words). Each datasource
(or connection pool) is managing of a set of connection processes (generic services). Connection pool keeps
reusable connection processes that can be retrived and returned by client software. Structure of the application
is shown on figure below. The client is using external Erlang Resource Pool project [https://sourceforge.net/projects/erlpool] for
connection pool implementation with customized connection_factory.erl.
<p><img src="mySQL.png" /></p>
<ul>
<li><b>mysql client</b> - OTP application that combines application and supervisor behaviour.
The supervisor is managing a numbers of datasource processes. It implements a functionality to create
new or delete existed datasources.
</li>
<li><b>datasource module</b> - contains connection pool process (gen_server) that is managing a few connection processes.
The <code>datasource</code> module can manipulate underlying resource (connection) pool.
The pool helps to reuse opened connection objects. Connection pool is automatically created when datasource is initialized.
</li>
<li><b>connection</b> - generic server process that incapsulates all functionality concerned connection to DB, quering,
prepared statement operations and so on.</li>
</ul>
<h3>Getting started</h3>
To start with the client you have to complete at least first two steps below:
<ol>
<li>Install MySQL [http://dev.mysql.com/downloads].</li>
<li>Install Erlang [http://www.erlang.org/download.html].</li>
<li>Install Eclipse IDE [http://www.eclipse.org/] with Erlide plugin [http://erlide.sourceforge.net/]. This is optional.
But I am doing developing of the software using these wonderful tools and highly recommend ones.</li>
<li>Install OpenSSL framework (If your workstation does not have it yet) [http://www.openssl.org/] because Erlang <code>crypto</code>
is depended on the library. Commonly OpenSSL is already installed in Linux hosts.</li>
</ol>
Next step is running the examples. Suppose you install MySQL server as 'localhost' that opened 3306 port for listening a TCP/IP connections from clients.
You have to adjust root user account: set 'root'@'localhost' with 'root' password and create account 'user'@'localhost'/'user'.
I will not teach you how using Erlang, just remind you:
<ul>
<li>You have to use Rebar to build project.
Issue command <code>rebar clean get-deps compile</code>.</li>
<li>Start Erlang shell.</li>
<li>Set up current directory with eshell command <code>c:cd(".../ebin")</code>.</li>
<li>Add path for dependency <code>code:add_path(".../deps/rsrc_pool/ebin")</code>.</li>
</ul>
<pre>
1> <span>c:cd("/home/alexei/eclipse-workspace/erl.mysql.client/ebin").</span>
/home/alexei/eclipse-workspace/erl.mysql.client/ebin
ok
2> <span>code:add_path("/home/alexei/eclipse-workspace/erl.mysql.client/deps/rsrc_pool/ebin").</span>
true
</pre>
Now we can issue commands for MySQL server. First at all we need to start application
'mysql_client' that represents describing client.
<pre>
2> <span>my:start_client().</span>
ok
</pre>
Next step is a creating of datasource process with associated connection pool. First lets
create description of our datasource.
Load records definitions to console environment to make our next steps more clear:
<pre>
3> <span>rr(".././include/client_records.hrl").</span>
[client_options,connection,datasource,eof_packet,
error_packet,field_metadata,metadata,mysql_decimal,
mysql_error,mysql_time,ok_packet,ok_stmt_packet,packet,
rs_header,server_info,server_status]
</pre>
Assign record #datasource{} to DS_def value:
<pre>
4> <span>DS_def = #datasource{</span>
4> <span>host = "localhost",</span>
4> <span>port = 3306,</span>
4> <span>database = "",</span>
4> <span>user = "root",</span>
4> <span>password = "root"}.</span>
#datasource{name = undefined,host = "localhost",port = 3306,
database = [],user = "root",password = "root",
flags = #client_options{charset_number = 33,
long_password = 1,found_rows = 0,
long_flag = 1,connect_with_db = 1,
no_schema = 0,compress = 0,odbc = 0,
local_files = 0,ignore_space = 0,
protocol_41 = 1,interactive = 1,ssl = 0,
ignore_sigpipe = 0,transactions = 1,
reserved = 0,secure_connection = 1,
multi_statements = 1,multi_results = 1,
trans_isolation_level = default}}
</pre>
And finally create new datasource object:
<pre>
5> <span>my:new_datasource(data_source, DS_def).</span>
`{ok,<0.46.0>}'
</pre>
We have now datasource named 'data_source' that we can use for connecting to DB.
Lets establish a connection to the server:
<pre>
6> <span>Cntn = datasource:get_connection(data_source).</span>
`<0.48.0>'
</pre>
Command above retrives connection from pool and if connection pool has no idle connection then connection
factory creates new one. We can check obtained connection:
<pre>
7> <span>connection:connection_record(Cntn).</span>
`#connection{
socket = #Port<0.668>,
ds_def =
#datasource{
name = data_source,host = "localhost",port = 3306,
database = [],user = "root",password = "root",
flags =
#client_options{
charset_number = 33,long_password = 1,found_rows = 0,
long_flag = 1,connect_with_db = 1,no_schema = 0,
compress = 0,odbc = 0,local_files = 0,ignore_space = 0,
protocol_41 = 1,interactive = 1,ssl = 0,
ignore_sigpipe = 0,transactions = 1,reserved = 0,
secure_connection = 1,...}},
server_info =
#server_info{
protocol_version = 10,server_version = "5.1.60",
thread_Id = 97,
server_capabilities =
#client_options{
charset_number = 8,long_password = 1,found_rows = 1,
long_flag = 1,connect_with_db = 1,no_schema = 1,
compress = 1,odbc = 1,local_files = 1,ignore_space = 1,
protocol_41 = 1,interactive = 1,ssl = 0,
ignore_sigpipe = 1,transactions = 1,reserved = 0,
secure_connection = 1,multi_statements = 0,
multi_results = 0,...},
server_status =
#server_status{
inTransaction = false,autocommit = true,
moreResultExists = false,queryNoGoodIndexUsed = false,
queryNoIndexUsed = false,cursorExists = false,
lastRowSent = false,dbDropped = false,
noBackSlashEscapes = false,metadataChanged = false,
queryWasSlow = false,psOutParams = false},
scramble_buff = <<"Kw8M[aVj2ZO[^G&&+F]$">>}}'
</pre>
Please, see client_records.hrl file to interpret content of returned 'connection' record.
You can use value of Cntn for further work. To create database named 'testDB' issue a command:
<pre>
8> <span>connection:execute_query(Cntn, "CREATE DATABASE IF NOT EXISTS testDB").</span>
`{#metadata{
field_count = 0,param_count = 0,
server_status =
#server_status{
inTransaction = false,autocommit = true,
moreResultExists = false,queryNoGoodIndexUsed = false,
queryNoIndexUsed = false,cursorExists = false,
lastRowSent = false,dbDropped = false,
noBackSlashEscapes = false,metadataChanged = false,
queryWasSlow = false,psOutParams = false},
field_metadata = [],param_metadata = []},
[#ok_packet{
affected_rows = 1,insert_id = 0,
server_status =
#server_status{
inTransaction = false,autocommit = true,
moreResultExists = false,queryNoGoodIndexUsed = false,
queryNoIndexUsed = false,cursorExists = false,
lastRowSent = false,dbDropped = false,
noBackSlashEscapes = false,metadataChanged = false,
queryWasSlow = false,psOutParams = false},
warning_count = 0,message = []}]}'
</pre>
Now your MySQL server has 'testDB' database. Next step is a table creating.
<pre>
9> <span>connection:execute_query(Cntn,</span>
9> <span>"CREATE TABLE testDB.sample_table (id bigint(20) NOT NULL AUTO_INCREMENT,</span>
9> <span> name varchar(45) DEFAULT NULL, age int(10) DEFAULT 21,</span>
9> <span> longtext_col longtext, PRIMARY KEY (id))</span>
9> <span> ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8").</span>
`{#metadata{
field_count = 0,param_count = 0,
server_status =
#server_status{
inTransaction = false,autocommit = true,
moreResultExists = false,queryNoGoodIndexUsed = false,
queryNoIndexUsed = false,cursorExists = false,
lastRowSent = false,dbDropped = false,
noBackSlashEscapes = false,metadataChanged = false,
queryWasSlow = false,psOutParams = false},
field_metadata = [],param_metadata = []},
[#ok_packet{
affected_rows = 0,insert_id = 0,
server_status =
#server_status{
inTransaction = false,autocommit = true,
moreResultExists = false,queryNoGoodIndexUsed = false,
queryNoIndexUsed = false,cursorExists = false,
lastRowSent = false,dbDropped = false,
noBackSlashEscapes = false,metadataChanged = false,
queryWasSlow = false,psOutParams = false},
warning_count = 0,message = []}]}'
</pre>
You can insert now some data rows into table 'sample_table':
<pre>
10> <span>connection:execute_query(Cntn,</span>
10> <span>"INSERT INTO testDB.sample_table(name) VALUES ('Alex'), ('John')").</span>
`{#metadata{
field_count = 0,param_count = 0,
server_status =
#server_status{
inTransaction = false,autocommit = true,
moreResultExists = false,queryNoGoodIndexUsed = false,
queryNoIndexUsed = false,cursorExists = false,
lastRowSent = false,dbDropped = false,
noBackSlashEscapes = false,metadataChanged = false,
queryWasSlow = false,psOutParams = false},
field_metadata = [],param_metadata = []},
[#ok_packet{
affected_rows = 2,insert_id = 1,
server_status =
#server_status{
inTransaction = false,autocommit = true,
moreResultExists = false,queryNoGoodIndexUsed = false,
queryNoIndexUsed = false,cursorExists = false,
lastRowSent = false,dbDropped = false,
noBackSlashEscapes = false,metadataChanged = false,
queryWasSlow = false,psOutParams = false},
warning_count = 0,
message = "&Records: 2 Duplicates: 0 Warnings: 0"}]}'
</pre>
And finally you can select a rows from the table:
<pre>
11> <span>connection:execute_query(Cntn, "SELECT * FROM testDB.sample_table").</span>
`{#metadata{
field_count = 4,param_count = 0,
server_status =
#server_status{
inTransaction = false,autocommit = true,
moreResultExists = false,queryNoGoodIndexUsed = false,
queryNoIndexUsed = true,cursorExists = false,
lastRowSent = false,dbDropped = false,
noBackSlashEscapes = false,metadataChanged = false,
queryWasSlow = false,psOutParams = false},
field_metadata =
[#field_metadata{
catalog = "def",schema = "testDB",table = "sample_table",
origtable = "sample_table",name = "id",origname = "id",
charsetnr = 63,length = 20,type = 8,
flags = <<3,66>>,
scale = 0,default = []},
#field_metadata{
catalog = "def",schema = "testDB",table = "sample_table",
origtable = "sample_table",name = "name",origname = "name",
charsetnr = 33,length = 135,type = 253,
flags = <<0,0>>,
scale = 0,default = []},
#field_metadata{
catalog = "def",schema = "testDB",table = "sample_table",
origtable = "sample_table",name = "age",origname = "age",
charsetnr = 63,length = 10,type = 3,
flags = <<0,0>>,
scale = 0,default = []},
#field_metadata{
catalog = "def",schema = "testDB",table = "sample_table",
origtable = "sample_table",name = "longtext_col",
origname = "longtext_col",charsetnr = 33,
length = 4294967295,type = 252,
flags = <<16,0>>,
scale = 0,default = []}],
param_metadata = []},
[[1,"Alex",21,null],[2,"John",21,null]]}'
</pre>
<h3>How interpret response</h3>
Allmost all functions of <code>connection</code>code> module returns a tuple that we can describe as mysql_response type:
<pre>
mysql_response = {metadata(), result()},
Where
metadata() = #metadata{
field_count = integer(),
server_status = list(#server_status{}),
field_metadata = list(#field_metadata{})
},
result() = [] | [E#ok_packet{}] | [E#ok_stmt_packet{}] | list(rowdata()),
rowdata() = list(field_value()),
field_value() = integer() | float() | string() | binary() | #mysql_time{} | #mysql_decimal{}
</pre>
First element of the tuple is metadata record (see client_records.hrl), that keeps an information about fields involved in the SQL query.
Second element is a list of result rows of query or command.
Some commands return empty list of result or list of the single element (ok_packet or ok_stmt_packet).
Other commands return list of rows of rowdata() type each of these in own turn is a list of field values (field_value() type).
Lets investigate the result of last query more carefully. After some formating it will look like:
<pre>
`{
#metadata{
field_count = 4,
param_count = 0,
server_status = #server_status{
inTransaction = false,
autocommit = true,
moreResultExists = false,
queryNoGoodIndexUsed = false,
queryNoIndexUsed = true,
cursorExists = false,
lastRowSent = false,
dbDropped = false,
noBackSlashEscapes = false,
metadataChanged = false,
queryWasSlow = false,
psOutParams = false
},
field_metadata = [
#field_metadata{
catalog = "def",
schema = "testDB",
table = "sample_table",
origtable = "sample_table",
name = "id",
origname = "id",
charsetnr = 63,
length = 20,
type = 8,
flags = <<3,66>>,
scale = 0,
default = []
},
#field_metadata{
catalog = "def",
schema = "testDB",
table = "sample_table",
origtable = "sample_table",
name = "name",
origname = "name",
charsetnr = 33,
length = 135,
type = 253,
flags = <<0,0>>,
scale = 0,
default = []
},
#field_metadata{
catalog = "def",
schema = "testDB",
table = "sample_table",
origtable = "sample_table",
name = "age",
origname = "age",
charsetnr = 63,
length = 10,
type = 3,
flags = <<0,0>>,
scale = 0,
default = []
},
#field_metadata{
catalog = "def",
schema = "testDB",
table = "sample_table",
origtable = "sample_table",
name = "longtext_col",
origname = "longtext_col",
charsetnr = 33,
length = 4294967295,
type = 252,
flags = <<16,0>>,
scale = 0,
default = []
}
],
param_metadata = []
},
[
[1,"Alex",21,null],
[2,"John",21,null]
]
}'
</pre>
We can see that the query returns two rows each of these contains four fields: values of 'id' = 1,2;
values of 'name' field = "Alex","John"; values of 'age' = 21,21 and 'longtext_col' = null, null. Also the query
returns a whole description of each fields in records named 'field_metadata'.
How extract the value we need? It is easy. Suppose we need value of second column 'name' from second row of the query result
<pre>
12> <span>{_, Rows} = connection:execute_query(Cntn, "SELECT * FROM testDB.sample_table").</span>
`{#metadata{
field_count = 4,param_count = 0,
server_status =
#server_status{
inTransaction = false,autocommit = true,
moreResultExists = false,queryNoGoodIndexUsed = false,
queryNoIndexUsed = true,cursorExists = false,
lastRowSent = false,dbDropped = false,
noBackSlashEscapes = false,metadataChanged = false,
queryWasSlow = false,psOutParams = false},
field_metadata =
[#field_metadata{
catalog = "def",schema = "testDB",table = "sample_table",
origtable = "sample_table",name = "id",origname = "id",
charsetnr = 63,length = 20,type = 8,
flags = <<3,66>>,
scale = 0,default = []},
#field_metadata{
catalog = "def",schema = "testDB",table = "sample_table",
origtable = "sample_table",name = "name",origname = "name",
charsetnr = 33,length = 135,type = 253,
flags = <<0,0>>,
scale = 0,default = []},
#field_metadata{
catalog = "def",schema = "testDB",table = "sample_table",
origtable = "sample_table",name = "age",origname = "age",
charsetnr = 63,length = 10,type = 3,
flags = <<0,0>>,
scale = 0,default = []},
#field_metadata{
catalog = "def",schema = "testDB",table = "sample_table",
origtable = "sample_table",name = "longtext_col",
origname = "longtext_col",charsetnr = 33,
length = 4294967295,type = 252,
flags = <<16,0>>,
scale = 0,default = []}],
param_metadata = []},
[[1,"Alex",21,null],[2,"John",21,null]]}'
13> <span>Rows.</span>
[[1,"Alex",21,null],[2,"John",21,null]]
14> <span>[_,{rs_row_data,Row}] = Rows.</span>
[[1,"Alex",21,null],[2,"John",21,null]]
15> <span>Row.</span>
[2,"John",21,null]
16> <span>[_,Name] = Row.</span>
[2,"John",21,null]
17> <span>Name.</span>
"John"
</pre>
Note that MySQL server returns result set fields as a strings and the client is trying to convert
them to proprietary Erlang types. Possible convertions are shown in Table 1 below.
<h3>Cursor (client side)</h3>
<p>Cursor is utility to help manipulate of result set data retrieved from DB server. Cursor is implemented as a process
(you can think about the cursor as an object).
This is more convenient way to retrieve data from response. We can create cursor object from response data on client side
and use this cursor to navigate through set of records and fields.
<pre>
18> <span>Response = connection:execute_query(Cntn, "SELECT * FROM testDB.sample_table").</span>
{#metadata{
... output is skipped ...},
[[1,"Alex",21,null],[2,"John",21,null]]}
19> <span>Cursor = cursor:new(Response).</span>
`<0.77.0>'
</pre>
To navigate to next row we have to call cursor:next function or set desired index of row.
<pre>
20> <span>cursor:next(Cursor).</span> %% step forward
true
21> <span>cursor:set(Cursor, 1).</span> %% set on cursor beginning
true
</pre>
Now we can get value of a field:
<pre>
22> <span>Name1 = cursor:get(Cursor, "name").</span>
"Alex"
23> <span>Age1 = cursor:get(Cursor, "age").</span>
21
</pre>
Move to next row and get a field by index in current row:
<pre>
25> <span>cursor:next(Cursor).</span>
true
26> <span>Name2 = cursor:get(Cursor, 2).</span>
"John"
</pre>
Other operations under cursor are:
<dl>
<dt>reset</dt><dd>set cursor pointer to a beginnig of the cursor.</dd>
<dt>next</dt><dd>move pointer to the next position.</dd>
<dt>set</dt><dd>set pointer to given position.</dd>
<dt>skip</dt><dd>skip a few position ahead.</dd>
<dt>back</dt><dd>move pointer to the previous position.</dd>
</dl>
Let us investigate a 'foreach' function.
The function returns list of values for given field from all rows in cursor:
<pre>
19> <span>cursor:foreach(Cursor, "name").</span>
["Alex","John"]
</pre>
Cursor object owns to process created it. Other processes cannot access the cursor so cursor cannot be used concurrently.
<h3>Prepared statements</h3>
MySQL client protocol allows to define prepared statements: SQL query with placeholder (?) for parameters
and using this prepared statement for querying of the server farther.
The simple example of a prepared statement is here:
<pre>
19><span>H = connection:get_prepared_statement_handle(Cntn, "SELECT * FROM testDB.sample_table WHERE id = ?").</span>
1
</pre>
Function get_prepared_statement_handle returns handler of the prepared statement we will use in next operations.
Now let's try to execute this prepared statement.
<pre>
20><span>{_,[R|_]} = connection:execute_statement(Cntn, H, [8], [1]).</span>
`{#metadata{
field_count = 4,param_count = 0,
server_status =
#server_status{
inTransaction = false,autocommit = true,
moreResultExists = false,queryNoGoodIndexUsed = false,
queryNoIndexUsed = false,cursorExists = false,
lastRowSent = false,dbDropped = false,
noBackSlashEscapes = false,metadataChanged = false,
queryWasSlow = false,psOutParams = false},
field_metadata =
[#field_metadata{
catalog = "def",schema = "testDB",table = "sample_table",
origtable = "sample_table",name = "id",origname = "id",
charsetnr = 63,length = 20,type = 8,
flags = <<3,66>>,
scale = 0,default = []},
#field_metadata{
catalog = "def",schema = "testDB",table = "sample_table",
origtable = "sample_table",name = "name",origname = "name",
charsetnr = 33,length = 135,type = 253,
flags = <<0,0>>,
scale = 0,default = []},
#field_metadata{
catalog = "def",schema = "testDB",table = "sample_table",
origtable = "sample_table",name = "age",origname = "age",
charsetnr = 63,length = 10,type = 3,
flags = <<0,0>>,
scale = 0,default = []},
#field_metadata{
catalog = "def",schema = "testDB",table = "sample_table",
origtable = "sample_table",name = "longtext_col",
origname = "longtext_col",charsetnr = 33,
length = 4294967295,type = 252,
flags = <<16,0>>,
scale = 0,default = []}],
param_metadata = []},
[[1,"Alex",21,null]]}'
21><span>R.</span>
[1,"Alex",21,null]
</pre>
We pass to connection:execute_statement/4 parameters:
<dl>
<dt>Cntn -</dt><dd>connection tuple,</dd>
<dt>H -</dt><dd>statement handle</dd>
<dt>[8] -</dt><dd>list of parameter types (in our case 8 - LONGLONG MySQL type)</dd>
<dt>[1] -</dt><dd>list of parameter values (in our case 1 - id of desired table record)</dd>
</dl>
Result is first record of the table with "Alex" in 'name' field. MySQL server formats a rows of a result set
in different ways when responses on query or executes prepared statement.
To make some order in types of data the Erlang client is doing some convertions of field values.
Table below describes a correspondence between types of field defined by DDL statement and types returned by
server in response for query and requered to set for prepared statement parameters.
<table border="1" >
<thead style="color: blue; font-weight: bold;">Table 1. SQL and Erlang types</thead>
<tr style="background-color: #00eeee;">
<th rowspan="3">DDL type of fields</th>
<th colspan="4">MySQL client type</th>
<th rowspan="3">Range limits</th>
</tr>
<tr style="background-color: #88eeaa;">
<th colspan="2">Result set of SQL query</th>
<th colspan="2">Prepared statement parameters</th>
</tr>
<tr style="background-color: #00eeee;">
<th>SQL type</th><th>Erlang type</th>
<th>SQL type</th><th>Erlang type</th>
</tr>
<tr>
<td>NULL (any type)</td><td>@nbsp;</td><td>null::atom()</td><td>MYSQL_TYPE_NULL (NULL)</td>
<td>null::atom()</td><td>@nbsp;</td>
</tr>
<tr>
<td>decimal</td><td>MYSQL_TYPE_NEWDECIMAL (NEWDECIMAL)</td><td>#mysql_decimal{}</td>
<td>NEWDECIMAL,<br/> DECIMAL</td><td>#mysql_decimal{}</td><td>@nbsp;</td>
</tr>
<tr>
<td>tinyint</td><td>MYSQL_TYPE_TINY (TINY)</td><td>integer()</td><td>TINY</td><td>integer()</td><td>@nbsp;</td>
</tr>
<tr>
<td>smallint</td><td>MYSQL_TYPE_SHORT (SHORT)</td><td>integer()</td><td>TINY, SHORT</td><td>integer()</td><td>@nbsp;</td>
</tr>
<tr>
<td>mediumint</td><td>MYSQL_TYPE_INT24 (INT24)</td><td>integer()</td><td>TINY, SHORT, INT24</td><td>integer()</td><td>@nbsp;</td>
</tr>
<tr>
<td>int</td><td>MYSQL_TYPE_LONG (LONG)</td><td>integer()</td><td>TINY, SHORT, INT24, LONG</td><td>integer()</td><td>@nbsp;</td>
</tr>
<tr>
<td>bigint</td><td>MYSQL_TYPE_LONGLONG (LONGLONG)</td><td>integer()</td><td>TINY, SHORT, INT24, LONG, LONGLONG</td><td>integer()</td><td>@nbsp;</td>
</tr>
<tr>
<td>float</td><td>MYSQL_TYPE_FLOAT (FLOAT)</td><td>float()</td><td>FLOAT</td><td>float()</td><td>@nbsp;</td>
</tr>
<tr>
<td>double</td><td>MYSQL_TYPE_DOUBLE (DOUBLE)</td><td>float()</td><td>DOUBLE</td><td>float()</td><td>@nbsp;</td>
</tr>
<tr>
<td>timestamp</td><td>MYSQL_TYPE_TIMESTAMP (TIMESTAMP)</td><td>#mysql_time{}</td><td>TIMESTAMP</td><td>#mysql_time{}</td><td>@nbsp;</td>
</tr>
<tr>
<td>date</td><td>MYSQL_TYPE_DATE (DATE)</td><td>#mysql_time{}</td><td>DATE</td><td>#mysql_time{}</td><td>@nbsp;</td>
</tr>
<tr>
<td>time</td><td>MYSQL_TYPE_TIME (TIME)</td><td>#mysql_time{}</td><td>TIME</td><td>#mysql_time{}</td><td>@nbsp;</td>
</tr>
<tr>
<td>datetime</td><td>MYSQL_TYPE_DATETIME (DATETIME)</td><td>#mysql_time{}</td><td>DATETIME</td><td>#mysql_time{}</td><td>@nbsp;</td>
</tr>
<tr>
<td>year</td><td>MYSQL_TYPE_YEAR (YEAR)</td><td>integer()</td><td>YEAR</td><td>integer()</td><td>@nbsp;</td>
</tr>
<tr>
<td>char</td><td>MYSQL_TYPE_STRING (STRING)</td><td>string()</td><td>STRING</td><td>string()</td>
<td>@nbsp;</td>
</tr>
<tr>
<td>varchar</td><td>MYSQL_TYPE_VAR_STRING (VAR_STRING)</td><td>string()</td>
<td>VARCHAR, VAR_STRING</td><td>string()</td><td>@nbsp;</td>
</tr>
<tr>
<td>binary</td><td>MYSQL_TYPE_STRING(STRING) [binary]</td><td>binary()</td><td>STRING</td><td>binary()</td>
<td>@nbsp;</td>
</tr>
<tr>
<td>varbinary</td><td>MYSQL_TYPE_VAR_STRING(VAR_STRING) [binary]</td><td>binary()</td>
<td>VARCHAR, VAR_STRING</td><td>binary()</td><td>@nbsp;</td>
</tr>
<tr>
<td>enum</td><td>MYSQL_TYPE_STRING(STRING) [enum]</td><td>atom()</td><td>MYSQL_TYPE_ENUM (ENUM)</td><td>atom()</td>
<td>@nbsp;</td>
</tr>
<tr>
<td>set</td><td>MYSQL_TYPE_STRING(STRING) [set]</td><td>list(atom())</td><td>MYSQL_TYPE_SET (SET)</td><td>list(atom())</td>
<td>@nbsp;</td>
</tr>
<tr>
<td>bit</td><td>MYSQL_TYPE_BIT(BIT) [unsigned]</td><td>binary()</td><td>BIT</td><td>binary()</td><td>@nbsp;</td>
</tr>
<tr>
<td>tinyblob</td>
<td rowspan="4">MYSQL_TYPE_BLOB (BLOB)<br/>[binary]</td><td>binary()</td><td>TINY_BLOB</td><td>binary()</td><td>@nbsp;</td>
</tr>
<tr>
<td>blob</td>
<td>binary()</td><td>MYSQL_TYPE_BLOB (BLOB)</td><td>binary()</td><td>@nbsp;</td>
</tr>
<tr>
<td>mediumblob</td>
<td>binary()</td><td>MEDIUM_BLOB</td><td>binary()</td><td>@nbsp;</td>
</tr>
<tr>
<td>longblob</td>
<td>binary()</td><td>LONG_BLOB</td><td>binary()</td><td>@nbsp;</td>
</tr>
<tr>
<td>tinytext</td>
<td rowspan="4">MYSQL_TYPE_BLOB (BLOB)</td><td>string()</td><td>TINY_BLOB</td><td>string()</td><td>@nbsp;</td>
</tr>
<tr>
<td>text</td>
<td>string()</td><td>MYSQL_TYPE_BLOB (BLOB)</td><td>string()</td><td>@nbsp;</td>
</tr>
<tr>
<td>mediumtext</td>
<td>string()</td><td>MYSQL_TYPE_MEDIUM_BLOB (MEDIUM_BLOB)</td><td>string()</td><td>@nbsp;</td>
</tr>
<tr>
<td>longtext</td>
<td>string()</td><td>MYSQL_TYPE_LONG_BLOB (LONG_BLOB)</td><td>string()</td><td>@nbsp;</td>
</tr>
<tr>
<td>?</td>
<td>MYSQL_TYPE_NEWDATE (NEWDATE)</td><td>@nbsp;</td><td>@nbsp;</td>
<td>@nbsp;</td>
<td>@nbsp;</td>
</tr>
</table>
<h3>Prepared statement cursor and result fetching</h3>
After a statement is prepared we can execute it under two modes. First kind of execution
is default and immediately returns a result set of the prepared statement. Second one
does not return a result set but create a cursor on the server side. To retrieve a data from
this cursor we can use fetch_statement command like this:
<pre>
22><span>`H1 = connection:get_prepared_statement_handle(Cntn, "SELECT * FROM testDB.sample_table WHERE id < ?").'</span>
2
23><span>LONGLONG = 8.</span>
8
24><span>CURSOR_TYPE_READ_ONLY = 1.</span>
1
25><span>{M,_} = connection:execute_statement(Cntn, H1, [LONGLONG], [1], CURSOR_TYPE_READ_ONLY, true).</span>
`{#metadata{
field_count = 4,param_count = 0,server_status = undefined,
field_metadata =
[#field_metadata{
catalog = "def",schema = "testDB",table = "sample_table",
origtable = "sample_table",name = "id",origname = "id",
charsetnr = 63,length = 20,type = 8,
flags = <<1,0>>,
scale = 0,default = []},
#field_metadata{
catalog = "def",schema = "testDB",table = "sample_table",
origtable = "sample_table",name = "name",origname = "name",
charsetnr = 33,length = 135,type = 253,
flags = <<0,0>>,
scale = 0,default = []},
#field_metadata{
catalog = "def",schema = "testDB",table = "sample_table",
origtable = "sample_table",name = "age",origname = "age",
charsetnr = 63,length = 10,type = 3,
flags = <<0,0>>,
scale = 0,default = []},
#field_metadata{
catalog = "def",schema = "testDB",table = "sample_table",
origtable = "sample_table",name = "longtext_col",
origname = "longtext_col",charsetnr = 33,
length = 4294967295,type = 252,
flags = <<16,0>>,
scale = 0,default = []}],
param_metadata = []},
[]}'
26><span>{_,R1} = connection:fetch_statement(Cntn, H1, M, 2).</span>
`{#metadata{
field_count = 4,param_count = 0,
server_status =
#server_status{
inTransaction = false,autocommit = true,
moreResultExists = false,queryNoGoodIndexUsed = false,
queryNoIndexUsed = false,cursorExists = true,
lastRowSent = false,dbDropped = false,
noBackSlashEscapes = false,metadataChanged = false,
queryWasSlow = false,psOutParams = false},
field_metadata =
[#field_metadata{
catalog = "def",schema = "testDB",table = "sample_table",
origtable = "sample_table",name = "id",origname = "id",
charsetnr = 63,length = 20,type = 8,
flags = <<1,0>>,
scale = 0,default = []},
#field_metadata{
catalog = "def",schema = "testDB",table = "sample_table",
origtable = "sample_table",name = "name",origname = "name",
charsetnr = 33,length = 135,type = 253,
flags = <<0,0>>,
scale = 0,default = []},
#field_metadata{
catalog = "def",schema = "testDB",table = "sample_table",
origtable = "sample_table",name = "age",origname = "age",
charsetnr = 63,length = 10,type = 3,
flags = <<0,0>>,
scale = 0,default = []},
#field_metadata{
catalog = "def",schema = "testDB",table = "sample_table",
origtable = "sample_table",name = "longtext_col",
origname = "longtext_col",charsetnr = 33,
length = 4294967295,type = 252,
flags = <<16,0>>,
scale = 0,default = []}],
param_metadata = []},
[[1,"Alex",21,null],[2,"John",21,null]]}'
</pre>
First line is a command to prepare a statement with handler H. Second line is a command to execute
the prepared statement in cursor mode. The command does not return any result but we need
get a metadata record for the following command. The next line is a fetch command that return 2
first rows from the server side cursor. A fetch command returns only binary packets of result set but
skips field metadata. So we have to pass metadata record as a parameter to fetch command
due to properly parse rows data.
<h3>Errors, Exceptions</h3>
The Erlang MySQL client can detect some errors and throws an exceptions. A record #mysql_error represents
information about the error. There are a few kind of the errors:
<dl>
<dt>tcp -</dt><dd>This kind of exception is thrown by the client while network or socket error is occured.</dd>
<dt>connection -</dt><dd>This concerns server connection errors.</dd>
<dt>sqlquery -</dt><dd>Errors arise during execution of SQL query.</dd>
<dt>statement -</dt><dd>Prepared statement can prevent an execution of query with wrong set of parameter.</dd>
<dt>transaction -</dt><dd>Error during transaction. The exception arises after transaction rollback.</dd>
</dl>
Functional programming style does not welcome a using exceptions, so MySQL client uses exception if it can not be avoided,
Otherwise a functions return #mysql_error{} record if execution is failed.
<h3>Transactions</h3>
The client has a transaction support. If you need some persistance operations/queries wrap as an one transaction
then just define a function that implements this queries. The function accesses only one parameter - Connection object.
This function has to return #mysql_error{} record if any of wrapped query is failed or any data if all transaction
query are successful. You need pass this function to my:transaction/2 command. The transaction command has two parameter:
first one is a Connection object, second one is a function mentioned above. See example:
<pre>
27><span>F = fun (C) -> connection:execute_query(C,</span>
27><span>"UPDATE testDB.sample_table SET age = age + 1 WHERE id = 1") end.</span>
`#Fun<erl_eval.6.82930912>'
28><span>Result = case connection:transaction(Cntn, F) of</span>
28><span>#mysql_error{} -> io:format("Transaction is failed and rollbacked ~n"), failed;</span>
28><span>R2 -> R2 end.</span>
`{#metadata{
field_count = 0,param_count = 0,
server_status =
#server_status{
inTransaction = true,autocommit = true,
moreResultExists = false,queryNoGoodIndexUsed = false,
queryNoIndexUsed = false,cursorExists = false,
lastRowSent = false,dbDropped = false,
noBackSlashEscapes = false,metadataChanged = false,
queryWasSlow = false,psOutParams = false},
field_metadata = [],param_metadata = []},
[#ok_packet{
affected_rows = 1,insert_id = 0,
server_status =
#server_status{
inTransaction = true,autocommit = true,
moreResultExists = false,queryNoGoodIndexUsed = false,
queryNoIndexUsed = false,cursorExists = false,
lastRowSent = false,dbDropped = false,
noBackSlashEscapes = false,metadataChanged = false,
queryWasSlow = false,psOutParams = false},
warning_count = 0,
message = "(Rows matched: 1 Changed: 1 Warnings: 0"}]}'
</pre>
connection:transaction/2 function is successfuly completed if the transaction is committed and it returns
#mysql_err{} record if the transaction is rollbacked.
Finally we need to return connection to pool and free the resource:
<pre>
18> <span>datasource:return(data_source, Cntn).</span>
ok
</pre>
<h3>Compression</h3>
Compression protocol is supported if instance of MySQL supports it. To activate this feature set compress field
in #client_options record and pass the record to datasource definition when create
new datasource object. Then established connection allows to talk to
server with compession. Tips: when we are using compression we win in packets size but lost in processor time. Example of
compressed connection establishment:
<pre>
DS_def_compr = #datasource{
host = "localhost",
port = 3306,
database = "testdb",
user = "root",
password = "root",
flags = #client_options{compress=1}
},
my:new_datasource(datasource_compr, DS_def_compr),
Connection = datasource:get_connection(datasource_compr)
</pre>
<h3>Blob transfer</h3>
<p>
MySQL allows keep in blob table fields a huge amount of data: up to 4294967296 (16#100000000) bytes.
To send a long data to server the MySQL client/server protocol defines SEND_LONG_DATA command. The command
is a part of prepared statement execution cycle and can be used only within one.
</p>
<p>
Suppose we have a some table with column of LONGBLOB type and we need to update the field.
First we have to create prepared statement:
<pre>
29><span>Handle = connection:get_prepared_statement_handle(Connection,</span>
29><span>"UPDATE some_table SET longtext_col= ? WHERE persist_id = ?").</span>
3
</pre>
After that we can send to server long block of data that has size of 1000000 bytes:
<pre>
30><span>`connection:send_statement_long_parameter(Connection, Handle, 0, <<16#AA:8000000>>).'</span>
ok
</pre>
Third parameter of the function is a position number of given prepared statement parameter.
We can apply the send_statement_long_parameter/4 a few times and all chunks will be merged in one huge data block.
Now as we complete sending of statement parameter value to server we can finally execute the statement:
<pre>
31><span>LONG_BLOB = 251.</span>
251
32><span>connection:execute_statement(Connection, Handle, [LONG_BLOB, LONG], [null, 1]).</span>
{#metadata{
field_count = 0,param_count = 0,
server_status =
#server_status{
inTransaction = false,autocommit = true,
moreResultExists = false,queryNoGoodIndexUsed = false,
queryNoIndexUsed = false,cursorExists = false,
lastRowSent = false,dbDropped = false,
noBackSlashEscapes = false,metadataChanged = false,
queryWasSlow = false,psOutParams = false},
field_metadata = [],param_metadata = []},
[#ok_packet{
affected_rows = 1,insert_id = 0,
server_status =
#server_status{
inTransaction = false,autocommit = true,
moreResultExists = false,queryNoGoodIndexUsed = false,
queryNoIndexUsed = false,cursorExists = false,
lastRowSent = false,dbDropped = false,
noBackSlashEscapes = false,metadataChanged = false,
queryWasSlow = false,psOutParams = false},
warning_count = 1,
message = "(Rows matched: 1 Changed: 1 Warnings: 0"}]}
</pre>
During execution we do not need to send blob parameter value, because it already is in the server.
Please, note that MySQL server has limitation to maximum client packet size (max_allowed_packet = 1048576 by default).
So you can not send chunk of long data more then max_allowed_packet, but you can send this chunks a few times
as much as needed and server will concatenate them.
</p>
<p>
Server response has no limitations and we can query table with blob any size. Server will split
huge packet to standard ones and ErlMySQL client merges them as needed.
<pre>
33><span>connection:execute_query(Connection, "SELECT longtext_col FROM some_table WHERE persist_id = 1").</span>
`{#metadata{
field_count = 1,param_count = 0,
server_status =
#server_status{
inTransaction = false,autocommit = true,
moreResultExists = false,queryNoGoodIndexUsed = false,
queryNoIndexUsed = false,cursorExists = false,
lastRowSent = false,dbDropped = false,
noBackSlashEscapes = false,metadataChanged = false,
queryWasSlow = false,psOutParams = false},
field_metadata =
[#field_metadata{
catalog = "def",schema = "testDB",table = "sample_table",
origtable = "sample_table",name = "longtext_col",
origname = "longtext_col",charsetnr = 33,
length = 4294967295,type = 252,
flags = <<16,0>>,
scale = 0,default = []}],
param_metadata = []},
[[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0|...]]]}'
</pre>
</p>
@reference [https://sourceforge.net/projects/erlpool] - Erlang resource Pool project is dependence for the MySQL client.
@reference [http://github.com/Eonblast/Emysql] - other similar project.
@reference [http://code.google.com/p/erlang-mysql-driver] - one more similar project.
@reference [http://mysql.timesoft.cc/doc/internals/en/index.html] - description of MySQL client-server low level protocol.
@reference [http://www.scribd.com/doc/32435818/MySQL-Client-Server-Protocol-Documentation-net-doc-txt] - MySQL Client/Server Protocol documentation.
@reference [http://erlangcentral.org/wiki/index.php?title=MySQL_client_(driver)] - article on Erlang Central.
@see my
@since 2010-10-08
@title MySQL client for Erlang.
@version {@version} |
# Shell_Scripting
<img src='images/shell.webp' width='950' height='300'>
### **What is Shell Scripting?**
A shell script is a list of commands in a computer program that is run by the Unix shell which is a command line interpreter. A shell script usually has comments that describe the steps. The different operations performed by shell scripts are program execution, file manipulation and text printing. A wrapper is also a kind of shell script that creates the program environment, runs the program etc.
### **Why use Shell Scripting?**
- Batch jobs
Several commands that would be entered manually in a command line interface can be executed automatically using a shell script. This can be done without the user needing to trigger each command separately.
- Generalisation
It is much more flexible to use loops, variables etc for multiple tasks in shell script. An example of this is a Unix shell script known as bash, which converts jpg images to png images.
- Shortcuts
There is a shortcut provided by a shell script for a system command where command options, environment settings or post processing apply. This still allows the shortcut script to act as a Unix command.
## Introduction to Shell Scripting and User Input
Shell scripts can be written in either a code editor like VSCode or you can use nano/ vim.
Since we want to keep our scripts we will be using VSCode.
1. Create a folder - `mkdir shell_scripting`
2. cd into the folder - `desktop/shell_scripting`
3. create the file for the shell script - `touch myscript.sh`
4. open up VSCode - `code .`

## Shell Scripting Syntax
1. **Variables**: Variables are used to store information to be referenced, this can be of various types such as numbers, strings and arrays. You can assign values to variables using the **=** operator. To access the value of the variable use the **$** symbol e.g `$variable_name`

2. **Control Flow**: Bash **if-else** statements are used to perform conditional tasks in the sequential flow of execution of statements. Sometimes, we want to process a specific set of statements if a condition is true, and another set of statements if it is false. To perform such type of actions, we can apply the if-else mechanism.

**For loop** is a control structure that is used to perform repetitive tasks or execute a bunch of commands a specific number of times. With for loop, you can iterate through numbers, lists, files, or even directories.
***
3. **Input and Output**: The **read command** is used to read input from the user or from a file and output the text using the echo command. You can also redirect input and output using operators like `>` output to a file, `<` input from a file, and `|`pipe the output of the one command as an input to another.

Here we have a script `echo Hello World` in our `myscript.sh` file, we will output the content into a new file `index.sh`

Below we see the content of `myscript.sh` in the new file

We can also pass the content of a file as input to a command.
`grep "demonstrate" < input.txt` - this will search for matching patterns in the `input.txt` file


***
5. **Functions**: Functions in bash scripting are a great option to reuse code. A Bash function can be defined as a set of commands which can be called several times within bash script. The purpose of function in bash is to help you make your scripts more readable and avoid writing the same code again and again.

## Time to our First Shell Script !!
Step 1: Inside your file copy and paste the code block below:
```
#!/bin/bash
# Prompt the user for their name
echo "Enter your name:"
read name
# Display a greeting with the entered name
echo "Hello, $name! Nice to meet you."
```
Step 2. Save your file
Step 3. Run the command `sudo chmod +x myscript.sh` this makes the file executable.
Step 6. Run the script using `./myscript.sh`

## Directory Manipulation and Navigation
This script will display the current directory, create a new directory called `"my_directory"`, change to that directory, create two files inside it, list the files, move back oe level up, remove the `"my_directory"` and its contents, and finally list the files in the current directory again.
Step 1: Open a file named navigating-linux-filesystem.sh
Step 2: paste the code block below into your file.
```
#!/bin/bash
# Display current directory
echo "Current directory: $PWD"
# Create a new directory
echo "Creating a new directory..."
mkdir my_directory
echo "New directory created."
# Change to the new directory
echo "Changing to the new directory..."
cd my_directory
echo "Current directory: $PWD"
# Create some files
echo "Creating files..."
touch file1.txt
touch file2.txt
echo "Files created."
# List the files in the current directory
echo "Files in the current directory:"
ls
# Move one level up
echo "Moving one level up..."
cd ..
echo "Current directory: $PWD"
# Remove the new directory and its contents
echo "Removing the new directory..."
rm -rf my_directory
echo "Directory removed."
# List the files in the current directory again
echo "Files in the current directory:"
ls
```
Step 3: Run the command `sudo chmod +x navigating-linux-filesystem.sh` to set execute permission on the file
Step 4: Run your script using the command `./navigating-linux-filesystem.sh`
Below is the expected output in the terminal:

## File Operations and Sorting
We will be writing a script that focuses on File Operations and Sorting.
This script creates three files `file1.txt, file2.txt, file3.txt`, displays the files in their current order. sorts them alphabetically, saves the sorted files in `sorted_files.txt`, displays the sorted files, removes the originalfiles, renames the sorted file to `sorted_files_sorted_alphabetically.txt` and finally displays the contents of the sorted file.
Step 1: Create a file `touch sorting.sh`
Step 2: Copy and paste the code block below into the file:
```
#!/bin/bash
# Create three files
echo "Creating files..."
echo "This is file3." > file3.txt
echo "This is file1." > file1.txt
echo "This is file2." > file2.txt
echo "Files created."
# Display the files in their current order
echo "Files in their current order:"
ls
# Sort the files alphabetically
echo "Sorting files alphabetically..."
ls | sort > sorted_files.txt
echo "Files sorted."
# Display the sorted files
echo "Sorted files:"
cat sorted_files.txt
# Remove the original files
echo "Removing original files..."
rm file1.txt file2.txt file3.txt
echo "Original files removed."
# Rename the sorted file to a more descriptive name
echo "Renaming sorted file..."
mv sorted_files.txt sorted_files_sorted_alphabetically.txt
echo "File renamed."
# Display the final sorted file
echo "Final sorted file:"
cat sorted_files_sorted_alphabetically.txt
```
Step 3: Set the execute permission `sudo chmod +x sorting.sh`
Step 4: Run your script using `./sorting.sh`


### Working with Numbers and Calculations
This script defines two variables num1 and num2 with numeric values, performs basic arithmetic operations(addition, subtraction, multiplication,division and modulus), and displays the results. It also performs more complex calculations such as raising num1 to the pwer of 2 and calculating the square root of num2, amd displays thos results as well.
Step 1: create a new file `tocuh calculations.sh`
Step 2: Copy and paste the code below:
```
#!/bin/bash
# Define two variables with numeric values
num1=10
num2=5
# Perform basic arithmetic operations
sum=$((num1 + num2))
difference=$((num1 - num2))
product=$((num1 * num2))
quotient=$((num1 / num2))
remainder=$((num1 % num2))
# Display the results
echo "Number 1: $num1"
echo "Number 2: $num2"
echo "Sum: $sum"
echo "Difference: $difference"
echo "Product: $product"
echo "Quotient: $quotient"
echo "Remainder: $remainder"
# Perform some more complex calculations
power_of_2=$((num1 ** 2))
square_root=$(echo "sqrt($num2)" | bc)
# Display the results
echo "Number 1 raised to the power of 2: $power_of_2"
echo "Square root of number 2: $square_root"
```
Step 3: Set the execute permission `sudo chmod +x calculations.sh`
Step 4: Run your script using `./calculations.sh`

## File Backup and Timestamping
This shell script focuses on file backup and timestamp.
This script defines the source directory and backup directory paths. It then creates a timestamp appended to its name. This script then copies all files from the source directory to the backup directory using the cp command with the `-r` option for recursive copying. Finally, it displays a message indicating the completion of the backup process and shows the path of the backup directory with the timestamp.
Step 1: Create a file `touch backup.sh`
Step 2: Copy and paste the code bock belwo into the file.
```
#!/bin/bash
# Define the source directory and backup directory
source_dir="/path/to/source_directory"
backup_dir="/path/to/backup_directory"
# Create a timestamp with the current date and time
timestamp=$(date +"%Y%m%d%H%M%S")
# Create a backup directory with the timestamp
backup_dir_with_timestamp="$backup_dir/backup_$timestamp"
# Create the backup directory
mkdir -p "$backup_dir_with_timestamp"
# Copy all files from the source directory to the backup directory
cp -r "$source_dir"/* "$backup_dir_with_timestamp"
# Display a message indicating the backup process is complete
echo "Backup completed. Files copied to: $backup_dir_with_timestamp"
```
Step 3: Set execute permission `sudo chmod +x backup.sh`
Step 4: Run your script `./backup.sh`

# THE END !!! |
setClass("ulam", slots=c( call = "language",
model = "character",
#stanfit = "stanfit",
coef = "numeric",
vcov = "matrix",
data = "list",
start = "list",
pars = "character" ,
formula = "list" ,
formula_parsed = "list" ))
setMethod("coef", "ulam", function(object) {
x <- summary(object)
y <- x$mean
names(y) <- rownames(x)
return(y)
})
setMethod("precis", "ulam",
function( object , depth=1 , pars , prob=0.89 , digits=2 , sort=NULL , decreasing=FALSE , lp__=FALSE , omit=NULL ,... ) {
low <- (1-prob)/2
upp <- 1-low
# when fit with cmdstan, all parameters/variable in result
# so want to filter at minimum by object@pars
if ( missing(pars) ) pars <- object@pars
if ( !is.null(attr(object,"stanfit")) ) {
result <- summary( attr(object,"stanfit") ,pars=pars,probs=c(low,upp))$summary[,c(1,3:7)]
result <- as.data.frame( result )
}
if ( !is.null(attr(object,"cstanfit")) ) {
return( precis( attr(object,"cstanfit") , depth=depth, pars=pars , prob=prob, omit=omit , ... ) )
}
banlist <- c("dev","lp__")
if ( lp__==TRUE ) banlist <- c("dev")
idx <- which( rownames(result) %in% banlist )
idx2 <- grep( "log_lik[" , rownames(result) , fixed=TRUE )
if ( length(idx2)>0 ) idx <- c( idx , idx2 )
if ( length(idx)>0 ) {
# remove dev and lp__ and log_lik from table
result <- result[ -idx , ]
}
# any pars to omit?
if ( !is.null(omit) ) {
for ( k in 1:length(omit) ) {
idx <- grep( omit[k] , rownames(result) , fixed=TRUE )
if ( length(idx)>0 ) result <- result[ -idx , ]
}
}
result <- precis_format( result , depth , sort , decreasing )
return( new( "precis" , result , digits=digits ) )
})
# models fit with cmdstan=TRUE include all parameters/variables
# so need to trim what is returned using object@pars
extract_post_ulam <-
function(object,n,clean=TRUE,pars,...) {
#require(rstan)
if ( missing(pars) & clean==TRUE ) pars <- object@pars
if ( !is.null(attr(object,"cstanfit")) ) {
# use posterior to extract draws and convert to array format
pr <- as_draws_rvars( attr(object,"cstanfit")$draws() )
p <- list()
for ( i in 1:length(pr) )
p[[ names(pr)[i] ]] <- draws_of( pr[[i]] )
} else
# assume old rstan fit
p <- rstan::extract(object@stanfit,pars=pars,...)
# get rid of dev and lp__
if ( clean==TRUE ) {
p[['dev']] <- NULL
p[['lp__']] <- NULL
p[['log_lik']] <- NULL
}
# get rid of those ugly dimnames
for ( i in 1:length(p) ) {
attr(p[[i]],"dimnames") <- NULL
}
if (FALSE ) {
if ( !missing(n) ) {
tot_samples <- stan_total_samples(object@stanfit)
n <- min(n,tot_samples)
for ( i in 1:length(p) ) {
n_dims <- length( dim(p[[i]]) )
if ( n_dims==1 ) p[[i]] <- p[[i]][1:n]
if ( n_dims==2 ) p[[i]] <- p[[i]][1:n,]
if ( n_dims==3 ) p[[i]] <- p[[i]][1:n,,]
}
} else {
n <- stan_total_samples(object@stanfit)
}
}
model_name <- match.call()[[2]]
attr(p,"source") <- concat( "ulam posterior from " , model_name )
return(p)
}
setMethod("extract.samples","ulam",extract_post_ulam)
setMethod("stancode", "ulam",
function(object) {
cat( object@model )
return( invisible( object@model ) )
}
)
setMethod("vcov", "ulam", function (object, ...) {
#object@vcov
cov(as.data.frame(extract.samples(object,...)))
} )
setMethod("nobs", "ulam", function (object, ...) { attr(object,"nobs") } )
setMethod("logLik", "ulam",
function (object, ...)
{
if(length(list(...)))
warning("extra arguments discarded")
if ( is.null(attr(object,"deviance") ) ) {
val <- attr( WAIC(object) , "lppd" )
} else {
val <- (-1)*attr(object,"deviance")/2
}
attr(val, "df") <- length(object@coef)
attr(val, "nobs") <- attr(object,"nobs")
class(val) <- "logLik"
val
})
setMethod("deviance", "ulam",
function (object, ...)
{
if ( is.null(attr(object,"deviance")) ) {
return( as.numeric((-2)*logLik(object)) )
} else {
return( attr(object,"deviance") )
}
})
setMethod("show", "ulam", function(object){
cat("Hamiltonian Monte Carlo approximation\n")
# timing and sample counts
is_cstan <- !is.null( attr(object,"cstanfit") )
if ( is_cstan==TRUE ) {
# cmdstan fit
dur <- attr(object,"cstanfit")$time()$chains
chains <- attr(object,"cstanfit")$num_chains()
iter <- attr(object,"cstanfit")$metadata()$iter_sampling
warm <- 0 # attr(object,"cstanfit")$metadata()$iter_warmup
# iter is just post warmup for cstan
} else {
# old stanfit
iter <- object@stanfit@sim$iter
warm <- object@stanfit@sim$warmup
chains <- object@stanfit@sim$chains
dur <- stan_sampling_duration(object)
}
chaintxt <- " chain\n"
if ( chains>1 ) chaintxt <- " chains\n"
tot_samples <- (iter-warm)*chains
cat(concat( tot_samples , " samples from " , chains , chaintxt ))
if ( is_cstan==FALSE )
lab <- attr(dur,"units")
else
lab <- "seconds"
attr(dur,"units") <- NULL
cat(concat("\nSampling durations (",lab,"):\n"))
print(round(dur,2))
cat("\nFormula:\n")
for ( i in 1:length(object@formula) ) {
print( object@formula[[i]] )
}
if ( !is.null(attr(object,"WAIC")) ) {
waic <- attr(object,"WAIC")
use_waic <- sum(waic)
cat("\nWAIC (SE): ")
cat( concat(round(as.numeric(use_waic),2) , " (" , round(as.numeric(attr(waic,"se")),1) , ")" , "\n" ) )
cat("pWAIC: ")
use_pWAIC <- sum( unlist(attr(waic,"pWAIC")) )
cat( round(as.numeric(use_pWAIC),2) , "\n" )
}
})
setMethod("summary", "ulam", function(object){
precis(object,depth=3)
})
setMethod("pairs" , "ulam" , function(x, n=200 , alpha=0.7 , cex=0.7 , pch=16 , adj=1 , pars , ...) {
#require(rstan)
if ( missing(pars) )
posterior <- extract.samples(x)
else
posterior <- extract.samples(x,pars=pars)
#if ( !missing(pars) ) {
# # select out named parameters
# p <- list()
# for ( k in pars ) p[[k]] <- posterior[[k]]
# posterior <- p
#}
panel.dens <- function(x, ...) {
usr <- par("usr"); on.exit(par(usr))
par(usr = c(usr[1:2], 0, 1.5) )
h <- density(x,adj=adj)
y <- h$y
y <- y/max(y)
abline( v=0 , col="gray" , lwd=0.5 )
lines( h$x , y )
}
panel.2d <- function( x , y , ... ) {
i <- sample( 1:length(x) , size=n )
abline( v=0 , col="gray" , lwd=0.5 )
abline( h=0 , col="gray" , lwd=0.5 )
dcols <- densCols( x[i] , y[i] )
dcols <- sapply( dcols , function(k) col.alpha(k,alpha) )
points( x[i] , y[i] , col=dcols , ... )
}
panel.cor <- function( x , y , ... ) {
k <- cor( x , y )
cx <- sum(range(x))/2
cy <- sum(range(y))/2
text( cx , cy , round(k,2) , cex=2*exp(abs(k))/exp(1) )
}
pairs( posterior , cex=cex , pch=pch , upper.panel=panel.2d , lower.panel=panel.cor , diag.panel=panel.dens , ... )
})
# my trace plot function
traceplot_ulam <- function( object , pars , chains , col=rethink_palette , alpha=1 , bg=col.alpha("black",0.15) , ask=TRUE , window , trim=100 , n_cols=3 , max_rows=5 , lwd=0.5 , lp=FALSE , ... ) {
if ( !(class(object) %in% c("map2stan","ulam","stanfit")) ) stop( "requires map2stan or stanfit fit object" )
#if ( class(object) %in% c("map2stan","ulam") ) object <- object@stanfit
# get all chains, not mixed, from stanfit
if ( missing(pars) ) {
# post <- extract(object,permuted=FALSE,inc_warmup=TRUE)
post <- as_draws_array( attr(object,"cstanfit")$draws(inc_warmup=TRUE) )
dimnames <- attr(post,"dimnames")
pars <- dimnames$variable
# cut out "dev" and "lp__" and "log_lik"
wdev <- which(pars=="dev")
if ( length(wdev)>0 ) pars <- pars[-wdev]
wlp <- which(pars=="lp__")
if ( length(wlp)>0 & lp==FALSE ) pars <- pars[-wlp]
wlp <- grep( "log_lik" , pars , fixed=TRUE )
if ( length(wlp)>0 ) pars <- pars[-wlp]
} else
#post <- extract(object,pars=pars,permuted=FALSE,inc_warmup=TRUE)
post <- as_draws_array( attr(object,"cstanfit")$draws(variables=pars,inc_warmup=TRUE) )
# names
dimnames <- attr(post,"dimnames")
n_chains <- length(dimnames$chain)
if ( missing(chains) ) chains <- 1:n_chains
chain.cols <- rep_len(col,n_chains)
# figure out grid and paging
n_pars <- length( pars )
n_rows=ceiling(n_pars/n_cols)
n_rows_per_page <- n_rows
paging <- FALSE
n_pages <- 1
if ( n_rows_per_page > max_rows ) {
n_rows_per_page <- max_rows
n_pages <- ceiling(n_pars/(n_cols*n_rows_per_page))
paging <- TRUE
}
n_iter <- length(dimnames$iteration) # all iterations
n_warm <- attr(object,"cstanfit")$metadata()$iter_warmup
n_samples_extracted <- dim( post )[1]
wstart <- 1
wend <- n_iter
if ( !missing(window) ) {
wstart <- window[1]
wend <- window[2]
}
show_warmup <- TRUE
if ( missing(window) ) {
if ( n_iter > n_samples_extracted ) {
# probably no warmup saved
wend <- n_samples_extracted
show_warmup <- FALSE
trim <- 1 # no trim when warmup not shown
n_iter <- n_samples_extracted
}
window <- c(trim,n_iter)
}
# worker
plot_make <- function( main , par , neff , ... ) {
ylim <- c( min(post[wstart:wend,,pars[par]]) , max(post[wstart:wend,,pars[par]]) )
plot( NULL , xlab="" , ylab="" , type="l" , xlim=c(wstart,wend) , ylim=ylim , ... )
# add polygon here for warmup region?
diff <- abs(ylim[1]-ylim[2])
ylim <- ylim + c( -diff/2 , diff/2 )
if ( show_warmup==TRUE )
polygon( n_warm*c(-1,1,1,-1) , ylim[c(1,1,2,2)] , col=bg , border=NA )
neff_use <- neff[ names(neff)==main ]
mtext( paste("n_eff =",round(neff_use,0)) , 3 , adj=1 , cex=0.9 )
mtext( main , 3 , adj=0 , cex=1 )
}
plot_chain <- function( x , nc , ... ) {
lines( 1:n_iter , x , col=col.alpha(chain.cols[nc],alpha) , lwd=lwd )
}
# fetch n_eff
n_eff <- summary(object)$ess_bulk
names(n_eff) <- rownames(summary(object))
# make window
#set_nice_margins()
par(mgp = c(0.5, 0.5, 0), mar = c(1.5, 1.5, 1.5, 1) + 0.1,
tck = -0.02)
par(mfrow=c(n_rows_per_page,n_cols))
# draw traces
n_ppp <- n_rows_per_page * n_cols # num pars per page
for ( k in 1:n_pages ) {
if ( k > 1 ) message( paste("Waiting to draw page",k,"of",n_pages) )
for ( i in 1:n_ppp ) {
pi <- i + (k-1)*n_ppp
if ( pi <= n_pars ) {
if ( pi == 2 ) {
if ( ask==TRUE ) {
ask_old <- devAskNewPage(ask = TRUE)
on.exit(devAskNewPage(ask = ask_old), add = TRUE)
}
}
plot_make( pars[pi] , pi , n_eff , ... )
for ( j in 1:n_chains ) {
if ( j %in% chains )
plot_chain( post[ , j , pars[pi] ] , j , ... )
}#j
}
}#i
}#k
}
setMethod("traceplot", "ulam" , function(x,...) traceplot_ulam(object=x,...) )
setMethod( "plot" , "ulam" , function(x,depth=1,...) precis_plot(precis(x,depth=depth),...) )
setMethod("nobs", "ulam", function (object, ...) {
z <- attr(object,"nobs")
if ( is.null(z) ) {
# try to get nobs from a link function
link_funcs <- object@formula_parsed$link_funcs
if ( length(link_funcs)>0 ) {
z <- link_funcs[[1]]$N
}
}
return(z)
} ) |
import * as fs from "fs"
import * as appdirs from "appdirs"
import * as mkdirp from "mkdirp"
import { FileSystem } from "./rx/FileSystem"
import { Observable } from "rxjs/Rx"
const APP_NAME = "Horo"
const APP_AUTHOR = "PeterCxy"
const APP_VERSION: string = require("../../package.json").version
const CONFIG_DIR = appdirs.userConfigDir(APP_NAME, APP_AUTHOR)
const DATA_DIR = appdirs.userDataDir(APP_NAME, APP_AUTHOR)
function checkDir(dir: string) {
if (!fs.existsSync(dir)) {
mkdirp.sync(dir)
}
}
checkDir(CONFIG_DIR)
checkDir(DATA_DIR)
export module UserData {
export function config<T>(name: string): Observable<T> {
let filename = `${CONFIG_DIR}/${name}.json`
return FileSystem.exists(filename)
.flatMap((exists) => {
if (!exists) {
throw new Error(`Config ${filename} does not exist`)
} else {
return FileSystem.readFile(filename, "utf8")
}
})
.map((data: string) => <T>JSON.parse(data))
}
} |
import React from 'react'
import { useState } from 'react';
import { useNavigate } from "react-router-dom";
const SignUp = (props) => {
const [credentials, setCredentials] = useState({ name: "", email: "", password: "", cpassword: "" });
let history = useNavigate();
const { name, email, password} = credentials;
const handleSubmit = async (e) => {
e.preventDefault();
const response = await fetch("http://localhost:5000/api/auth/createuser", {
method: 'POST',
headers: {
'Content-Type': 'Application/json'
},
body: JSON.stringify({ name, email, password })
})
const json = await response.json();
console.log(json);
localStorage.setItem('token', json.authToken);
history("/");
props.showAlert("SignUp Successful","success")
}
const onChange = (e) => {
setCredentials({ ...credentials, [e.target.name]: e.target.value });
}
return (
<div className='container'>
<form onSubmit={handleSubmit}>
<div className="mb-3">
<label htmlFor="name" className="form-label">Enter your Name</label>
<input type="text" className="form-control" onChange={onChange} id="name" name='name' aria-describedby="emailHelp" />
</div>
<div className="mb-3">
<label htmlFor="email" className="form-label">Email address</label>
<input type="email" className="form-control" onChange={onChange} id="email" name='email' aria-describedby="emailHelp" />
</div>
<div className="mb-3">
<label htmlFor="password" className="form-label">Password</label>
<input type="password" className="form-control" onChange={onChange} id="password" name='password' />
</div>
<div className="mb-3">
<label htmlFor="cpassword" className="form-label">Confirm Password</label>
<input type="password" className="form-control" onChange={onChange} id="cpassword" name='cpassword' />
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
)
}
export default SignUp |
<?php
namespace App\Http\Controllers;
use JavaScript;
// use Spatie\PdfToText\Pdf;
use App\Models\GeneralReport;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests\GeneralReportRequest;
use App\Http\Requests\GeneralReportUpdateRequest;
class GeneralReportController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$generalReports = [];
if(Auth::user()->company) {
$generalReports = GeneralReport::where('company_id', Auth::user()->company->id)->orderBy('id', 'desc')->get();
}
return view('reports.general.index', compact('generalReports'));
}
/**
* Show the form for creating a new resource.
*/
public function create()
{
return view('reports.general.create');
}
/**
* Store a newly created resource in storage.
*/
public function store(GeneralReportRequest $request)
{
$request->validated();
$generalReport = GeneralReport::create([
'title' => $request->title,
'description' => $request->description,
'company_id' => Auth::user()->company->id,
]);
if($request->hasFile('report_attachement')) {
$generalReport->addMedia($request->report_attachement)->toMediaCollection('report_attachement');
}
return redirect()->route('general-reports.index')->with("success", $generalReport->title . " created successfully!");
}
/**
* Display the specified resource.
*/
public function show(GeneralReport $generalReport)
{
$generalReportUrl = $generalReport->getFirstMediaUrl('report_attachement');
return view('reports.general.show', compact(['generalReport', 'generalReportUrl']));
}
/**
* Show the form for editing the specified resource.
*/
public function edit(GeneralReport $generalReport)
{
return view('reports.general.edit', compact('generalReport'));
}
/**
* Update the specified resource in storage.
*/
public function update(GeneralReportUpdateRequest $request, GeneralReport $generalReport)
{
$request->validated();
$generalReport->update($request->except('report_attachement'));
if($request->hasFile('report_attachement')) {
$generalReport->clearMediaCollection('report_attachement');
$generalReport->addMedia($request->report_attachement)->toMediaCollection('report_attachement');
}
return redirect()->route('general-reports.index', $generalReport)->with('success', $generalReport->title . ' updated successfully.');
}
/**
* Remove the specified resource from storage.
*/
public function destroy(GeneralReport $generalReport)
{
$generalReport->delete();
return redirect()->route('general-reports.index')->with('success', 'General report deleted successfully');
}
public function download($id)
{
$generalReport = GeneralReport::findOrFail($id);
$path = $generalReport->getFirstMedia('report_attachement')->getPath();
$file_name = $generalReport->getFirstMedia('report_attachement')->file_name;
return response()->download($path, $file_name);
}
} |
"use client";
import Heading from "@/components/Heading";
import { MessageSquare } from "lucide-react";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import React, { useState } from "react";
import { ConversationFormSchema } from "@/schemas";
import { Button } from "@/components/ui/button";
import {
Form,
FormControl,
FormField,
FormItem,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import axios from "axios";
import { useRouter } from "next/navigation";
import { ChatCompletionRequestMessage } from "openai";
import Empty from "@/components/Empty";
import Loader from "@/components/Loader";
import UserAvatar from "@/components/UserAvatar";
import BotAvatar from "@/components/BotAvatar";
import { cn } from "@/lib/utils";
import { useProModal } from "@/hooks/useProModal";
import toast from "react-hot-toast";
const ConversationGenerationPage = () => {
const router = useRouter();
const proModal = useProModal();
const [messages, setMessages] = useState<ChatCompletionRequestMessage[]>([]);
const form = useForm<z.infer<typeof ConversationFormSchema>>({
resolver: zodResolver(ConversationFormSchema),
defaultValues: {
prompt: "",
},
});
const isLoading = form.formState.isSubmitting;
async function onSubmit(values: z.infer<typeof ConversationFormSchema>) {
try {
const userMessage = {
role: "user",
content: values.prompt,
};
const newMessages = [...messages, userMessage];
const response = await axios.post("/api/conversation", {
messages: values.prompt,
});
setMessages((current) => [...current, userMessage, response.data[0]]);
form.reset();
} catch (error: any) {
if (error?.response?.status === 403) {
proModal.onOpen();
} else {
toast.error("Something went wrong!");
}
} finally {
router.refresh();
}
}
return (
<section className="mt-8">
<Heading
title="Conversation"
description="Our most advanced conversation model."
Icon={MessageSquare}
iconColor="text-violet-500"
bgColor="bg-violet-500/10"
/>
<div className="px-4 lg:px-8">
<div>
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="rounded-lg border w-full p-4 px-3 md:px-6 focus-within:shadow-sm grid grid-cols-12 gap-2"
>
<FormField
control={form.control}
name="prompt"
render={({ field }) => (
<FormItem className="col-span-12 lg:col-span-10">
<FormControl className="m-0 p-0">
<Input
className="border-0 outline-none focus-visible:ring-0 focus-visible:ring-transparent"
placeholder="Have a conversation with Genify..."
disabled={isLoading}
{...field}
autoComplete="off"
type="text"
/>
</FormControl>
</FormItem>
)}
/>
<Button
type="submit"
disabled={isLoading}
className="col-span-12 lg:col-span-2 w-full"
>
Generate
</Button>
</form>
</Form>
</div>
<div className="space-y-4 mt-4">
{isLoading && (
<div className="p-8 rounded-lg w-full flex items-center justify-center bg-muted">
<Loader color="fill-violet-500" />
</div>
)}
{messages.length === 0 && !isLoading && (
<div>
<Empty label="No conversation started!" />
</div>
)}
<div className="flex flex-col-reverse gap-y-4">
<div className="flex flex-col-reverse gap-y-4">
{messages.map((message, index) => (
<div
key={index}
className={cn(
"p-8 w-full flex items-start gap-x-8 rounded-lg",
message.role === "user"
? "bg-white border border-black/10"
: "bg-muted"
)}
>
{message.role === "user" ? <UserAvatar /> : <BotAvatar />}
<p className="text-sm">{message?.content}</p>
</div>
))}
</div>
</div>
</div>
</div>
</section>
);
};
export default ConversationGenerationPage; |
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>入力画面</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-sm navbar-dark bg-dark mt-3 mb-3">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav4" aria-controls="navbarNav4" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="#">登録画面</a>
<div class="collapse navbar-collapse">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" th:href="@{/index}">トップ</a>
</li>
<li class="nav-item active">
<a class="nav-link" th:href="@{/employee/input/}">新規登録</a>
</li>
<li class="nav-item active">
<a class="nav-link" th:href="@{/employee/list/}">一覧</a>
</li>
</ul>
</div>
</nav>
<form action="#" th:action="@{/employee/confirm}" th:object="${employee}" method="post">
<div>
<p>ユーザー情報を入力してください。</p>
<p>個人コードを入力してください。</p>
<input type="text" th:field="*{code}" />
<span th:if="${#fields.hasErrors('code')}" th:errors="*{code}" style="color: red"></span>
<p>名前を入力してください。</p>
<input type="text" th:field="*{name}" />
<span th:if="${#fields.hasErrors('name')}" th:errors="*{name}" style="color: red"></span>
<p>パスワードを入力してください。</p>
<input type="text" th:field="*{password}" />
<span th:if="${#fields.hasErrors('password')}" th:errors="*{password}" style="color: red"></span>
<p>役割を入力してください。</p>
<input type="text" th:field="*{role}" />
<span th:if="${#fields.hasErrors('role')}" th:errors="*{role}" style="color: red"></span>
<p>メールアドレスを入力してください。</p>
<input type="text" th:field="*{mailadress}" />
<span th:if="${#fields.hasErrors('mailadress')}" th:errors="*{mailadress}" style="color: red"></span>
</div>
<div>
<button type="submit" class="btn btn-default">確認</button>
</div>
</form>
</body>
</html> |
"""Entry point for the Song Player Console Application.
The application provides a console-based user interface to manage and play songs, create and manage playlists,
adjust volume levels, and control song playback.
Author: Erik Ccanto
Date: 30 Jul 2023
"""
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = 'hide'
# pylint: disable=wrong-import-order, wrong-import-position
import logging
from pathlib import Path
from typing import Optional
import click
from pygame import mixer
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.widgets import Footer, Header
from cplayer import __version__
from cplayer.src.elements import CONFIG
from cplayer.src.elements.downloader import YoutubeDownloader
from cplayer.src.pages.help import HelpPage
from cplayer.src.pages.home import HomePage
__LOGGING_FORMAT = '[%(asctime)s] [%(process)d] %(filename)s:%(lineno)d - %(levelname)s - %(message)s'
class Application(App):
"""Class that represent the main application and inherits from the textual App class."""
TITLE = f'{CONFIG.data.appearance.style.icons.playlist} Playlist'
CSS = (
f'$primary: {CONFIG.data.appearance.style.colors.primary}; '
f'$background: {CONFIG.data.appearance.style.colors.background};'
)
CSS_PATH = Path(__file__).parent.joinpath('resources/styles/application.css')
BINDINGS = [
Binding(CONFIG.data.general.shortcuts.pages.quit, 'quit', 'Quit', show=True),
Binding(CONFIG.data.general.shortcuts.pages.home, 'home', 'Home', show=True),
Binding(CONFIG.data.general.shortcuts.pages.information, 'info', 'Info', show=True),
]
def __init__(self, path: Optional[Path], *args, **kwargs) -> None:
"""Initializes the Application object.
:param path: The optional path of the directory songs.
:param *args: Variable length argument list.
:param **kwargs: Arbitrary keyword arguments.
"""
super().__init__(*args, **kwargs)
self.home_page = HomePage(path, change_title=self.set_title, start_hidden=False)
self.help_page = HelpPage(change_title=self.set_title)
def compose(self) -> ComposeResult:
"""Composes the application layout.
:returns: The ComposeResult object representing the composed layout.
"""
yield Header()
yield self.home_page
yield self.help_page
if CONFIG.data.appearance.style.footer:
yield Footer()
def set_title(self, title: str) -> None:
"""Sets the title of the application window.
:param title: The title of the application window.
"""
self.title = title
def action_info(self) -> None:
"""Opens the information window."""
help_page = self.query_one(HelpPage)
help_page.show()
home_path = self.query_one(HomePage)
home_path.hide()
def action_home(self) -> None:
"""Opens the home window."""
home_path = self.query_one(HomePage)
home_path.show()
help_page = self.query_one(HelpPage)
help_page.hide()
@click.command()
@click.option(
'-p',
'--path',
help='Path to the directory containing your music files.',
type=click.Path(exists=True, path_type=Path),
)
@click.option(
'-u',
'--url',
help='URL of the song to download from YouTube.',
)
@click.version_option(version=__version__)
def main(path: Optional[Path], url: Optional[str]) -> None:
# noqa: D413, D407, D412, D406
"""Command Line Python player CLI.
This command line tool plays music files from a specified directory or last used playlist.
Examples:
- Play music from the current directory or the last used playlist if it exists:
$ cplayer
- Play music from a specific directory:
$ cplayer --path /path/to/music_directory
- Download song from YouTube
$ cplayer --url 'https://www.youtube.com/watch?v=xyz'
For more information, visit https://github.com/eccanto/cplayer
"""
logging.basicConfig(
filename=Path(CONFIG.data.development.logfile).expanduser(),
level=logging.getLevelName(CONFIG.data.development.level),
format=__LOGGING_FORMAT,
)
if url:
downloader = YoutubeDownloader(url)
downloader.download()
else:
mixer.init()
app = Application(path)
app.run() |
# Open Latency Tester Theia (OLTT)
## Overview
OLTT (Open Latency Tester Theia) is an innovative, open-source tool inspired by Theia, the Greek goddess of sight, designed to measure input latency in various computing environments. Perfect for both End User Computing (EUC) professionals and gaming enthusiasts, OLTT combines Adafruit QT Py hardware with CircuitPython, providing a DIY approach to latency testing and calibration.
## Hardware Requirements
- Adafruit QT Py
- Luminance sensor
- Additional hardware as per your specific setup requirements
## Software Requirements
- CircuitPython (latest version recommended)
- Necessary CircuitPython libraries
## Getting Started
### Setting Up Your Hardware
1. Assemble the Adafruit QT Py and luminance sensor as per the [Adafruit guide](https://www.adafruit.com/product/4600).
2. Ensure all connections are properly established.
### Installing CircuitPython
1. Download the latest version of CircuitPython from [CircuitPython.org](https://circuitpython.org/board/qt_py_m0/).
2. Follow the guide to install CircuitPython on your Adafruit QT Py.
### Running the Testing Code
1. Clone or download the OLTT repository.
2. Upload the testing code to your Adafruit QT Py.
3. Detailed usage instructions can be found on [Go-EUC](https://www.go-euc.com/measuring-latency-with-adafruit-qt-py-a-circuitpython-approach/).
### Calibration Code
The calibration code is currently a work in progress. It will allow users to achieve more accurate and tailored measurements.
## Contributing
## Contributing to OLTT
We warmly welcome contributions from the community, especially those involved in End User Computing (EUC). Your insights, experiences, and perspectives are invaluable in making OLTT a more effective and versatile tool. Contributions are what make the open-source community such an amazing place to learn, inspire, and create. Any contributions you make to OLTT are **greatly appreciated**.
### Why Your Contribution Matters
As members of the EUC community, you understand the practical challenges and needs of managing and optimizing computing environments. Your hands-on experiences can greatly inform the development of OLTT, ensuring it meets real-world requirements and solves relevant problems.
### How You Can Contribute
1. **Providing Feedback and Ideas**: Share your insights on how OLTT can be more effectively used within EUC environments. Suggest features, improvements, or report issues.
2. **Writing Code**: Improve existing code or add new features. We value your technical contributions, whether it's refining the core functionality or enhancing user experience.
3. **Testing**: Help test the tool in different EUC scenarios and provide feedback on its performance.
4. **Writing Documentation**: Contribute to the project’s documentation to make it more comprehensive and user-friendly.
5. **Spreading the Word**: Advocate for OLTT within the EUC community. The more it's known and used, the more feedback and contributions we can gather.
Read our [CONTRIBUTING.md](https://github.com/eltjovangulik/OLTT/CONTRIBUTING.md) file for more information on making contributions. Don't hesitate to reach out if you have any questions or need guidance on where to start.
## License
Distributed under the MIT License. See `LICENSE.md` for more information.
## Disclaimer
### Personal Project
This is a personal project and is not affiliated with, sponsored by, or endorsed by my employer, Citrix Systems, Inc. The opinions and contributions are my own and not related to my position at Citrix.
### No Affiliation with NVIDIA
I would also like to clarify that I have no affiliation with NVIDIA Corporation. While Open Latency Tester Theia (OLTT) shares similar goals with tools like NVIDIA's LDAT (Latency Display Analysis Tool) in terms of measuring input latency, it is independently developed with no connection to NVIDIA's product.
This project aims to contribute to the community by providing an alternative, accessible tool for latency measurement. It should not be considered a replica or a 'ripoff' of NVIDIA's LDAT or any other commercial tool. Instead, it should be viewed as part of the broader ecosystem of tools that enable users to measure and optimize their computing and gaming experiences.
## Contact
Project Link: [https://github.com/eltjovangulik/OLTT](https://github.com/eltjovangulik/OLTT)
## Acknowledgements
- [Go-EUC](https://www.go-euc.com/)
- [Adafruit](https://www.adafruit.com/)
- [CircuitPython Community](https://circuitpython.org/) |
package runlog
import (
"errors"
"fmt"
"io"
"log"
"os"
"strings"
)
// 日志输出级别:0:fatal 1:error 2:warn 3:info 4:debug 5:trace
type DebugLevelCtrl int32
const (
DbgFatal DebugLevelCtrl = 0
DbgError DebugLevelCtrl = 1
DbgWarn DebugLevelCtrl = 2
DbgInfo DebugLevelCtrl = 3
DbgDebug DebugLevelCtrl = 4
DbgTrace DebugLevelCtrl = 5
)
// debug configuration
type DebugConf struct {
DbgLogFile string // 日志文件输出路径
DbgLevel DebugLevelCtrl // 输出日志最低级别,低于这个级别的不会输出
WithFunc bool // 日志末尾自动输出函数
WithFileLine bool // 日志末尾输出所在行
WithLongFile bool // 是否全文件名
WhiteTable bool // true:使用白名单,否则使用黑名单
Include []string //
includemap map[string]string // 白名单列表
BlackTable bool // 使用黑名单
Exclude []string
excludemap map[string]string // 黑名单列表
MaxAge int32 // 最长保留几天
RotationSize int64 // 日志切割大小,单位k
HistroyNum int32 // 被压缩的日志最多保留几个
Zip bool // 是否压缩历史日志
}
var dbgConf *DebugConf
var rwt *rotatewriter
func Init(c *DebugConf) error {
if len(c.DbgLogFile) < 5 {
return errors.New("logfile path required")
}
// 没有配置,默认7天
if c.MaxAge <= 0 {
c.MaxAge = 7
}
// 默认100M,这里的单位是k
if c.RotationSize <= 0 {
c.RotationSize = 102400
}
var writer io.Writer
if c.DbgLogFile == "stdout" {
writer = os.Stdout
} else {
idx := strings.LastIndex(c.DbgLogFile, "/")
_ = os.MkdirAll(c.DbgLogFile[:idx], 0755)
rw := &rotatewriter{
maxage: c.MaxAge,
rotateSize: c.RotationSize * 1024,
histroyNum: c.HistroyNum,
zip: c.Zip,
}
err := rw.Init(c.DbgLogFile)
if err != nil {
return err
}
writer = rw
rwt = rw
}
logflag := 0
if c.WithFileLine {
if c.WithLongFile {
logflag = log.LstdFlags | log.Llongfile
} else {
logflag = log.LstdFlags | log.Lshortfile
}
} else {
logflag = log.LstdFlags
}
logger = log.New(writer, "", logflag)
c.slice2map()
dbgConf = c
return nil
}
func (c *DebugConf) slice2map() {
if c.Include != nil {
c.includemap = make(map[string]string)
for _, v := range c.Include {
c.includemap[v] = ""
}
}
if c.Exclude != nil {
c.excludemap = make(map[string]string)
for _, v := range c.Exclude {
c.excludemap[v] = ""
}
}
}
func SetNewConf(c *DebugConf) {
if dbgConf.DbgLevel != c.DbgLevel {
Warn("dbg level changed %d --> %d", dbgConf.DbgLevel, c.DbgLevel)
}
c.slice2map()
dbgConf = c
}
func GetConf() *DebugConf {
return dbgConf
}
// debug调试输出,全部输出到标准输出,跑测试用例的时候适用
func SetupDebugRunlog() {
cf := &DebugConf{
DbgLogFile: "stdout",
DbgLevel: 5,
WithFunc: true,
WithFileLine: true,
}
err := Init(cf)
if err != nil {
fmt.Println(err.Error())
}
} |
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<style>
@import url('https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap');
</style>
</head>
<body>
<div class="container">
<!-- Title Section -->
<h1>Curious Gifter</h1>
<!-- Generate Button -->
<span class='start-btn'onclick="generateImage()">GENERATE</span>
<!-- Clear Button Section -->
<span class='start-btn'onclick="clearImages()">CLEAR</span>
<!-- Image Display Section -->
<div class="image-display" id="image-display">
<!-- <img id="generated-image" src="" alt="Generated Image"> -->
</div>
</div>
<!-- Icon Link -->
<a href="newpage.html">
<img class="icon" src="page content/openletter.png" alt="Icon">
</a>
<script>
function generateImage() {
var imageRepository = [
"gift images/image1.png",
"gift images/image2.png",
"gift images/image3.png",
"gift images/image4.png",
"gift images/image5.png",
"gift images/image6.png",
"gift images/image7.png",
"gift images/image8.png",
"gift images/image9.png",
"gift images/image10.png",
"gift images/image11.png",
"gift images/image12.png",
"gift images/image13.gif",
"gift images/image14.png",
// Add more image URLs here
];
// Randomize which image is chosen
var randomIndex = Math.floor(Math.random() * imageRepository.length);
// Get the generated image element
var generatedImage = document.getElementById("generated-image");
// Create a new image element for the generated image
var generatedImage = document.createElement("img");
generatedImage.src = imageRepository[randomIndex];
// Randomize the position of the generated image
var containerWidth = document.querySelector('.container').offsetWidth;
var containerHeight = document.querySelector('.container').offsetHeight;
var imageWidth = generatedImage.offsetWidth;
var imageHeight = generatedImage.offsetHeight;
// Calculate random positions within the window bounds
var randomLeft = Math.floor(Math.random() * (containerWidth - imageWidth));
var randomTop = Math.floor(Math.random() * (containerHeight - imageHeight));
// Apply the random positions to the generated image
generatedImage.style.left = randomLeft + 'px';
generatedImage.style.top = randomTop + 'px';
// Append the generated image to the image display section
var imageDisplay = document.getElementById("image-display");
imageDisplay.appendChild(generatedImage);
}
function clearImages() {
var imageDisplay = document.getElementById("image-display");
imageDisplay.innerHTML = "";
}
// Reposition the generated image if the window is resized
window.addEventListener('resize', generateImage);
</script>
</body>
</html> |
import { useEffect, useState } from "react";
import reactLogo from "./assets/react.svg";
import viteLogo from "/vite.svg";
import {Link} from 'react-router-dom'
import "./App.css";
import axios from "axios";
import Sekeleton from "./Components/Skeleton";
function App() {
window.document.title = "Qallam";
const [count, setCount] = useState(0);
const [Surahs, setSurahs] = useState(false);
const [Search, SetSearch] = useState(null);
function searchTerm(e) {
SetSearch(e.target.value);
}
useEffect(() => {
axios.get("https://equran.id/api/v2/surat").then((res) => {
setSurahs(res.data.data);
});
}, []);
return (
<div className="w-full">
<div className="dark:bg-gray-800 rounded text-center text-2xl text-slate-600 bg-slate-100 w-full p-4 font-semibold text-primary-green-light dark:text-slate-200 border border-green-500 dark:border-primary-green-dark">
بِسْــــــــــــــــــمِ اللهِ الرَّحْمَنِ الرَّحِيْمِ
</div>
<div className="mt-4">
<div className="mb-6">
<input
onKeyUp={searchTerm}
type="search"
id="email"
className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-none focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
placeholder="Cari surat"
required
/>
</div>
<div className="mt-3">
{Surahs ? (
<div className="flex flex-wrap">
{Surahs.map(function (x) {
return (
<div key={x.nomor} className="w-full md:w-1/2 lg:w-3/12 p-1">
<Link to={'surah/'+x.nomor}>
<div className="p-4 text-slate-500 text-slate-600 border border-green-500 bg-green-300 rounded dark:text-slate-200 hover:bg-primary-hover-light hover:dark:bg-primary-hover-dark">
<p className="dark:font-semibold">
{x.nomor}-{x.namaLatin}
</p>
<p className="text-right font-lateef font-semibold text-3xl">
{x.nama}
</p>
<p className="text-right text-sm mt-3">
{x.tempatTurun} • {x.arti}
</p>
</div>
</Link>
</div>
);
})}
</div>
) : (
<Sekeleton/>
)}
</div>
</div>
</div>
);
}
export default App; |
import axios from "axios";
import { xml2json, json2xml } from "xml-js";
import * as en from "../constants/errors/en";
import * as ja from "../constants/errors/ja";
import * as Encoding from "encoding-japanese";
const sha1 = require("sha1");
/**
* @interface XMLFieldData
* @property {string} _text - XML value
*/
export interface XMLFieldData {
_text: string;
}
/**
* @interface SoftbankResponse
* @property {XMLFieldData} [res_result]
* @property {XMLFieldData} [res_code]
* @property {XMLFieldData} [res_message]
* @property {XMLFieldData} [error_message]
*/
export interface SoftbankResponse {
res_result: XMLFieldData;
res_err_code: XMLFieldData;
res_date: XMLFieldData;
error?: any;
error_message?: string;
}
const configLocale: any = {
en: en,
ja: ja,
};
/**
* @enum {string}
* @property {string} EN - en
* @property {string} JA - ja
*/
export enum Locale {
EN = "en",
JA = "ja",
}
export enum ResultText {
NG = "NG",
OK = "OK",
}
/**
* @constructor
* @param {string} endpoint Softbank API endpoint
* @param {string} merchantId Softbank API merchant ID
* @param {string} serviceId Softbank API service ID
* @param {string} hashKey Softbank API hash key
* @param {string} locale Softbank API locale
*/
export class SoftbankService {
public endpoint: string;
public merchantId: string;
public serviceId: string;
public hashKey: string;
public locale: Locale;
public debug = false;
public requestId = {
CREATE_CUSTOMER_REQUEST: "MG02-00101-101",
UPDATE_CUSTOMER_REQUEST: "MG02-00102-101",
CREATE_CUSTOMER_TOKEN_REQUEST: "MG02-00131-101",
UPDATE_CUSTOMER_TOKEN_REQUEST: "MG02-00132-101",
DELETE_CUSTOMER_REQUEST: "MG02-00103-101",
GET_CUSTOMER_REQUEST: "MG02-00104-101",
CREATE_TRANSACTION_REQUEST: "ST01-00131-101",
CONFIRM_TRANSACTION_REQUEST: "ST02-00101-101",
PURCHASE_REQUEST: "ST02-00201-101",
REFUND_REQUEST: "ST02-00303-101",
};
constructor(
endpoint: string,
merchantId: string,
serviceId: string,
hashKey: string,
locale: Locale = Locale.EN,
debug = false
) {
this.endpoint = endpoint;
this.merchantId = merchantId;
this.hashKey = hashKey;
this.serviceId = serviceId;
this.locale = locale;
this.debug = debug;
if (this.debug) {
console.log(
"SBPS Debug init: ",
endpoint,
merchantId,
hashKey,
serviceId,
locale,
debug
);
}
}
/**
* @function generateHashCode
* @memberof SoftbankService
* @param {string[]} args
* @returns string
*/
public generateHashCode(...args: string[]): string {
if (this.locale === Locale.JA) {
const unicodeArray = Encoding.stringToCode(
`${this.merchantId}${this.serviceId}${args.join("")}${
this.hashKey
}`
);
return sha1(
Encoding.convert(unicodeArray, {
to: "SJIS",
from: "UNICODE",
})
);
}
return sha1(
`${this.merchantId}${this.serviceId}${args.join("")}${this.hashKey}`
);
}
private parseMessageError(errorCode: string) {
const paymentMethodErrCode = errorCode.slice(0, 3);
const paymentTypeErrCode = errorCode.slice(3, 5);
const paymentItemErrCode = errorCode.slice(5, 9);
const paymentMethodErr =
configLocale[this.locale].paymentMethod[paymentMethodErrCode] || "";
let paymentTypeErr = "";
let paymentItemErr = "";
if (configLocale[this.locale].paymentTypeError[paymentMethodErrCode]) {
paymentTypeErr =
configLocale[this.locale].paymentTypeError[
paymentMethodErrCode
][paymentTypeErrCode] || "";
}
if (configLocale[this.locale].paymentItemError[paymentItemErrCode]) {
paymentItemErr =
configLocale[this.locale].paymentItemError[
paymentItemErrCode
] || "";
} else if (
configLocale[this.locale].paymentItemError[paymentMethodErrCode]
) {
paymentItemErr =
configLocale[this.locale].paymentItemError[
paymentMethodErrCode
][paymentItemErrCode] || "";
}
return `${paymentMethodErr} ${paymentTypeErr} ${paymentItemErr}`;
}
public async request(data: any): Promise<any> {
try {
if (this.debug) {
console.log("SBPS Debug payload: ", data);
}
const result = await axios.post(
this.endpoint,
json2xml(JSON.stringify(data), { compact: true }),
{
auth: {
username: this.merchantId + this.serviceId,
password: this.hashKey,
},
headers: {
"Content-Type": "application/xml",
},
}
);
const parseDataString = xml2json(result.data, { compact: true });
const parseData = JSON.parse(parseDataString || "{}");
if (!parseData["sps-api-response"]) {
throw new Error("No response from Softbank API");
}
if (parseData["sps-api-response"].res_result._text === "NG") {
return {
...parseData["sps-api-response"],
error_message: this.parseMessageError(
parseData["sps-api-response"].res_err_code._text
),
};
}
return parseData["sps-api-response"];
} catch (error) {
return {
res_result: {
_text: "NG",
},
res_err_code: {
_text: "0000000",
},
error: error,
error_message: this.parseMessageError("0000000"),
};
}
}
} |
import React from "react";
import Input from "../../../components/UI/Input";
import Modal from "../../../components/UI/Modal";
import { Row, Col } from "react-bootstrap";
const AddCateogryModal = (props) => {
const {
show,
handleClose,
onSubmit,
categoryList,
modelTitle,
setCategoryName,
setParentCategoryId,
parentCategoryId,
categoryName,
handleCategoryImage,
} = props;
return (
<Modal show={show} handleClose={handleClose} onSubmit={onSubmit} modelTitle={modelTitle}>
<Row>
<Col>
<Input
placeholder={"Cateogory Name"}
value={categoryName}
onChange={(e) => setCategoryName(e.target.value)}
className="form-control-sm"
/>
</Col>
<Col>
<select
className="form-control form-control-sm"
value={parentCategoryId}
onChange={(e) => setParentCategoryId(e.target.value)}
>
<option>Select category</option>
{categoryList.map((option) => (
<option key={option.name} value={option.value}>
{option.name}
</option>
))}
</select>
</Col>
</Row>
<Row>
<Col>
<input type="file" name="categoryImage" onChange={handleCategoryImage} />
</Col>
</Row>
</Modal>
);
};
export default AddCateogryModal; |
package file
import java.io.File
public class TestFile{
public static void main(String[] args) {
// 绝对路径
File f1 = new File("d:/LOLFolder");
System.out.println("f1的绝对路径:" + f1.getAbsolutePath());
// 相对路径,相对于工作目录,如果在eclipse中,就是项目目录
File f2 = new File("LOL.exe");
System.out.println("f2的绝对路径:" + f2.getAbsolutePath());
// 把f1作为父目录创建文件对象
File f3 = new File(f1, "LOL.exe");
System.out.println("f3的绝对路径:" + f3.getAbsolutePath());
}
}
文件的常用方法1、
ackage file;
import java.io.File;
import java.util.Date;
public class TestFile {
public static void main(String[] args) {
File f = new File("d:/LOLFolder/LOL.exe");
System.out.println("当前文件是:" +f);
//文件是否存在
System.out.println("判断是否存在:"+f.exists());
//是否是文件夹
System.out.println("判断是否是文件夹:"+f.isDirectory());
//是否是文件(非文件夹)
System.out.println("判断是否是文件:"+f.isFile());
//文件长度
System.out.println("获取文件的长度:"+f.length());
//文件最后修改时间
long time = f.lastModified();
Date d = new Date(time);
System.out.println("获取文件的最后修改时间:"+d);
//设置文件修改时间为1970.1.1 08:00:00
f.setLastModified(0);
//文件重命名
File f2 =new File("d:/LOLFolder/DOTA.exe");
f.renameTo(f2);
System.out.println("把LOL.exe改名成了DOTA.exe");
System.out.println("注意: 需要在D:\\LOLFolder确实存在一个LOL.exe,\r\n才可以看到对应的文件长度、修改时间等信息");
}
}
文件常用方法2
package file;
import java.io.File;
import java.io.IOException;
public class TestFile {
public static void main(String[] args) throws IOException {
File f = new File("d:/LOLFolder/skin/garen.ski");
// 以字符串数组的形式,返回当前文件夹下的所有文件(不包含子文件及子文件夹)
f.list();
// 以文件数组的形式,返回当前文件夹下的所有文件(不包含子文件及子文件夹)
File[]fs= f.listFiles();
// 以字符串形式返回获取所在文件夹
f.getParent();
// 以文件形式返回获取所在文件夹
f.getParentFile();
// 创建文件夹,如果父文件夹skin不存在,创建就无效
f.mkdir();
// 创建文件夹,如果父文件夹skin不存在,就会创建父文件夹
f.mkdirs();
// 创建一个空文件,如果父文件夹skin不存在,就会抛出异常
f.createNewFile();
// 所以创建一个空文件之前,通常都会创建父目录
f.getParentFile().mkdirs();
// 列出所有的盘符c: d: e: 等等
f.listRoots();
// 刪除文件
f.delete();
// JVM结束的时候,刪除文件,常用于临时文件的删除
f.deleteOnExit();
}
}
什么是流?
什么是流(Stream),流就是一系列的数据
当不同的介质之间有数据交互的时候,JAVA就使用流来实现。
数据源可以是文件,还可以是数据库,网络甚至是其他的程序
比如读取文件的数据到程序中,站在程序的角度来看,就叫做输入流
输入流: InputStream
输出流:OutputStream
文件输入流
package stream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class TestStream {
public static void main(String[] args) {
try {
File f = new File("d:/lol.txt");
// 创建基于文件的输入流
FileInputStream fis = new FileInputStream(f);
// 通过这个输入流,就可以把数据从硬盘,读取到Java的虚拟机中来,也就是读取到内存中
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
字节流:
InputStream字节输入流
OutputStream字节输出流
用于以字节的形式读取和写入数据
nputStream是字节输入流,同时也是抽象类,只提供方法声明,不提供方法的具体实现。
FileInputStream 是InputStream子类,以FileInputStream 为例进行文件读取
package stream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class TestStream {
public static void main(String[] args) {
try {
//准备文件lol.txt其中的内容是AB,对应的ASCII分别是65 66
File f =new File("d:/lol.txt");
//创建基于文件的输入流
FileInputStream fis =new FileInputStream(f);
//创建字节数组,其长度就是文件的长度
byte[] all =new byte[(int) f.length()];
//以字节流的形式读取文件所有内容
fis.read(all);
for (byte b : all) {
//打印出来是65 66
System.out.println(b);
}
//每次使用完流,都应该进行关闭
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
OutputStream是字节输出流,同时也是抽象类,只提供方法声明,不提供方法的具体实现。
FileOutputStream 是OutputStream子类,以FileOutputStream 为例向文件写出数据
注: 如果文件d:/lol2.txt不存在,写出操作会自动创建该文件。
但是如果是文件 d:/xyz/lol2.txt,而目录xyz又不存在,会抛出异常
package stream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class TestStream {
public static void main(String[] args) {
try {
// 准备文件lol2.txt其中的内容是空的
File f = new File("d:/lol2.txt");
// 准备长度是2的字节数组,用88,89初始化,其对应的字符分别是X,Y
byte data[] = { 88, 89 };
// 创建基于文件的输出流
FileOutputStream fos = new FileOutputStream(f);
// 把数据写入到输出流
fos.write(data);
// 关闭输出流
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
关闭流:
所有的流,无论是输入流还是输出流,使用完毕之后,都应该关闭。 如果不关闭,会产生对资源占用的浪费。 当量比较大的时候,会影响到业务的正常开展。
1、在try中关闭
在try的作用域里关闭文件输入流,在前面的示例中都是使用这种方式,这样做有一个弊端;
如果文件不存在,或者读取的时候出现问题而抛出异常,那么就不会执行这一行关闭流的代码,存在巨大的资源占用隐患。 不推荐使用
package stream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class TestStream {
public static void main(String[] args) {
try {
File f = new File("d:/lol.txt");
FileInputStream fis = new FileInputStream(f);
byte[] all = new byte[(int) f.length()];
fis.read(all);
for (byte b : all) {
System.out.println(b);
}
// 在try 里关闭流
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2、在finally中关闭
这是标准的关闭流的方式
1. 首先把流的引用声明在try的外面,如果声明在try里面,其作用域无法抵达finally.
2. 在finally关闭之前,要先判断该引用是否为空
3. 关闭的时候,需要再一次进行try catch处理
这是标准的严谨的关闭流的方式,但是看上去很繁琐,所以写不重要的或者测试代码的时候,都会采用上面的有隐患try的方式,因为不麻烦~
package stream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class TestStream {
public static void main(String[] args) {
File f = new File("d:/lol.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
byte[] all = new byte[(int) f.length()];
fis.read(all);
for (byte b : all) {
System.out.println(b);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 在finally 里关闭流
if (null != fis)
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
步骤 3 : 使用try()的方式
把流定义在try()里,try,catch或者finally结束的时候,会自动关闭
这种编写代码的方式叫做 try-with-resources, 这是从JDK7开始支持的技术
所有的流,都实现了一个接口叫做 AutoCloseable,任何类实现了这个接口,都可以在try()中进行实例化。 并且在try, catch, finally结束的时候自动关闭,回收相关资源。
package stream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class TestStream {
public static void main(String[] args) {
File f = new File("d:/lol.txt");
//把流定义在try()里,try,catch或者finally结束的时候,会自动关闭
try (FileInputStream fis = new FileInputStream(f)) {
byte[] all = new byte[(int) f.length()];
fis.read(all);
for (byte b : all) {
System.out.println(b);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
字节流
Reader字符输入流
Writer字符输出流
专门用于字符的形式读取和写入数据
使用字符流读取文件
FileReader 是Reader子类,以FileReader 为例进行文件读取
package stream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class TestStream {
public static void main(String[] args) {
// 准备文件lol.txt其中的内容是AB
File f = new File("d:/lol.txt");
// 创建基于文件的Reader
try (FileReader fr = new FileReader(f)) {
// 创建字符数组,其长度就是文件的长度
char[] all = new char[(int) f.length()];
// 以字符流的形式读取文件所有内容
fr.read(all);
for (char b : all) {
// 打印出来是A B
System.out.println(b);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
使用字符流把字符串写入到文件
FileWriter 是Writer的子类,以FileWriter 为例把字符串写入到文件
package stream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class TestStream {
public static void main(String[] args) {
// 准备文件lol2.txt
File f = new File("d:/lol2.txt");
// 创建基于文件的Writer
try (FileWriter fr = new FileWriter(f)) {
// 以字符流的形式把数据写入到文件中
String data="abcdefg1234567890";
char[] cs = data.toCharArray();
fr.write(cs);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
缓存流
以介质是硬盘为例,字节流和字符流的弊端:
在每一次读写的时候,都会访问硬盘。 如果读写的频率比较高的时候,其性能表现不佳。
为了解决以上弊端,采用缓存流。
缓存流在读取的时候,会一次性读较多的数据到缓存中,以后每一次的读取,都是在缓存中访问,直到缓存中的数据读取完毕,再到硬盘中读取。
就好比吃饭,不用缓存就是每吃一口都到锅里去铲。用缓存就是先把饭盛到碗里,碗里的吃完了,再到锅里去铲
缓存流在写入数据的时候,会先把数据写入到缓存区,直到缓存区达到一定的量,才把这些数据,一起写入到硬盘中去。按照这种操作模式,就不会像字节流,字符流那样每写一个字节都访问硬盘,从而减少了IO操作 |
use binrw::{binwrite, io::Cursor, BinWriterExt};
#[test]
fn assert_fail() {
#[binwrite]
struct Test {
#[bw(assert(*x != 1, "x cannot be 1"))]
x: u32,
}
let mut x = Cursor::new(Vec::new());
if let Err(err) = x.write_be(&Test { x: 1 }) {
assert!(matches!(err, binrw::Error::AssertFail { .. }));
} else {
panic!("Assert error expected");
}
}
#[test]
fn top_level_assert_fail() {
#[binwrite]
#[bw(assert(*x != 1, "x cannot be 1"))]
struct Test {
x: u32,
}
let mut x = Cursor::new(Vec::new());
if let Err(err) = x.write_be(&Test { x: 1 }) {
assert!(matches!(err, binrw::Error::AssertFail { .. }));
} else {
panic!("Assert error expected");
}
}
#[test]
fn top_level_assert_self_enum() {
#[binwrite]
#[bw(assert(!matches!(self, Test::A(1))))]
#[derive(PartialEq)]
enum Test {
A(u32),
}
let mut x = Cursor::new(Vec::new());
if let Err(err) = x.write_be(&Test::A(1)) {
assert!(matches!(err, binrw::Error::AssertFail { .. }));
} else {
panic!("Assert error expected");
}
}
#[test]
fn assert_enum_variant() {
#[binwrite]
#[derive(PartialEq)]
enum Test {
#[bw(assert(self_0 != &1))]
A(u32),
}
let mut x = Cursor::new(Vec::new());
if let Err(err) = x.write_be(&Test::A(1)) {
assert!(matches!(err, binrw::Error::AssertFail { .. }));
} else {
panic!("Assert error expected");
}
}
#[test]
fn top_level_assert_self_struct() {
#[binwrite]
#[bw(assert(self != &Test(1)))]
#[derive(PartialEq)]
struct Test(u32);
let mut x = Cursor::new(Vec::new());
if let Err(err) = x.write_be(&Test(1)) {
assert!(matches!(err, binrw::Error::AssertFail { .. }));
} else {
panic!("Assert error expected");
}
} |
// Protocol Buffers - Google's data interchange format
// Copyright 2023 Google LLC. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google LLC nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef UPB_TEST_FUZZ_UTIL_H_
#define UPB_TEST_FUZZ_UTIL_H_
#include <string>
#include <vector>
#include "upb/mini_table/extension_registry.h"
// #include "upb/mini_table/types.h"
namespace upb {
namespace fuzz {
struct MiniTableFuzzInput {
// MiniDescripotrs for N messages, in the format accepted by
// upb_MiniTable_Build().
std::vector<std::string> mini_descriptors;
// MiniDescripotrs for N enums, in the format accepted by
// upb_MiniTableEnum_Build().
std::vector<std::string> enum_mini_descriptors;
// A MiniDescriptor for N extensions, in the format accepted by
// upb_MiniTableExtension_Build().
std::string extensions;
// Integer indexes into the message or enum mini tables lists. These specify
// which message or enum to use for each sub-message or enum field. We mod
// by the total number of enums or messages so that any link value can be
// valid.
std::vector<uint32_t> links;
};
// Builds an arbitrary mini table corresponding to the random data in `input`.
// This function should be capable of producing any mini table that can
// successfully build, and any topology of messages and enums (including
// cycles).
//
// As currently written, it effectively fuzzes the mini descriptor parser also,
// and can therefore trigger any bugs in that parser. To better isolate these
// two, we may want to change this implementation to use the mini descriptor
// builder API so we are producing mini descriptors in a known good format. That
// would mostly eliminate the chance of crashing the mini descriptor parser
// itself.
//
// TODO: maps. If we give maps some space in the regular encoding instead of
// using a separate function, we could get that for free.
const upb_MiniTable* BuildMiniTable(const MiniTableFuzzInput& input,
upb_ExtensionRegistry** exts,
upb_Arena* arena);
} // namespace fuzz
} // namespace upb
#endif // UPB_TEST_FUZZ_UTIL_H_ |
import * as React from 'react';
import './CustomDataGrid.css'
import { DataGrid } from '@mui/x-data-grid';
const defaultColumns = [
{ field: 'id', headerName: 'ID', width: 90 },
{
field: 'firstName',
headerName: 'First name',
width: 150,
editable: true,
},
{
field: 'lastName',
headerName: 'Last name',
width: 150,
editable: true,
},
{
field: 'age',
headerName: 'Age',
type: 'number',
width: 110,
editable: true,
},
{
field: 'fullName',
headerName: 'Full name',
description: 'This column has a value getter and is not sortable.',
sortable: false,
width: 160,
valueGetter: (params) =>
`${params.row.firstName || ''} ${params.row.lastName || ''}`,
}
];
const defaultRows = [
{ id: 1, lastName: 'Snow', firstName: 'Jon', age: 25 },
{ id: 2, lastName: 'Lannister', firstName: 'Cersei', age: 42 },
{ id: 3, lastName: 'Lannister', firstName: 'Jaime', age: 45 },
{ id: 4, lastName: 'Stark', firstName: 'Arya', age: 16 },
{ id: 5, lastName: 'Targaryen', firstName: 'Daenerys', age: 10 },
{ id: 6, lastName: 'Melisandre', firstName: 'Jotaro', age: 150 },
{ id: 7, lastName: 'Clifford', firstName: 'Ferrara', age: 44 },
{ id: 8, lastName: 'Frances', firstName: 'Rossini', age: 36 },
{ id: 9, lastName: 'Roxie', firstName: 'Harvey', age: 65 },
];
const gridStyle = {
"&.MuiDataGrid-root .MuiDataGrid-cell:focus-within": {
outline: "none !important",
}
}
export default function CustomDataGrid({ columns = defaultColumns , rows = defaultRows }) {
return (
<DataGrid
rows={rows}
columns={columns}
className='custom-row'
initialState={{
pagination: {
paginationModel: {
pageSize: 5,
},
},
}}
getRowId={(row) => row._id}
pageSizeOptions={[5]}
disableRowSelectionOnClick
sx={{ borderRadius : '8px' , padding : '10px 30px' , ...gridStyle }}
getRowClassName={( params ) => 'custom-data-grid-row' }
/>
)
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.