Developers can use these components to create functionalities such as UI controls, interactions, gestures, animations, and a lot more. Each open-source UI component can have its own unique style and different levels of support for modifications and implementation. However, if you pair the framework with some JavaScript plugins, the possibilities could be endless.
Popular New Releases in User Interface
vue
react
18.0.0 (March 29, 2022)
bootstrap
4.6.1
react-native
0.68.1
create-react-app
v5.0.1
Popular Libraries in User Interface
by vuejs javascript
192954
MIT
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
by facebook javascript
186685
MIT
A declarative, efficient, and flexible JavaScript library for building user interfaces.
by twbs javascript
156587
MIT
The most popular HTML, CSS, and JavaScript framework for developing responsive, mobile first projects on the web.
by facebook javascript
102222
NOASSERTION
A framework for building native applications using React
by facebook javascript
94434
MIT
Set up a modern web app by running one command.
by vercel javascript
85621
MIT
The React Framework
by mrdoob javascript
80965
MIT
JavaScript 3D Library.
by mui-org javascript
75241
MIT
MUI (formerly Material-UI) is the React UI library you always wanted. Follow your own design system, or start with Material Design.
by animate-css css
74293
NOASSERTION
🍿 A cross-browser library of CSS animations. As easy to use as an easy thing.
Trending New libraries in User Interface
by vitejs typescript
40832
MIT
Next generation frontend tooling. It's fast!
by withfig typescript
16522
MIT
Fig adds autocomplete to your terminal.
by facebookexperimental javascript
16419
MIT
Recoil is an experimental state management library for React apps. It provides several capabilities that are difficult to achieve with React alone, while being compatible with the newest features of React.
by type-challenges typescript
16090
MIT
Collection of TypeScript type challenges with online judge
by tailwindlabs javascript
14454
MIT
A set of free MIT-licensed high-quality SVG icons for UI development.
by tailwindlabs typescript
14223
MIT
Completely unstyled, fully accessible UI components, designed to integrate beautifully with Tailwind CSS.
by remotion-dev typescript
12674
NOASSERTION
🎥 Create videos programmatically in React
by pavlobu typescript
12515
AGPL-3.0
Deskreen turns any device with a web browser into a secondary screen for your computer
by rustdesk rust
11657
GPL-3.0
Yet another remote desktop software
Top Authors in User Interface
1
188 Libraries
196712
2
184 Libraries
48576
3
183 Libraries
5728
4
102 Libraries
3425
5
100 Libraries
8163
6
99 Libraries
21316
7
98 Libraries
24945
8
92 Libraries
5387
9
88 Libraries
272
10
85 Libraries
119528
1
188 Libraries
196712
2
184 Libraries
48576
3
183 Libraries
5728
4
102 Libraries
3425
5
100 Libraries
8163
6
99 Libraries
21316
7
98 Libraries
24945
8
92 Libraries
5387
9
88 Libraries
272
10
85 Libraries
119528
Trending Kits in User Interface
Gulp-typescript is a plugin which allows you to convert your Typescript code into JavaScript. It can serve as an alternative to TypeScript compiler.
This kandi kit for Candy Crush (one of the most popular games), has been rewritten using the Phaser HTML5 game engine along with Typescript language. AngularJs is also used for creating game directives, so they can be easily included in the angular app.
Gulp is a streaming build system which can run tasks in sequence or parallel. Gulp-typescript is a plugin which allows you to convert your Typescript code into JavaScript. It can also serve as an alternative to TypeScript compiler if you don’t want all the features it provides (like support for external modules, rich IDE support). Gulp-concat is used to concatenate files together. Gulp-clean-css is used to remove comments from your CSS code.
The most important part of building a game like Candy Crush is to have a solid workflow. We have used TypeScript, Gulp and Webpack and built a fully-functional Candy Crush game. We'll be using TypeScript, Gulp and Webpack to build a fully-functional Candy Crush game. kandi kit provides you with a fully deployable Candy Crush app. Source code included so that you can customize it for your requirement.
Troubleshooting
- While running batch file, if you encounter Windows protection alert, select More info --> Run anyway
- During kit installer, if you encounter Windows security alert, click Allow
- While executing 'start http://localhost:3000 && gulp start' command, if you encounter browser-sync issue, go to default-config.js file, which will be under node_modules\browser-sync\dist directory and set property open to false without any quotes.
- While running batch file, if you encounter npm not recognized error, re-run the batch file.
- If you face any issues while running the candy crush app, reduce the node version to 10.24.1
For a detailed tutorial on installing & executing the solution as well as learning resources including training & certification opportunities, please visit the OpenWeaver Community
Development Environment
Visual Studio Code is a source-code editor made by Microsoft for Windows, Linux, and macOS. Features include support for debugging, syntax highlighting, intelligent code completion, snippets, code refactoring, and embedded Git.
Runtime Environment
Node.js is an open-source, cross-platform, JavaScript runtime environment. It executes JavaScript code outside of a browser.
JavaScript Libraries
The following libraries provide flexibility to automate slow, and redundant workflows efficiently.
Support
If you need help using this kit, you may reach us at the OpenWeaver Community.
Google maps is a powerful and complex application. To integrate it into the React app “google-map-react” package is used. Any React component on Google Maps can be rendered by this package, which is a component written atop a tiny portion of the Google Maps API. It is actively maintained and simple enough to use. It is entirely isomorphic. Even without the Google Maps API being loaded, it can render map components in the browser. Every item on the map may be hovered using an internal, adjustable hover algorithm.
Since google-map-react allows the user to render any React component on the map, a specific component can be designed that shows a pin icon and text. One can use Iconify library (a collection of free SVG icons) for the icons.
One should be aware of a few prerequisites for the purpose:
- JavaScript ES6
- Searching for Location in Google Map
- React.js library
To know more about the integration of Google Maps, refer to the code given below.
Fig 1: Preview of the output that you will get on running this code from your IDE.
Code
In this solution we're using React library.
Instructions
Follow the steps carefully to get the output easily.
- Install the Node.js and React on your IDE(preferable Visual Studio Code).
- Create React Application using npx create-react-app foldername.
- cd foldername.
- Open the folder in IDE.
- Copy the code using "copy" button above and paste it in app.js file(remove the earlier code from app.js).
- Open the terminal from IDE.
- npm start to run the file.
Note: Create your own API KEY and paste it in the place of 'YOUR_API_KEY' in the code snippet.
I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.
I found this code snippet by searching for "how to embed an exact place in google map in Reactjs" in kandi. You can try any such use case!
Environment Tested
I tested this solution in the following versions. Be mindful of changes when working with other versions.
- The solution is created in Visual Studio Code 1.73.1.
- The solution is tested on node v18.12.1 and npm v8.19.2.
- React version-18.2.0.
Using this solution, we are able to embed an place in google map with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to embed an exact place in google map in Reactjs.
Dependent Libraries
You can also search for any dependent library on kandi like 'react'.
Support
- For any support on kandi solution kits, please use the chat
- For further learning resources, visit the Open Weaver Community learning page.
A color picker is another application of react that enables the users to pick colors from a palette or a color wheel. In online applications, color pickers are frequently used for tasks like choosing a text color, a background color, or a color for a graphical element. React color picker components are provided by several libraries, including react-color and react-color-picker.
- react-color-picker: This library provides components that enable the users to include a color- choosing interface in their application.
- react-color: A wide range of color picker components, including SketchPicker, ChromePicker, and HuePicker, are included in this library.
react-color is a more comprehensive library that includes a variety of color picker components with different styles unlike react-color-picker, which is a much simpler library, including a single-color picker component, and customization options are provided by props. There are several more props available for modifying the default color, the format of the selected color, and the layout of the color picker, among other aspects of the ColorPicker component's look and performance.
For more information about customizing color picker in React, refer to the code given below
Fig : Preview of the output that you will get on running this code from your IDE.
Code
In this solution we're using React and Styled-components library.
Instructions
Follow the steps carefully to get the output easily.
- Install the Node.js and React on your IDE(preferable Visual Studio Code).
- Create React Application using npx create-react-app foldername.
- cd foldername.
- Install npm i styled-components.
- Open the folder in IDE.
- Copy the code using "copy" button above and paste it in app.js file(remove the earlier code from app.js) and refer demo for styles.css file.
- Open the terminal from IDE.
- npm start to run the file.
You can also refer this url 'DEMO' for getting the above output.
I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.
I found this code snippet by searching for 'create color picker in react' in kandi. You can try any such use case!
Environment Tested
I tested this solution in the following versions. Be mindful of changes when working with other versions.
- The solution is created in Visual Studio Code 1.73.1.
- The solution is tested on node v18.12.1 and npm v8.19.2.
- React version-18.2.0.
- Styled-components version-6.0.0.
Using this solution, we are able to customize color picker in React with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to customize color picker in React.
Dependent Library
You can also search for any dependent libraries on kandi like 'react' and 'styled-components'.
Support
- For any support on kandi solution kits, please use the chat
- For further learning resources, visit the Open Weaver Community learning page.
Use the react-player or video-react libraries to integrate a YouTube video into a React project. React Player allows you to embed audio and video players.
It supports various media kinds and sources, including YouTube, Vimeo, SoundCloud, and local files, and offers a straightforward, programmable interface for playing media files. Another library for playing audio and video in React applications is called Video-React. It offers comparable user experience for manipulating audio and video players in your React components and is built on top of the well-known video.js package. Like React Player, Video-react offers support for various media formats and sources. With a large user base and vibrant developer communities, React Player and Video-react are well-liked choices for integrating audio and video features into React apps. Consider each library's features and options, the level of customization and control you require, and the compatibility and integration with other tools and libraries you are using when choosing which library to employ in your project.
Here is an example of how you embed a YouTube video into a React project:
Fig 1: Preview of the output that you will get on running this code from your IDE.
Code
In this solution we're using React and ReactPlayer libraries.
Instructions
Follow the steps carefully to get the output easily.
- Install the Node.js and React on your IDE(preferable Visual Studio Code).
- Create React Application using npx create-react-app foldername.
- cd foldername.
- Install npm install react-player.
- Open the folder in IDE.
- Copy the code using "copy" button above and paste it in app.js file(remove the earlier code from app.js).
- Remove the first line(import statement).
- Import React library by using the command -> import React from 'react';
- Import ReactPlayer library by using the command -> import ReactPlayer from 'react-player';
- Replace ReactVideo as ReactPlayer which is present inside the div tag.
- Open the terminal from IDE.
- npm start to run the file.
I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.
I found this code snippet by searching for 'youtube video on react page' in kandi. You can try any such use case!
Environment Tested
I tested this solution in the following versions. Be mindful of changes when working with other versions.
- The solution is created in Visual Studio Code 1.73.1.
- The solution is tested on node v18.12.1 and npm v8.19.2.
- React version-18.2.0.
- ReactPlayer version: current.
Using this solution, we are able to create an youtube video on react page with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to create an youtube video on react page.
Dependent Libraries
You can also search for any dependent libraries on kandi like 'react' and 'react-player'.
Support
- For any support on kandi solution kits, please use the chat
- For further learning resources, visit the Open Weaver Community learning page.
JavaScript libraries are collections of pre-written code that can be used to create web applications. They provide functions, features, and resources.
It makes the development process faster and easier They often create dynamic, interactive experiences on websites and applications. JavaScript libraries are used for various tasks, such as DOM manipulation, AJAX requests, data analysis and visualization, client-side storage, and more. It includes Creating Interactive Tours, Enhancing Customer Experience, Creating Interactive Tutorials, and Improving User Onboarding.
Let us look at some of these famous libraries.
webpack
- Offers advanced features such as code-splitting, hot module replacement (HMR), tree-shaking, and dynamic loading.
- Provides plugins and loaders that can be used to customize how code is transformed and bundled.
- Allows to combine multiple modules into a single bundle.
mocha
- Provides an asynchronous testing interface.
- Supports a wide variety of testing styles with its flexible syntax.
- Allows developers to create custom test interfaces and reporters.
intro.js
- Supports auto-scroll and scroll-hijacking.
- Allows developers to create custom tours in any language.
- Provides a modern and lightweight interface, with a minimalistic design.
bower
- Supports versioning and resolution of dependencies.
- Provides command line interface making it easy to instantly search, install, and manage packages in a project.
- Allows to manage both front-end and back-end packages.
grunt
- Provides wide range of plugins and third-party integrations.
- Provides built-in support for popular frameworks and libraries.
- Allows developers to easily configure and create tasks for automating common development workflows.
knockout
- Provides an easy-to-use two-way data-binding system.
- Provides a powerful templating system that makes it easy to display complex data structures.
- Provides a declarative binding syntax that simplifies linking the data to the HTML elements on the page.
shepherd
- Allows developers to create step-by-step product tours and walkthroughs intuitively.
- Provides options for targeting specific users, including localization and different themes.
- Supports integration with other libraries and frameworks, such as React and Vue.
mixitup
- Provides built-in support for powerful animation effects.
- Allows developers to create custom sorting and filtering rules.
- Supports integration with external API's, allowing pulling in data from other sources.
hopscotch
- Is highly accessible, i.e., it is easy for people with disabilities to use.
- Offers comprehensive documentation, making it easy for developers to get up and running quickly.
- Is device-agnostic, meaning it works across different devices and browsers.
joyride
- Provides a built-in feature called “Progress Indicator,” which allows the user to see their progress through the tour.
- A built-in analytics system provides valuable insights into how users interact with the tour.
- Allows developers to easily add triggers and custom CSS to enhance the user experience.
3D graphics are becoming increasingly important, enabling developers to build immersive and interactive user experiences.
JavaScript has evolved as a popular language for creating such events. These libraries enable a wide range of applications, including gaming, e-commerce, education, and more, and content from Three.js, widely regarded as the industry standard for browser-based 3D graphics, to Babylon.js, which provides a powerful game engine and physics system, to PlayCanvas, which enables collaborative, browser-based game development.
Here are 8 of the best JavaScript 3D libraries 2023 developers can use for an immersive 3D experience.
Three.js:
- Shows 3D-printed object previews.
- Helps create virtual concerts and events.
- Helpful in product animations for marketing.
Babylon.js:
- Helps in product design and prototyping.
- Helps do virtual makeup try-on.
- Allows 3D printing model creation and optimization.
cesium:
- Helpful in real-time traffic monitoring and visualization.
- Helps in weather and environmental monitoring.
- Helps monitor geospatial data and provides its analysis and visualization.
Whs.js:
- Helps create interactive virtual art galleries.
- Shows 3D product catalogs and configurators for fashion.
- Helps in virtual reality amusement park rides.
Cannon.js:
- Helps with physics-based interactive educational videos.
- Helps create interactive roller coaster and amusement park ride simulations.
- Allows collaborative remote prototyping for mechanical engineering.
Physics.js:
- Creates interactive kinetic art installations.
- Helps create physics-based educational games for kids.
- Helps create interactive science museum exhibits.
PlayCanvas-ar:
- Helps in collaborative remote design and prototyping.
- Helps do 3D product customization and personalization.
- Has immersive language learning simulations.
Turbulenz_jslib:
- Helps in interactive educational simulations for mathematics and statistics.
- Creates virtual reality art galleries.
- Allows immersive virtual reality movie theaters.
We can create any animation with suitable libraries or combinations of libraries that are well-known for their functionalities using Python Animation Libraries. For developers looking for options with less complex code with maximum customization options, users can customize their plots and designs depending on their preferences.
Choosing a suitable library plays a key role in any machine learning or data science project, and we should do it properly to avoid other related issues which may arise. Some libraries offer an interactive plot to attract playing with the graph and visualize it uniquely. It will allow you to edit videos, create animations, and create a map or geological animations where we can analyze the geological data.
Here is the list of handpicked 18 best Python Animation Libraries in 2023 which will help you with your animation requirements:
manim - 3b1b
- Is a Python library for creating mathematical animations and educational videos that Grant Sanderson develops.
- Is an open source library that allows users to create high-quality animations which visualize mathematical concepts like animations of graphs, functions, fractals, and more.
- Uses Python code for creating animations which we can export to animated GIFs or video files.
PythonRobotics
- Is a Python library for implementing different robotics simulations, visualizations, and algorithms.
- Offers various resources and tools for robotics developers, like algorithms for path planning, localization, motion control, mapping, and many more.
- Includes simulation environments like 2D and 3D simulators, that will allow developers to test their algorithms in virtual environments before deploying them on real robots.
matplotlib
- Is a comprehensive library for creating animated, interactive visualizations and static in Python.
- Produces publication-quality figures in different interactive environments and hardcopy formats across platforms.
- Can be used in Python Scripts, web application servers, various graphical user interface toolkits, and Python/IPython shells.
manim - ManimCommunity
- Is an animation engine for explanatory math videos used for programmatically creating precise animations.
- Includes various tools for creating animations like support for vector graphics, 3D objects, and complex mathematical equations.
- Also includes features for creating animations with custom fonts, styles, and colors.
plotly.py
- Is a Python library used to create interactive data visualizations, built on the plotly JavaScript library that allows developers to create various interactive plots.
- Is designed to be easy to use and includes different resources and tools for creating high-quality visualizations.
- Includes support for complex data structures like pandas DataFrames and offers various customization options for fonts, styles, and colors.
seaborn
- Is a Python data visualization library based on Matplotlib, offering a high-level interface to create attractive and informative statistical graphics.
- Offers various plotting functions for visualizing various data types like continuous data, data distribution, and categorial data.
- Its the ability to create visually appealing plots with minimal effort and supports the customization of plot elements like axes, titles, legends, and labels.
moviepy
- Is a Python library for video editing, concatenations, cutting, video composting, title insertions, creation of custom effects, and video processing.
- Has the ability to add audio to video clips easily and offers various filters and audio effects like changing pitch and speed, adding sound effects, and adjusting volume.
- Includes support for creating animations like moving text, images, and shapes and allows users to export their video clips to different file formats.
termtosvg
- Is a Python library that allows users to record terminal sessions and save them as SVG animations.
- Produces clean-looking and lightweight still frames embeddable on the project page or animations.
- Includes support for recording multiple terminal sessions, allowing users to control the size and speed of the resulting animation.
altair
- Is a declarative statistical visualization library that can help you spend more time understanding your data and its meaning.
- Offers a simple syntax for creating different visualizations, like line charts, histograms, scatterplots, and bar charts.
- Its declarative syntax lets user's express visualizations as a series of high-level mappings between visual and data properties like color, size, and position.
PathPlanning
- Is a Python library used for path and motion planning applications designed to be accessible to beginners and experts with a straightforward API.
- Offers various algorithms for computing collision-free paths for drones, mobile robots, and manipulators in 2D and 3D environments.
- Also offers tools for trajectory generation, motion control, and obstacle avoidance and supports simulation and visualization of robot motion.
alive-progress
- Is a Python library for displaying spinners and progress bars in command-line applications designed to offer a customizable way of showing progress indicators for long-running processes or tasks.
- Supports for pausing and resuming progress indicators, nested spinners, and progress bars.
- Designed to be intuitive and simple with various default settings and a straightforward API for customizing the behavior and appearance of spinners and progress bars.
asciimatics
- Is a package for helping people create full-screen text UIs on any platform and offers a single cross-platform Python class to do all the low-level console functions.
- Includes cursor positioning, mouse input, screen scraping, colored/styled text, detecting and handling if the console resizes, and keyboard input like Unicode support.
- Is a Python library for creating text-based animations and user interfaces in the terminal.
pygal
- Is a Python library for creating interactive Scalable Vector Graphics (SVG) graphs and charts.
- Offers various tools for generating customizable charts, graphs, and high-quality for use in presentations, reports, and web applications.
- Includes built-in support for data/time axis labeling, responsive design, and integration with web frameworks and interactive charts elements.
GANimation
- Is a Python implementation of the GANimation research project, which offers various tools for generating animations from still images using Generative Adversarial Networks (GANs).
- Includes tools for augmenting and preprocessing input data, customizable GAN training parameters and architecture, and support for evaluating and visualizing GAN models.
- Offers various tools for fine-tuning GAN models and generating high-quality animations for various applications.
deep-motion-editing
- Offers advanced and fundamental functions to work with 3D character animations in deep learning with Pytorch.
- Is a Python implementation of the research project of the same name, which offers tools for editing the motion of human characters in video sequences using deep learning methods.
- Its ability to generate realistic, high-quality animations for various applications offers tools for fine-tuning the deep learning model and editing the generated motions to achieve the desired results.
geoplotlib
- Is a Python library for creating geographical maps and visualizations and offers an easy-to-use interface for creating maps with different data types, like polygons, heatmaps, lines, and points.
- Includes support for different tile providers and map projections, customizable styling options for data layers like size, transparency, and color.
- Designed for creating interactive maps and visualizations and is suitable for various applications like data analysis, presentation, and exploration.
Linux-Fake-Background-Webcam
- Is a Python library that will allow users to replace their webcam background with a custom video or image on Linux systems.
- Works by creating a virtual webcam device that can be selected as the input source in video conferencing applications, allowing users to appear as if they are in various environments and locations.
- Includes the ability to control the position and size of the custom background video or image and support for replacing the webcam background with a custom video or audio.
celluloid
- Is a Python library that offers a simple interface for creating visualizations and animations in Matplotlib
- Designed to make it easy for users to create animations without having to write to deal with low-level details and complex code.
- Includes a simple interface for adding and updating data in the animation, the ability to save the animation as an MP4 or GIF video file, and support for customizing the animation style and appearance.
FAQ
What are the best data visualizations for Python animation libraries?
The Python Animation libraries create amazing visuals that can move and change. Here are the best data visualization libraries:
- Matplotlib
- Bokeh
- Plotly
- Pygal
- Plotnine
- Seaborn
- Holoviews
Which animation library is most used by Python coders today?
Matplotlib is a powerful 2D plotting library. It supports various visualizations. It is used in the scientific and data analysis communities. The 'FuncAnimation' class provides its animation capabilities. It allows coders to create dynamic and interactive visualizations. Its popularity is due to its advanced development, clear documentation, and reliability. Other higher-level visualization libraries use it as the backend.
How can I create explanatory math videos using a Python animation library?
You can use a Python Animation library to make math videos that show concepts visually. You should follow the below steps:
- Choose a Python animation library
- Plan your content
- Write the Python code
- Animate with time
- Narrate or annotate
- Export the video
- Edit and visualize
- Share your video
What does the code for a basic Python animation look like?
You can make a simple animation in Python with different libraries. Many people like using the matplotlib library. Matplotlib, a strong Python library, can make plots and do basic animations.
Here's an example of a basic Python animation using matplotlib:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# Function to update the plot in each animation frame
def update(frame):
# Clear the previous plot
plt.cla()
# Generate some data points for the animation
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x + 2*np.pi*frame/100)
# Plot the data
plt.plot(x, y)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Basic Python Animation')
plt.grid(True)
# Create a blank figure
fig, ax = plt.subplots()
# Create the animation with the update function, 100 frames, and 100ms delay between frames
animation = FuncAnimation(fig, update, frames=100, interval=100)
# If you want to save the animation as a video file, you can use the following line:
# animation.save('basic_animation.mp4', writer='ffmpeg', fps=30)
# Display the animation
plt.show()
This code creates a simple animation that displays a sine wave. The update function makes new data points and updates the plot in each animation frame. The FuncAnimation class controls the animation. It calls the update function many times with different frame values.
In this example, the animation has 100 frames with a delay of 100 milliseconds between frames.
To save the animation as a video file:
- Remove the comment from the animation.
- Save line.
- Make sure you have ffmpeg installed.
- Before running the code, ensure you have installed matplotlib in your Python setup. You can install it using pip install matplotlib.
Using an animation library, how can you make line charts with various colors in Python?
You can use different libraries in Python to make line charts with colors and animations. I will teach you how to use Matplotlib's FuncAnimation to animate graphs.
Here's a step-by-step guide:
#Install the required libraries (if you haven't already)
pip install matplotlib
# Import the necessary modules
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# Generate your data: Create multiple datasets with different colors. For this example, let's consider two datasets, data1 and data2
x = np.linspace(0, 10, 100)
data1 = np.sin(x)
data2 = np.cos(x)
# Create a figure and an axis to plot the data
fig, ax = plt.subplots()
# Define the line objects for each dataset and set their properties
line1, = ax.plot([], [], color='red', label='Data 1')
line2, = ax.plot([], [], color='blue', label='Data 2')
# Define the initialization function for the animation
def init():
line1.set_data([], [])
line2.set_data([], [])
return line1, line2
# Define the update function for the animation
def update(frame):
line1.set_data(x[:frame], data1[:frame])
line2.set_data(x[:frame], data2[:frame])
return line1, line2
# Create the animation using FuncAnimation
frames = len(x)
animation = FuncAnimation(fig, update, frames=frames, init_func=init, blit=True)
# Display the animation or save it to a file (optional)
plt.legend()
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Animated Line Chart with Different Colors')
plt.show()
This code makes a line chart that shows two datasets using different colors. You can customize the colors, data, and other properties per your requirements. To add more datasets, make new line objects and update their data in the update function.
Can FuncAnimation be used to animate 3D objects and 2D shapes in Python?
Yes, 'FuncAnimation' can animate both 3D objects and 2D shapes. But 'FuncAnimation' is a part of the Matplotlib library. It is primarily known for 2D plotting. Matplotlib's 3D plotting toolkit makes 3D objects, and visualizations come to life.
Are there any tips or tricks to improve creating animations with Python libraries?
To improve your animations, follow these helpful tips and tricks for efficient engineering. Here are some valuable tips to help you with it:
- Plan your animation
- Keep it simple
- Use subplots
- Choose the right library
- Optimize data processing
- Minimize redrawing
- Control animation speed
- Add labels and annotations
- User color thoughtfully
- Consider interactivity
- Test on a smaller subset
Can I find open-source projects to practice coding with a Python animation library?
Yes, there are many open-source projects available that use Python animation libraries. These resources help you practice animation libraries before starting your own project. Here are some places where you can find such projects:
- Matplotlib Examples Gallery
- GitHub Repositories
- Plotly Examples Gallery
- Kaggle Notebooks
- Bokeh Examples Gallery
- Data Science Blogs
- YouTube Tutorials
One of the most intellectual indoor games which keep the player engaged is Sudoku. Sudoku is a classic logic-based puzzle game. It requires a keen focus of mind and a logical vision. It is a number-placement game where you will be given a 9*9 grid which contains sub-grids of nine 3*3 matrices. The ultimate goal is to fill a grid with numbers from 1 to 9 in such a way each of its rows and columns contains each number exactly once. The outgrowth of technology in the last decade brought this intriguing game online. How about you creating this brilliant Sudoku game? How about building this complex game in a single-page application like React? Sounds interesting! Isn't it? Let's get into it with the help of the following libraries. This kit aids the development of Sudoku games using React by following the below steps. 1. Choose a development environment 2. Create a 2D array 3. Set up a track to look into the game's progress 4. Set up a track to determine the number of conflicts left 5. Create a component to indicate the connection between cells 6. Write a script to indicate connections using signals 7. Manage user's input 8. Create a component to drag and drop the numbers 9. Set up the tools to perform operations 10. Do the scripting to track the history of actions done
Development Environment
React is used for development. With React, it becomes easy and simple to develop an interactive UI. The state management in React makes the process of developing an application more flexible.
Graphical user interface
GUIs act as intermediaries to communicate with your device through UI components. In React, building UI components gets easy with the aid of CSS. React can be used for desktop applications and mobile applications as well.
Puzzle Solver
The puzzle-solving is simplified by creating cell components that throw signals indicating the relationship or connection between similar cell components using different colors.
Puzzle generator
Generating a puzzle is one of the key steps in creating a logic-based game. State management in React optimizes the puzzle generation.
Flappy Bird is an arcade-style game. It was initially released as a mobile game while tapping the screen to make the bird fly. Later, the game's pc version was released, where the Bird will be controlled using the up key or the space bar. If Bird hits on the pipes or the screen edges, the game ends, and the player needs to restart. Flappy Bird can fly the Bird as far as you can without hitting a pipe. The player is tasked with navigating Faby through pairs of pipes with equally sized gaps placed at random heights. Try to play as long as possible, score as many points as you can!. Following are the steps to be followed for build Flappy Bird Game, 1. Graphics Setup 2. Game Logic 3. Creating Input Controls 4. Generating Sound effects & Display Scores 5. Multi-player
Multi-player
Flappy bird is a single-player game, but it's possible to have multiplayer by using below libraries. Players will play on their game field one who gets more scores will win the game.
Graphic Designs & Game logic
Graphic designs are used in a flappy game to build an image of the player (bird), background, pipe, base and for displaying messages. Game logic and Graphic designs are build by using below libraries.
Creating Input Controls
Key mapper is an open-source library that allows users to use a key or combination of keys to perform a specific action(fly), which can be used for navigating.
Sound effects & Scores
Sound effects are used while the bird hits the pipe, generating scores for every move of a bird and a Game over by sfb & FlapPyBird libraries . Using flairfly library, scores can be calculated by the number of pipes crossed.
Pinball is an arcade game where a player uses paddles to launch the ball into the table. It prevents the ball from falling past your flippers if possible.
Interact with dynamic elements of the table like blockers, bumpers, flippers, gates, holes, LEDs, plungers, rollovers, slingshots, spinners, targets, ramps, and pipes to increase your score and get multipliers. This game comes with three balls. Use the arrow keys to hit the left or right flippers. Following are the steps to be followed to build Your Pinball Game, 1. Graphic designs 2. Sound effects 3. User Interface 4. Pinball controller 5. Leaderboard 6. 3D Pinball game
Graphic Designs
Listed below libraries help in creating the best graphic design for gaming applications, which is used in design tables and infrastructure in pinball.
User Interface
The below user interface libraries are used for different platforms like android, Pc.
Sound effects
Sound effects are used for ball hitting, dropping, paddles, and also starting & ending of the game. These effects can be achieved by using the below libraries.
Pinball Controller
The below libraries are used to control the spring to start, left and right paddles to prevent ball drop.
Leaderboard
The below libraries are used to display scores, the history of the player, player name. It has a database connection to save the scores and create a leaderboard.
3D Pinball Game
The pinball game can be built in 3D by using the below library.
Tetris has established itself as a famous game since the early video games. Even though the game looks simple requires intelligence and skills to play.
The gameplay contains tiles or tetrominoes of different shapes and a game field grid. The game's objective is to position the tiles in the game field, which fills the grid. The disappearing line will grant points. Accumulated points help users to move a level up. Once the game is over, the final score will be displayed to the user. Following steps to be followed to build your own Tetris game, 1.Create Blocks for Tetris 2.Graphic designs 3.Multi-player Tetris 4.Creating customized Game field 5.2D Tetris 6.3D Tetris 7.Control keys
Create Blocks & Graphics
Listed below libraries help in creating the best graphic design for gaming applications can help the moving tiles across the game field, selecting colors for tiles, making different shapes of tiles using different sizes of arrays, and matrix rotation. In the case of a single-player game, the game gets over when all blocks are formed such that no lines are disappearing.
2D Tetris Game
2D games are titles with only two axes of motion. Typically, these are "flat" games where you can move left and right up and down. You can create a 2D Tetris game using the below libraries.
3D Tetris Game
Players control multiple falling blocks, positioning and rotating them to clear layers in a three-dimensional environment similar to Tetris gameplay. You can create a 3D Tetris game using the below libraries.
Creating own Game field
The libraries listed below help to create custom matrices for the Tetris game.
Multi-player Tetris
Listed below libraries helps to build a multi-player Tetris game, two players will play on their game field one who gets more scores will win the battle.
Control Keys
Key mapper is an open-source that allows users to use a key or combination of keys to perform a rotation and move, which can be used for navigating. You can create your keys to play using the below libraries.
"Animate different Objects with three.js" is a code example that shows how to create a 3D scene using the three.js library and animate multiple objects. In this example, a box and a sphere are animated by changing their rotation and position properties over time using the requestAnimationFrame method.
This explains various features of three.js, such as creating a renderer, a scene, a camera, and adding lights and materials to the objects. The code also demonstrates how to create geometries for the box and the sphere and meshes by combining the geometries and materials.
Using three.js, developers can create interactive and immersive experiences that can run on the web or various platforms, including desktop, mobile, and VR devices. The example can be useful in various applications that require 3D graphics, such as video games, simulations, virtual and augmented reality, scientific visualization, and product design. Animating different objects in a 3D scene can add a sense of dynamism, realism, and engagement to such applications, making them more effective and enjoyable for users.
Please check the below code to learn how to animate different objects with three.js,
Fig : Preview of the output that you will get on running this code from your IDE.
Code
In this solution we're using React, Nodejs and three.js.
Instructions
Follow the steps carefully to get the output easily.
- Install the Node.js and React on your IDE(preferable Visual Studio Code).
- Create React Application using npx create-react-app foldername.
- cd foldername.
- Open the folder in IDE.
- Copy the code using "copy" button above and paste it in app.js file(remove the earlier code from app.js).
- Cut the script tag which is present at the end of code and paste it in index.html file(remove the earlier code from index.html).
- Import three.js library as import * as THREE from 'three'.
- Add export default statement at end of the code as "export default animate".
- Open the terminal from IDE.
- npm start to run the file.
I hope you found this useful. I have added the link to dependent library, version information in the following sections.
I found this code snippet by searching for 'animate different objects with three.js' in kandi. You can try any such use case!
Environment Tested
I tested this solution in the following versions. Be mindful of changes when working with other versions.
- The solution is created in Visual Studio Code 1.73.1.
- The solution is tested on node v18.12.1 and npm v8.19.2.
- React version-18.2.0.
- three version-0.148.0.
Using this solution, we are able to animate different objects with three.js with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to animate different objects with three.js.
Dependent Libraries
You can also search for any dependent libraries on kandi like 'react', 'nodejs' and 'three.js'.
Support
- For any support on kandi solution kits, please use the chat
- For further learning resources, visit the Open Weaver Community learning page.
Technology has always been evolving at a breakneck speed, but the pace of change today is surely unprecedented. Applications of blockchain, for instance, go beyond cryptocurrencies into industries like finance, healthcare, supply chain and logistics, asset management, etc. It is one of the most disruptive technologies of the 21st century, and now you can program blockchain web apps using JavaScript. With that in mind, here are some of the JavaScript libraries to help you in the process. ccxt - A cryptocurrency trading API; ZeroNet - Decentralized websites using Bitcoin crypto and the BitTorrent network; truffle - A tool for developing smart contracts. The following is a list of the most popular open-source libraries for building and scaling JavaScript Blockchain Applications.
Carousels (slideshows) are containers with images or information that users can select by clicking a button that forwards or backward through the slideshow. The image carousel is a container (slideshow) that users choose by clicking a button that is used to direct them to the next or previous image in the slideshow. A timer can automatically change the images, or they can be manually changed by clicking the buttons displayed. Following are the steps to be followed for building Carousel And Screen Saver builder, 1. Transition Effect And Touch slider 2. Multiple Layout 3. Slider Libraries 4. Screen Saver Libraries
Transition Effect And Touch slider
These libraries are used to process the transition effect .
Slider Libraries
These libraries are used to build the carousel .
Multiple Layout
These libraries are used to build multiple layout in website.
Screen Saver Libraries
These libraries are used to process the screen saver.
If you are a designer you design logos and mockups, you use the color picker every day when choosing a new project's color scheme. By mixing the three primary colors, we can form any color we like. Red(R), Green(G), Blue(B) are the three primary colors we know. Using this tool, you can experiment with custom colors on the web and adjust them according to your preference. In addition, different color formats can be converted easily supported by JavaScript. These libraries allow building color picker and generator client-side applications in minutes. Following are the steps to be followed for building Color Picker and Code Generator, 1. Color Picker 2. Code Generator
Code Generator
These libraries are used to generate the code based on the color.
Color Picker
These libraries are used to pick the color.
NFT stands for Non-Fungible Token. It is a digital asset and what makes it unique from stock photos is the token associated with the asset. This combination of asset and token makes it non-fungible and guaranteed by blockchain technology. You may compare it to original artwork or maybe an autographed print copy or digital trading cards. An easy start into NFT is a self service marketplace like OpenSea or Mintable. But if you are more of a developer than an artist, here are trending libraries that help you publish your own NFTs.
Listing NFTs in your Website
The libraries embeddable, nfte and nftgecko help in listing the NFTs in your website.
Creating DApp
Scaffold-eth, etherplate and kitty-items are frameworks for creating DApp (Decentralized Applications) & Marketplace on Ethereum blockchain.
Deploying and Minting NFTs
EthArt, contractor and open-proofs are used for deploying and minting the NFTs.
Add functionalities such as building tables, data grids, and interactive data visualizations into your application easily and in a visually appealing way with the Python table libraries.
Python table libraries are highly useful in advanced applications with data management functions such as analytics, data science, and machine learning. Using these libraries, you can represent data in an organized manner while controlling and customizing various aspects of a table. These include:
- width and column padding
- text alignment
- data sorting
- table borders, and more.
These libraries also provide a large number of predefined formats that allows you to publish tables in different ways. Also, you can format the tables to publish on popular project management software such as Jira and GitHub.
Explore the top and trending Python table libraries to add table formatting features in your applications:
prettytable
- Supports custom table formatting and styling.
- Allows adding, deleting, and rearranging columns easily.
- Provides a simple way to display tabular data in a text-based interface.
pytablewriter
- Supports various file formats for table export (CSV, Excel, JSON, etc.).
- Allows fine-grained control over cell alignment and formatting.
- Offers an intuitive and extensible API for creating and writing tables.
python-tabulate
- Provides multiple table styles and formatting options.
- Supports data alignment, numbering, and various output formats.
- Can render tables as plain text or HTML for different use cases.
dataset
- Offers a simplified interface for working with databases.
- Supports data loading, querying, and manipulation with minimal code.
- Provides a consistent API across different database backends.
camelot
- Specialized for extracting tables from PDF documents.
- Supports both text-based and image-based table extraction.
- Offers advanced table configuration options for precise extraction.
pdftabextract
- Designed for OCR-based table extraction from scanned PDFs.
- Provides tools for layout analysis and structured table data extraction.
- Useful for digitizing tabular information from documents.
django-tables2
- Integrates seamlessly with Django web applications.
- Offers a declarative syntax for defining table structures.
- Supports sorting, pagination, and customization of table rendering.
django-watson
- A full-text search library for Django applications.
- Provides efficient search functionality across multiple models.
- Supports stemming, ranking, and result highlighting.
petl
- A powerful library for ETL (Extract, Transform, Load) operations on tabular data.
- Offers a wide range of data manipulation functions.
- Integrates well with other data processing libraries like pandas.
csvtotable
- Converts CSV data into an interactive HTML table.
- Supports data sorting, filtering, and pagination in the web interface.
- Suitable for quickly visualizing and exploring CSV data.
textfsm
- A template-based text parsing library.
- Used for extracting structured data from unstructured text.
- Commonly used for parsing network device configuration files.
rows
- A minimalistic library for working with tabular data.
- Provides basic data manipulation and serialization capabilities.
- Lightweight and easy to use for simple table operations.
image2csv
- Converts images containing tabular data into CSV format.
- Useful for digitizing data from scanned documents or images.
- Supports customization of image preprocessing and OCR options.
csvtomd
- Converts CSV data into Markdown tables for documentation.
- Supports alignment and column formatting in Markdown.
- Useful for generating human-readable documentation from CSV data.
Pylsy
- Creates pretty ASCII tables with cell alignment.
- Offers easy customization of table styling and formatting.
- Suitable for displaying tabular data in console applications.
jupyter_pivottablejs
- Integrates with Jupyter Notebook for interactive pivot table creation.
- Allows users to explore and analyze data with a graphical interface.
- Supports aggregation, filtering, and dynamic table manipulation within Jupyter notebooks.
FAQ
1. What Python libraries are available for data visualization?
Python boasts a plethora of libraries for data visualization. Some popular ones include Matplotlib, Seaborn, Plotly, and Bokeh. Each tool has different features and abilities. Analysts and scientists use this to make charts and graphs and study data better.
2. How can a Python data visualization library help someone in a Data Science Career?
Employing a Python data visualization library is instrumental in a Data Science career. It enables professionals to convey complex data findings in a visually comprehensible manner. This helps with decision-making using data and sharing insights to improve business results.
3. Which software do you need to run the PrettyTable library?
You do not need additional software to use the PrettyTable library in Python. This Python library can be easily added to Python scripts or projects. It doesn't require any external dependencies.
4. Is there a machine learning library available for Python?
Python has many machine learning libraries, and scikit-learn is a popular one. Python is a flexible platform for machine learning. It has powerful libraries like TensorFlow, PyTorch, and Keras. These libraries cater to deep learning and neural networks.
5. How does one learn Python, and which libraries should they focus on first?
Learning Python begins with grasping the fundamentals of the language. To become a programmer, start by learning libraries like NumPy and Pandas. These will help you manipulate data. Once you feel comfortable, you can use Matplotlib and Seaborn to visualize data. To delve into machine learning, starting with scikit-learn is advisable. Online tutorials, courses, and hands-on projects help you learn Python and its libraries.
Buttons are essentially the drivers of online interaction as we use them to login into our emails, add products to our shopping carts, download photos and basically confirm any and all actions. But more than that, every button click is a successful conclusion of every front-end web developer’s hard work. That’s why it is crucial to spend time creating functional buttons that both look beautiful and provide visual cues to the user. JavaScript offers a ton of great button libraries for you to choose your essential UI components from. Here are some of the JavaScript libraries for buttons including Semantic-UI - UI component framework based around useful principles; Buttons - A CSS button library built using Sass and Compass; Ladda - Buttons with built-in loading indicators. The following is a comprehensive list of the best open-source JavaScript Button libraries in 2022
Animation is one of the most interesting features in an application. It's not a new thing, but it's something that you can use to make a difference to your app. Animation has been around for some time now, and with the evolution of computers and technology, animation has become even more popular. A library of animation classes that can be applied to game object properties such as position, rotation, and scale, with a focus on keeping core classes small and efficient, while still being able to animate many different types of parameters. Animations bring to life the website and make it look more appealing to the visitor. Build interactive C# applications, animate elements, elegant UI effects. Listed here the best C# Animation libraries in 2022.
Visualizing data as interactive charts is extremely easy using charting libraries based on JavaScript. These free and open-source code components employ HTML5 <canvas> element to create different chart types, including time series, bar chart, lines, bars, etc. This makes it yield good performance even when working with large data sets. The code packages are easily integrable with popular JavaScript animation frameworks like Angular, React, PHP, JQuery, Rails, and more, making it possible to create a chart with real-time data and animations. In addition, downward compatibility with outdated browsers is also achievable with polyfills. Listed below are some of the most popular open-source libraries for charting in 2021. We highly recommend Chart.js - Simple HTML5 Charts using the canvas tag; D3 (or D3.js) is a JavaScript library for visualizing data using web standards; Plotly.js is a standalone Javascript data visualization library, and it also powers the Python and R modules named plotly.
Trending Discussions on User Interface
Why Metamask if web3.js can interact directly with ganache?
Is it possible to save several values to a button?
How to upload an Image File modified by OpenCV using FileSystemStorage in Django?
How to dynamically define Headers and Settings for UWP NavigationView's menu, using C++/winRT?
With Stripe API, How To Get session_id of Checkout Session That Created a payment_intent Object, From payment_intent.succeeded Webhook
Is it safe to store, access and HTMLElement objects directly inside an object, vs. relying on CSS selectors?
How to increase height of jQueryUI selectmenu?
Is a work manager good for these situations?
Data exchange between websocket clients and server
Register all inputs inside a multi-page data table
QUESTION
Why Metamask if web3.js can interact directly with ganache?
Asked 2022-Mar-30 at 17:55I am new to blockchain app development, I saw a project where ganache accounts are imported into Metamask, then web3.js is used to access and print those accounts and balances on Frontend (user interface).
If web3.js can directly access ganache blockchain accounts and balances, why do we need Metamask in between?
ANSWER
Answered 2022-Feb-08 at 09:11If web3.js can directly acccess ganache blockchain accounts and balances, why we need metamask in between?
In this case, you don't need MetaMask to sign the transaction, as the node (Ganache) holds your private key.
But in a public environment (testnets and mainnet), the node doesn't hold your private key, so you'd need to sign the transaction using MetaMask (or any other tool that holds the private key).
QUESTION
Is it possible to save several values to a button?
Asked 2022-Mar-08 at 02:57Traditionally buttons are designed to save only ONE single value, eg:
1<button type="button" value="Love" onclick="fetchValue(this)"> Primary </button>
2
3function fetchValue(_button){
4 alert(_button.value);
5}
6
For instance, in the above HTML
code, when a user clicks on the Primary button, an alert with the word Love will pop up!
For (UI/UX)User Interface/Experience purposes, I need to design a button that can hold several values and NOT just one value. This is because I plan on coupling a click event to the button to send/post all stored values.
The much desired code would be something like the code below:
1<button type="button" value="Love" onclick="fetchValue(this)"> Primary </button>
2
3function fetchValue(_button){
4 alert(_button.value);
5}
6<button type="button" value="Love", value2="Love",
7value3="Love" onclick="fetchValue(this)"> Primary </button>
8
Is there someone who might know how to resolve this or even a better solution to my problem?
Thanks in advance
ANSWER
Answered 2022-Mar-07 at 15:34You can use data
attributes for additional values.
1<button type="button" value="Love" onclick="fetchValue(this)"> Primary </button>
2
3function fetchValue(_button){
4 alert(_button.value);
5}
6<button type="button" value="Love", value2="Love",
7value3="Love" onclick="fetchValue(this)"> Primary </button>
8function fetchValue(_button){
9 alert(`${_button.value} ${_button.dataset.value2}`);
10}
1<button type="button" value="Love" onclick="fetchValue(this)"> Primary </button>
2
3function fetchValue(_button){
4 alert(_button.value);
5}
6<button type="button" value="Love", value2="Love",
7value3="Love" onclick="fetchValue(this)"> Primary </button>
8function fetchValue(_button){
9 alert(`${_button.value} ${_button.dataset.value2}`);
10}<button type="button" value="Love" data-value2="you" onclick="fetchValue(this)"> Primary </button>
QUESTION
How to upload an Image File modified by OpenCV using FileSystemStorage in Django?
Asked 2022-Feb-13 at 16:57I am taking an uploaded image from the user and then sending it to a YOLO model which then returns me an image.
I want to store that returned image in my Local Directory and then display it on the user interface.
This is the Code of views.py
that takes in an image and sends it to the Yolo Model,
1def predictImage(request):
2 # print(request)
3 # print(request.POST.dict())
4 fileObj = request.FILES['filePath']
5 fs = FileSystemStorage()
6 filePathName = fs.save(fileObj.name, fileObj)
7 filePathName = fs.url(filePathName)
8 testimage = '.'+filePathName
9 # img = image.load_img(testimage, target_size=(img_height, img_width))
10 img = detect_image(testimage)
11 filePathName = fs.save(fileObj.name + "_result", img) # -> HERE IS THE ERROR
12 filePathName = fs.url(filePathName)
13
This is the function of YOLO Model that uses OpenCV to read the image (Image is sent as argument to the function) and then returns that image,
1def predictImage(request):
2 # print(request)
3 # print(request.POST.dict())
4 fileObj = request.FILES['filePath']
5 fs = FileSystemStorage()
6 filePathName = fs.save(fileObj.name, fileObj)
7 filePathName = fs.url(filePathName)
8 testimage = '.'+filePathName
9 # img = image.load_img(testimage, target_size=(img_height, img_width))
10 img = detect_image(testimage)
11 filePathName = fs.save(fileObj.name + "_result", img) # -> HERE IS THE ERROR
12 filePathName = fs.url(filePathName)
13import numpy as np
14import cv2
15
16def detect_image(img_path):
17
18 confidenceThreshold = 0.5
19 NMSThreshold = 0.3
20
21 modelConfiguration = 'cfg/yolov3.cfg'
22 modelWeights = 'yolov3.weights'
23
24 labelsPath = 'coco.names'
25 labels = open(labelsPath).read().strip().split('\n')
26
27 np.random.seed(10)
28 COLORS = np.random.randint(0, 255, size=(len(labels), 3), dtype="uint8")
29
30 net = cv2.dnn.readNetFromDarknet(modelConfiguration, modelWeights)
31
32 image = cv2.imread(img_path)
33 (H, W) = image.shape[:2]
34
35 #Determine output layer names
36 layerName = net.getLayerNames()
37 layerName = [layerName[i - 1] for i in net.getUnconnectedOutLayers()]
38
39 blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB = True, crop = False)
40 net.setInput(blob)
41 layersOutputs = net.forward(layerName)
42
43 boxes = []
44 confidences = []
45 classIDs = []
46
47 for output in layersOutputs:
48 for detection in output:
49 scores = detection[5:]
50 classID = np.argmax(scores)
51 confidence = scores[classID]
52 if confidence > confidenceThreshold:
53 box = detection[0:4] * np.array([W, H, W, H])
54 (centerX, centerY, width, height) = box.astype('int')
55 x = int(centerX - (width/2))
56 y = int(centerY - (height/2))
57
58 boxes.append([x, y, int(width), int(height)])
59 confidences.append(float(confidence))
60 classIDs.append(classID)
61
62 #Apply Non Maxima Suppression
63 detectionNMS = cv2.dnn.NMSBoxes(boxes, confidences, confidenceThreshold, NMSThreshold)
64
65 if(len(detectionNMS) > 0):
66 for i in detectionNMS.flatten():
67 (x, y) = (boxes[i][0], boxes[i][1])
68 (w, h) = (boxes[i][2], boxes[i][3])
69
70 color = [int(c) for c in COLORS[classIDs[i]]]
71 cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
72 text = '{}: {:.4f}'.format(labels[classIDs[i]], confidences[i])
73 cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
74
75 return image
76
77 #cv2.imshow('Image', image)
78 #cv2.waitKey(0)
79
On this line,
1def predictImage(request):
2 # print(request)
3 # print(request.POST.dict())
4 fileObj = request.FILES['filePath']
5 fs = FileSystemStorage()
6 filePathName = fs.save(fileObj.name, fileObj)
7 filePathName = fs.url(filePathName)
8 testimage = '.'+filePathName
9 # img = image.load_img(testimage, target_size=(img_height, img_width))
10 img = detect_image(testimage)
11 filePathName = fs.save(fileObj.name + "_result", img) # -> HERE IS THE ERROR
12 filePathName = fs.url(filePathName)
13import numpy as np
14import cv2
15
16def detect_image(img_path):
17
18 confidenceThreshold = 0.5
19 NMSThreshold = 0.3
20
21 modelConfiguration = 'cfg/yolov3.cfg'
22 modelWeights = 'yolov3.weights'
23
24 labelsPath = 'coco.names'
25 labels = open(labelsPath).read().strip().split('\n')
26
27 np.random.seed(10)
28 COLORS = np.random.randint(0, 255, size=(len(labels), 3), dtype="uint8")
29
30 net = cv2.dnn.readNetFromDarknet(modelConfiguration, modelWeights)
31
32 image = cv2.imread(img_path)
33 (H, W) = image.shape[:2]
34
35 #Determine output layer names
36 layerName = net.getLayerNames()
37 layerName = [layerName[i - 1] for i in net.getUnconnectedOutLayers()]
38
39 blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB = True, crop = False)
40 net.setInput(blob)
41 layersOutputs = net.forward(layerName)
42
43 boxes = []
44 confidences = []
45 classIDs = []
46
47 for output in layersOutputs:
48 for detection in output:
49 scores = detection[5:]
50 classID = np.argmax(scores)
51 confidence = scores[classID]
52 if confidence > confidenceThreshold:
53 box = detection[0:4] * np.array([W, H, W, H])
54 (centerX, centerY, width, height) = box.astype('int')
55 x = int(centerX - (width/2))
56 y = int(centerY - (height/2))
57
58 boxes.append([x, y, int(width), int(height)])
59 confidences.append(float(confidence))
60 classIDs.append(classID)
61
62 #Apply Non Maxima Suppression
63 detectionNMS = cv2.dnn.NMSBoxes(boxes, confidences, confidenceThreshold, NMSThreshold)
64
65 if(len(detectionNMS) > 0):
66 for i in detectionNMS.flatten():
67 (x, y) = (boxes[i][0], boxes[i][1])
68 (w, h) = (boxes[i][2], boxes[i][3])
69
70 color = [int(c) for c in COLORS[classIDs[i]]]
71 cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
72 text = '{}: {:.4f}'.format(labels[classIDs[i]], confidences[i])
73 cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
74
75 return image
76
77 #cv2.imshow('Image', image)
78 #cv2.waitKey(0)
79filePathName = fs.save(fileObj.name + "_result", img)
80
I am getting this following error,
1def predictImage(request):
2 # print(request)
3 # print(request.POST.dict())
4 fileObj = request.FILES['filePath']
5 fs = FileSystemStorage()
6 filePathName = fs.save(fileObj.name, fileObj)
7 filePathName = fs.url(filePathName)
8 testimage = '.'+filePathName
9 # img = image.load_img(testimage, target_size=(img_height, img_width))
10 img = detect_image(testimage)
11 filePathName = fs.save(fileObj.name + "_result", img) # -> HERE IS THE ERROR
12 filePathName = fs.url(filePathName)
13import numpy as np
14import cv2
15
16def detect_image(img_path):
17
18 confidenceThreshold = 0.5
19 NMSThreshold = 0.3
20
21 modelConfiguration = 'cfg/yolov3.cfg'
22 modelWeights = 'yolov3.weights'
23
24 labelsPath = 'coco.names'
25 labels = open(labelsPath).read().strip().split('\n')
26
27 np.random.seed(10)
28 COLORS = np.random.randint(0, 255, size=(len(labels), 3), dtype="uint8")
29
30 net = cv2.dnn.readNetFromDarknet(modelConfiguration, modelWeights)
31
32 image = cv2.imread(img_path)
33 (H, W) = image.shape[:2]
34
35 #Determine output layer names
36 layerName = net.getLayerNames()
37 layerName = [layerName[i - 1] for i in net.getUnconnectedOutLayers()]
38
39 blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB = True, crop = False)
40 net.setInput(blob)
41 layersOutputs = net.forward(layerName)
42
43 boxes = []
44 confidences = []
45 classIDs = []
46
47 for output in layersOutputs:
48 for detection in output:
49 scores = detection[5:]
50 classID = np.argmax(scores)
51 confidence = scores[classID]
52 if confidence > confidenceThreshold:
53 box = detection[0:4] * np.array([W, H, W, H])
54 (centerX, centerY, width, height) = box.astype('int')
55 x = int(centerX - (width/2))
56 y = int(centerY - (height/2))
57
58 boxes.append([x, y, int(width), int(height)])
59 confidences.append(float(confidence))
60 classIDs.append(classID)
61
62 #Apply Non Maxima Suppression
63 detectionNMS = cv2.dnn.NMSBoxes(boxes, confidences, confidenceThreshold, NMSThreshold)
64
65 if(len(detectionNMS) > 0):
66 for i in detectionNMS.flatten():
67 (x, y) = (boxes[i][0], boxes[i][1])
68 (w, h) = (boxes[i][2], boxes[i][3])
69
70 color = [int(c) for c in COLORS[classIDs[i]]]
71 cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
72 text = '{}: {:.4f}'.format(labels[classIDs[i]], confidences[i])
73 cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
74
75 return image
76
77 #cv2.imshow('Image', image)
78 #cv2.waitKey(0)
79filePathName = fs.save(fileObj.name + "_result", img)
80'numpy.ndarray' object has no attribute 'read'
81
I am not sure how can I resolve this. I tried searching how can I store OpenCV Modified file usnig FileSystemStorage but found nothing of help. Can anyone help me regarding this?
ANSWER
Answered 2022-Feb-13 at 16:57You can use the imwrite
function of cv2
library to store your files in the local directory, i.e.,
In your case, simply do this,
1def predictImage(request):
2 # print(request)
3 # print(request.POST.dict())
4 fileObj = request.FILES['filePath']
5 fs = FileSystemStorage()
6 filePathName = fs.save(fileObj.name, fileObj)
7 filePathName = fs.url(filePathName)
8 testimage = '.'+filePathName
9 # img = image.load_img(testimage, target_size=(img_height, img_width))
10 img = detect_image(testimage)
11 filePathName = fs.save(fileObj.name + "_result", img) # -> HERE IS THE ERROR
12 filePathName = fs.url(filePathName)
13import numpy as np
14import cv2
15
16def detect_image(img_path):
17
18 confidenceThreshold = 0.5
19 NMSThreshold = 0.3
20
21 modelConfiguration = 'cfg/yolov3.cfg'
22 modelWeights = 'yolov3.weights'
23
24 labelsPath = 'coco.names'
25 labels = open(labelsPath).read().strip().split('\n')
26
27 np.random.seed(10)
28 COLORS = np.random.randint(0, 255, size=(len(labels), 3), dtype="uint8")
29
30 net = cv2.dnn.readNetFromDarknet(modelConfiguration, modelWeights)
31
32 image = cv2.imread(img_path)
33 (H, W) = image.shape[:2]
34
35 #Determine output layer names
36 layerName = net.getLayerNames()
37 layerName = [layerName[i - 1] for i in net.getUnconnectedOutLayers()]
38
39 blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB = True, crop = False)
40 net.setInput(blob)
41 layersOutputs = net.forward(layerName)
42
43 boxes = []
44 confidences = []
45 classIDs = []
46
47 for output in layersOutputs:
48 for detection in output:
49 scores = detection[5:]
50 classID = np.argmax(scores)
51 confidence = scores[classID]
52 if confidence > confidenceThreshold:
53 box = detection[0:4] * np.array([W, H, W, H])
54 (centerX, centerY, width, height) = box.astype('int')
55 x = int(centerX - (width/2))
56 y = int(centerY - (height/2))
57
58 boxes.append([x, y, int(width), int(height)])
59 confidences.append(float(confidence))
60 classIDs.append(classID)
61
62 #Apply Non Maxima Suppression
63 detectionNMS = cv2.dnn.NMSBoxes(boxes, confidences, confidenceThreshold, NMSThreshold)
64
65 if(len(detectionNMS) > 0):
66 for i in detectionNMS.flatten():
67 (x, y) = (boxes[i][0], boxes[i][1])
68 (w, h) = (boxes[i][2], boxes[i][3])
69
70 color = [int(c) for c in COLORS[classIDs[i]]]
71 cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
72 text = '{}: {:.4f}'.format(labels[classIDs[i]], confidences[i])
73 cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
74
75 return image
76
77 #cv2.imshow('Image', image)
78 #cv2.waitKey(0)
79filePathName = fs.save(fileObj.name + "_result", img)
80'numpy.ndarray' object has no attribute 'read'
81img = detect_image(testimage)
82cv2.imwrite(fileObj.name+"_result.jpg", img=img)
83
QUESTION
How to dynamically define Headers and Settings for UWP NavigationView's menu, using C++/winRT?
Asked 2022-Feb-02 at 17:01I'm working on a cross-platform project in C++ generating the UI dynamically, and I am struggling with C++/winRT UWP NavigationView on two problems:
- When defining a NavigationViewItemHeader, the resulting header title doesn't show in the navigation menu, the space remains empty,
- When trying to update the SettingsItem of the navigation menu, the value of the Settings navigation item is nullptr as returned by SettingsItem().
Here is the code I wrote for generating the menu from a list of items managed independently from the host (e.g. Windows):
1bool
2CANavigationView::UpdateHostView( void )
3{
4 TNavigationItemPtr item;
5 TIndex index;
6
7 if( _hostViewUpdateNeeded == false )
8 return false;
9
10 Windows::UI::Xaml::Controls::NavigationViewItemBase hItem( nullptr );
11 Windows::UI::Xaml::Controls::TextBlock hText( nullptr );
12 winrt::hstring hTag;
13
14 // Remove all navigation items from the current host view:
15 _hostNavigationView.MenuItems().Clear();
16 _hostNavigationView.IsSettingsVisible( false );
17
18 // Build the navigation menu items:
19 for( index = 0; index < _navigationItems.CountOfItems(); index++ )
20 {
21 item = * _navigationItems.GetItemAtIndex( index );
22
23 if( item->identifier == kSettingsItem )
24 {
25 _hostNavigationView.IsSettingsVisible( true );
26 hText = Windows::UI::Xaml::Controls::TextBlock();
27 CSString::ConvertToUIString( item->title->GetString( gAppLanguageCode ), & hTag );
28 hText.Text( hTag );
29// Issue #1 : cannot access to the Settings item
30// _hostNavigationView.SettingsItem().as< Windows::UI::Xaml::Controls::NavigationViewItem >().Content( hText );
31// SettingsItem() returns nullptr...
32 }
33 else
34 {
35 switch( item->type )
36 {
37 case eNavigationHeader:
38 hItem = Windows::UI::Xaml::Controls::NavigationViewItemHeader();
39 hText = Windows::UI::Xaml::Controls::TextBlock();
40 CSString::ConvertToUIString( item->title->GetString( gAppLanguageCode ), & hTag );
41 hText.Text( hTag );
42// Issue #2: The header's title is not displayed
43 hItem.Content( hText );
44 _hostNavigationView.MenuItems().Append( hItem );
45 break;
46
47 case eNavigationSeparator:
48 hItem = Windows::UI::Xaml::Controls::NavigationViewItemSeparator();
49 _hostNavigationView.MenuItems().Append( hItem );
50 break;
51
52 case eNavigationItem:
53 hItem = Windows::UI::Xaml::Controls::NavigationViewItem();
54 CSString::ConvertToUIString( CAUIElement::GetStringFromUIIdentifier( item->identifier ), & hTag );
55 hItem.Tag( winrt::box_value( hTag ) );
56 hText = Windows::UI::Xaml::Controls::TextBlock();
57 CSString::ConvertToUIString( item->title->GetString( gAppLanguageCode ), & hTag );
58 hText.Text( hTag );
59 hItem.Content( hText );
60 hItem.as< Windows::UI::Xaml::Controls::NavigationViewItem>().Icon( GetHostIcon( item->icon ) );
61 _hostNavigationView.MenuItems().Append( hItem );
62 break;
63
64 default:
65 break;
66 }
67 }
68 }
69
70 _hostViewUpdateNeeded = false;
71
72 return true;
73}
74
As I'm using my own string format (I'm stuck in old C++ standards...) and I18N support, I need to first convert the UTF8 string to the host (here Windows) before setting the value of the text block, using the hTag variable of type hstring. In debugging mode, the text is well transcoded in the hstring format...
What is puzzling me is the fact that both NavigationSeparator and NavigationItem cases are working fine, in line with the official Microsoft documentation (including the Tag for menu event handling and Icon setting for NavigationViewItem).
I understand this is not the "mainstream XAML way" of working on UWP user interface but so far the approach is working well on other UI elements.
Here is a screenshot of the navigation view with the empty spaces for the headers:
Also, in the example above, I logged the number of menu items in the host navigation view (_hostNavigationView.MenuItems().Size()) and got 7 as a result, which is correct...
At last, here's the detailed log I'm generating in DEBUG mode:
1bool
2CANavigationView::UpdateHostView( void )
3{
4 TNavigationItemPtr item;
5 TIndex index;
6
7 if( _hostViewUpdateNeeded == false )
8 return false;
9
10 Windows::UI::Xaml::Controls::NavigationViewItemBase hItem( nullptr );
11 Windows::UI::Xaml::Controls::TextBlock hText( nullptr );
12 winrt::hstring hTag;
13
14 // Remove all navigation items from the current host view:
15 _hostNavigationView.MenuItems().Clear();
16 _hostNavigationView.IsSettingsVisible( false );
17
18 // Build the navigation menu items:
19 for( index = 0; index < _navigationItems.CountOfItems(); index++ )
20 {
21 item = * _navigationItems.GetItemAtIndex( index );
22
23 if( item->identifier == kSettingsItem )
24 {
25 _hostNavigationView.IsSettingsVisible( true );
26 hText = Windows::UI::Xaml::Controls::TextBlock();
27 CSString::ConvertToUIString( item->title->GetString( gAppLanguageCode ), & hTag );
28 hText.Text( hTag );
29// Issue #1 : cannot access to the Settings item
30// _hostNavigationView.SettingsItem().as< Windows::UI::Xaml::Controls::NavigationViewItem >().Content( hText );
31// SettingsItem() returns nullptr...
32 }
33 else
34 {
35 switch( item->type )
36 {
37 case eNavigationHeader:
38 hItem = Windows::UI::Xaml::Controls::NavigationViewItemHeader();
39 hText = Windows::UI::Xaml::Controls::TextBlock();
40 CSString::ConvertToUIString( item->title->GetString( gAppLanguageCode ), & hTag );
41 hText.Text( hTag );
42// Issue #2: The header's title is not displayed
43 hItem.Content( hText );
44 _hostNavigationView.MenuItems().Append( hItem );
45 break;
46
47 case eNavigationSeparator:
48 hItem = Windows::UI::Xaml::Controls::NavigationViewItemSeparator();
49 _hostNavigationView.MenuItems().Append( hItem );
50 break;
51
52 case eNavigationItem:
53 hItem = Windows::UI::Xaml::Controls::NavigationViewItem();
54 CSString::ConvertToUIString( CAUIElement::GetStringFromUIIdentifier( item->identifier ), & hTag );
55 hItem.Tag( winrt::box_value( hTag ) );
56 hText = Windows::UI::Xaml::Controls::TextBlock();
57 CSString::ConvertToUIString( item->title->GetString( gAppLanguageCode ), & hTag );
58 hText.Text( hTag );
59 hItem.Content( hText );
60 hItem.as< Windows::UI::Xaml::Controls::NavigationViewItem>().Icon( GetHostIcon( item->icon ) );
61 _hostNavigationView.MenuItems().Append( hItem );
62 break;
63
64 default:
65 break;
66 }
67 }
68 }
69
70 _hostViewUpdateNeeded = false;
71
72 return true;
73}
74DBG-[000002686A230710]CANavigationView::UpdateDisplayedLanguage() {
75 DBG-[000002686A230710]CANavigationView::UpdateHostView() {
76 DBG-[000002686A230710]CANavigationView::UpdateHostView() Navigation item 0, type 2
77 DBG-[000002686A230710]CANavigationView::UpdateHostView() Header case: Reference Library
78 DBG-[000002686A230710]CANavigationView::UpdateHostView() Navigation item 1, type 1
79 DBG-[000002686A230710]CANavigationView::UpdateHostView() Navigation item case
80 DBG-[000002686A230710]CANavigationView::UpdateHostView() Navigation item 2, type 1
81 DBG-[000002686A230710]CANavigationView::UpdateHostView() Navigation item case
82 DBG-[000002686A230710]CANavigationView::UpdateHostView() Navigation item 3, type 1
83 DBG-[000002686A230710]CANavigationView::UpdateHostView() Navigation item case
84 DBG-[000002686A230710]CANavigationView::UpdateHostView() Navigation item 4, type 3
85 DBG-[000002686A230710]CANavigationView::UpdateHostView() Separator case
86 DBG-[000002686A230710]CANavigationView::UpdateHostView() Navigation item 5, type 2
87 DBG-[000002686A230710]CANavigationView::UpdateHostView() Header case: Project Library
88 DBG-[000002686A230710]CANavigationView::UpdateHostView() Navigation item 6, type 1
89 DBG-[000002686A230710]CANavigationView::UpdateHostView() Navigation item case
90 DBG-[000002686A230710]CANavigationView::UpdateHostView() Navigation item 7, type 1
91 DBG-[000002686A230710]CANavigationView::UpdateHostView() Settings case
92 DBG-[000002686A230710]CANavigationView::UpdateHostView() Value of SettingsItem(): 0000000000000000
93 DBG-[000002686A230710]CANavigationView::UpdateHostView() Count of menu items for the navigation view: 7 (8)
94 DBG-}
95DBG-}
96
Your help in solving those two issues would be greatly appreciated !
Best regards,
Arnaud
ANSWER
Answered 2022-Feb-02 at 11:34Dynamic Headers/Footers enable different grouping options in reports, such as "By Location" or "By Location By System": Note that the words "Report Definitions" are circled above. Although reports can have up to three Dynamic Headers/Footers, some reports only have one or two Dynamic Groups.
QUESTION
With Stripe API, How To Get session_id of Checkout Session That Created a payment_intent Object, From payment_intent.succeeded Webhook
Asked 2022-Jan-31 at 22:04I am working on developing and testing a Stripe integration, written in PHP, and it's working beautifully. I can create sessions, redirect to the checkout form, and when the payments are complete it sends an event to my webhhook script, which successfully processes the information about the payment going through.
When I create a session, I store the data about the form filled out on my site, in a database, and when the payment goes through, I store information in a different table, which is great.
The problem I'm having is that I don't know how to link up the information about the successful payment, with the session that generated it.
Linking up these data is essential to me, because I want to track which sessions actually result in successful payments, so that I can analyze the flow of the user interface and track conversion rates and analyze factors that lead to abandonment of the checkout session.
In some cases, it is easy to link these things up. For example, if there's only one session generated and one successful payment, associated with a given email in a given time-frame, I can just link them up. The problem is that I want to be able to deal with the (likely common) scenario where a person creates multiple sessions and abandons them. I cannot link the payment to the most recent session associated with the email, in this scenario, because it's possible that a single customer would create two sessions, but complete the payment on the first, earlier-created session.
I can't figure out how to access the session_id from the payment_intent object that is returned to my webhook. Some thoughts I have had about how to possibly approach this include:
- Listening for some other event in my webhook script, that occurs, that would possibly allow me to link the two records.
- Passing metadata to the session, such as a uniquely-generated ID, and then accessing that same metadata from the payment_intent object. However I cannot figure out from reading the Stripe documentation how metadata works and even if the metadata is passed from the session to the payment_intent object (the documentation does not explicitly state this or explain it, and the fact that the session_id is not passed makes me wonder if the metadata would be passed at all). I would prefer not to do this solution because it would require the additional step of generating a unique ID before generating the session, which would require more work on my end and also make my code more complex and involve more database calls and more potential steps that can go wrong (currently I am generating the session and then storing the information in response to the successful creation of the session), but I could tolerate it if there are really no better options.
I would like to follow "best practices" here, but it's not clear to me how Stripe intends people to link up or access the data, or if this is perhaps an oversight on their end.
If you give me example code I would prefer seeing it in PHP if possible but you don't need to show me any code at all; just giving me an abstract or general idea of how to accomplish this would be sufficient and I could come up with the coding details on my own.
ANSWER
Answered 2021-Nov-10 at 00:01The payment_intent.succeeded
event gives you the PaymentIntent ID. You can use the CheckoutSessions "list" endpoint [0] to get the CheckoutSession that used that PaymentIntent ID by passing the payment_method
parameter.
[0] https://stripe.com/docs/api/checkout/sessions/list#list_checkout_sessions-payment_intent
QUESTION
Is it safe to store, access and HTMLElement objects directly inside an object, vs. relying on CSS selectors?
Asked 2022-Jan-22 at 09:00I have a vanilla Javascript class that builds a bunch of HTML, essentially a collection of related HTMLElement objects that form the user interface for a component, and appends them to the HTML document. The class implements controller logic, responding to events, mutating some of the HTMLElements etc.
My gut instinct (coming from more backend development experience) is to store those HTMLElement objects inside my class, whether inside a key/value object or in an array, so my class can just access them directly through native properties whenever it's doing something with them. But everything I look at seems to follow the pattern of relying on document selectors (document.getElementById
, getElementsByClassName
, etc etc). I understand the general utility of that approach but it feels weird to have a class that creates objects, discards its own references to them, and then just looks them back up again when needed.
A simplified example would look like this:
1<html>
2<body>
3<script>
4/* Silly implementation of the "Concentration" memory match game.
5 This is just a S/O example but it should actually work =P
6 */
7
8class SymbolMatchGame {
9
10 constructor(symbolsArray) {
11 this.symbols = symbolsArray.concat(symbolsArray); // we want two of every item
12 this.allButtons = [];
13 this.lastButtonClicked = null;
14 }
15
16 shuffle() {
17 for (let i = this.symbols.length - 1; i > 0; i--) {
18 const j = Math.floor(Math.random() * (i + 1));
19 const temp = this.symbols[i];
20 this.symbols[i] = this.symbols[j];
21 this.symbols[j] = temp;
22 }
23 }
24
25 build(parentElement) {
26 document.body.innerHTML = '';
27 this.shuffle();
28 const rowSize = Math.floor(Math.sqrt(this.symbols.length));
29 for (let i = 0; i < this.symbols.length; i++) {
30 const button = document.createElement('input');
31 button.type = 'button';
32 button.setAttribute('secret-value', this.symbols[i]);
33 button.value = ' ';
34 button.onclick = (event) => this.turnOver(event);
35 this.allButtons.push(button);
36 document.body.appendChild(button);
37 if ((i+1) % rowSize === 0) {
38 const lineBreak = document.createElement('br');
39 document.body.appendChild(lineBreak);
40 }
41 }
42 }
43
44 turnOver(event) {
45 const button = event.target;
46 if (this.lastButtonClicked === null) {
47 this.allButtons.forEach(button => button.value = button.disabled ? button.value : ' ');
48 this.lastButtonClicked = button;
49 } else if (button === this.lastButtonClicked) {
50 button.value = ' ';
51 this.lastButtonClicked = null;
52 } else {
53 if (button.getAttribute('secret-value') === this.lastButtonClicked.getAttribute('secret-value')) {
54 console.log('Match found!');
55 button.disabled = true;
56 this.lastButtonClicked.disabled = true;
57 } else {
58 console.log('No match!');
59 }
60 this.lastButtonClicked = null;
61 }
62 button.value = button.getAttribute('secret-value');
63 if (this.gameIsSolved()) {
64 alert('You did it! Game will reset.')
65 this.build();
66 }
67 }
68
69 gameIsSolved() {
70 const remainingButtons = game.allButtons.filter(button => !button.disabled)
71 return remainingButtons.length === 0;
72 }
73
74}
75
76const alphabetArray = Array.from(Array(8).keys()).map(k => String.fromCharCode(k+65));
77game = new SymbolMatchGame(alphabetArray);
78game.build();
79</script>
80</body>
81</html>
82
(Note: I'm not expecting you to examine this code in detail; just illustrating what I mean when I talk about storing element references in the class and accessing them directly instead of via document.get*
lookups)
I don't want this to be a style/"best practice" question that isn't appropriate for S/O, so I'm more looking for concrete information about whether my approach actually works the way I think it does. My question: what are the implications or side effects of what I'm doing? Is storing references to created elements inside my class instead of of a "just in time" document.get*
lookup every time I want to access or modify them unsafe in some way, prone to side effects or stale references, or otherwise lacking implicit guarantees about document state, that might break things on me?
ANSWER
Answered 2022-Jan-22 at 09:00In general, you should always cache DOM elements when they're needed later, were you using OOP or not. DOM is huge, and fetching elements continuously from it is really time-consuming. This stands for the properties of the elements too. Creating a JS variable or a property to an object is cheap, and accessing it later is lightning-fast compared to DOM queries.
Many of the properties of the elements are deep in the prototype chain, they're often getters, which might execute a lot of hidden DOM traversing, and reading specific DOM values forces layout recalculation in the middle of JS execution. All this makes DOM usage slow. Instead, create a simplified JavaScript model of the page, and store all the needed elements and values to the model whenever possible.
A big part of OOP is just keeping up states, that's the key of the model too. In the model you keep up the state of the view, and access the DOM only when you need to change the view. Such a model will prevent a lot of "layout trashing", and it allows you to bind data to elements without actually revealing it in the global namespace (ex. Map object is a great tool for this). Nothing beats good encapsulation when you've security concerns, it's an effective way ex. to prevent self-XSS. Additionally, a good model is reusable, you can use it where ever the functionality is needed, the end-user just parametrizes the model when taken into use. That way the model is almost independent from the used markup too, and can also be developed independently (see also Separation of concerns).
A caveat of storing DOM elements into object properties (or into JS variables in general) is, that it's an easy way to create memory leaks. Such model objects are usually having long life-time, and if elements are removed from the DOM, the references from the object have to be deleted as well in order to get the removed elements being garbage-collected.
In practice this means, that you've to provide methods for removing elements, and only those methods should be used to delete elements. Additionally to the element removal, the methods should update the model object, and remove all the unused element references from the object.
It's notable, that when having methods handling existing elements, and specifically when creating new elements, it's easy to create variables which are stored in closures. When such a stored variable contains references to elements, they can't be removed from the memory even with the aforementioned removing methods. The only way is to avoid creating these closures from the beginning, which might be a bit easier with OOP compared to other paradigms (by avoiding variables and creating the elements directly to the properties of the objects).
As a sidenote, document.getElementsBy*
methods are the worst possible way to get references to DOM elements. The idea of the live collection of the elements sounds nice, but the way how those are implemented, ruins the good idea.
QUESTION
How to increase height of jQueryUI selectmenu?
Asked 2022-Jan-04 at 13:00How can I increase the height of a select menu styled with jQuery's user interface? I want to increase the height of the actual element, not the height of the dropdown menu of options that appears when you click it (there are a few answers on the site already for that). Basically, I want the menu to look squared, almost like a button instead.
I tried setting the height at the moment of applying the UI to the element in javascript. However, any height value I use seems to be ignored:
1$(document).ready(function() {
2
3 let testSelect = document.createElement('select');
4 let firstOption = document.createElement('option');
5 firstOption.text = 'blablablabla...';
6 firstOption.defaultSelected = true;
7 testSelect.appendChild(firstOption);
8
9 document.getElementById('testDiv').appendChild(testSelect);
10 $(testSelect).selectmenu({height: '50%'}); // no matter what value of height I use, the menu does not change
11
12 testButton = document.createElement('button');
13 testButton.innerHTML = 'Like this example button';
14 $(testButton).button();
15 document.getElementById('testDiv').appendChild(testButton); // I want the select menu to look similar to a button like this
16
17});
1$(document).ready(function() {
2
3 let testSelect = document.createElement('select');
4 let firstOption = document.createElement('option');
5 firstOption.text = 'blablablabla...';
6 firstOption.defaultSelected = true;
7 testSelect.appendChild(firstOption);
8
9 document.getElementById('testDiv').appendChild(testSelect);
10 $(testSelect).selectmenu({height: '50%'}); // no matter what value of height I use, the menu does not change
11
12 testButton = document.createElement('button');
13 testButton.innerHTML = 'Like this example button';
14 $(testButton).button();
15 document.getElementById('testDiv').appendChild(testButton); // I want the select menu to look similar to a button like this
16
17});<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
18<script type="text/javascript" src="https://code.jquery.com/ui/1.13.0/jquery-ui.min.js"></script>
19<link rel="stylesheet" href="http://code.jquery.com/ui/1.13.0/themes/redmond/jquery-ui.css">
20
21<div id="testDiv" style="width:100px; height:100px;"></div>
ANSWER
Answered 2022-Jan-04 at 13:00you forget to use .css()
function to add the css of height. add .css(height:100px)
and then you will get your height
QUESTION
Is a work manager good for these situations?
Asked 2022-Jan-02 at 00:08I'm developing some features that need to run in the background with a UI update like creating a file from the input stream and notifying the user after it's finished
After trying the work manager for this task. It works well, but is it a good option in your opinion?
Note: I am very interested in updating the user interface during the process and as you know async task deprecated
ANSWER
Answered 2022-Jan-02 at 00:08Yes. Initially, WorkManager
was a library for managing defferable background work. Now however, WorkManager
is a recommended solution for any persistent work, that is, the work that must be completed - no matter if the application process is stopped, or even the device is rebooted. From version 2.3.0-alpha01
, WorkManager
provides first-class support for setting and observing intermediate progress for workers. Updatig the user interface is exactly what this feature can be used for.
For me the easiest way to reason about WorkManager is an extension of your app scopes:
Activity
Scope - the works lives untilonDestroy
lifecycle eventViewModel
Scope - the works lives as long as ViewModel. If you navigate away - the work is stoppedApplication
Scope (eg. Coroutine'sGlobalScope
) - the work lives as long as applcation process. If the user ends the app process in task manager or the system kills it - the work is lostWorkManager
- the work survives process death and device reboot. It is persisted with help of Room DB under the hood, so that you can continue the work after your application process was restarted.
QUESTION
Data exchange between websocket clients and server
Asked 2021-Dec-20 at 01:50I have a system that has a fastAPI server, a python client implemented on Raspberry and Javascript clients for the user interface. Data is sent from python client to server then forwarded to Js client and vice versa. I established the connection between the server and each type of client but when sending from a client-side to the server, it just send back to that client and the rest ones receive nothing. What is the proper way to deal with this problem? Hope for your help. Thanks.
ANSWER
Answered 2021-Dec-20 at 01:50The problem with websocket is it doesn't support broadcasting. You can store somewhere list of connected clients and iterate over them to send a message
1CLIENTS = set()
2async def broadcast():
3 while True:
4 await asyncio.gather(
5 *[ws.send("woof") for ws in CLIENTS],
6 return_exceptions=False,
7 )
8 await asyncio.sleep(2)
9
10asyncio.create_task(broadcast())
11
12async def handler(websocket, path):
13 CLIENTS.add(websocket)
14 try:
15 async for msg in websocket:
16 pass
17 finally:
18 CLIENTS.remove(websocket)
19
20start_server = websockets.serve(handler, ...)
21
22asyncio.get_event_loop().run_until_complete(start_server)
23asyncio.get_event_loop().run_forever()
24
QUESTION
Register all inputs inside a multi-page data table
Asked 2021-Dec-17 at 16:15I have a datatable in which I've added checkboxes for my users to select various options. Unfortunately, the only inputs that shiny seems to see are ones that have been displayed in the table. So if I have multiple pages, I'm only able to see the first 10 inputs.
In the example below, I've printed all of the inputs that I can see registered above the datatable object. At the moment, I only see the first 10 inputs (A - J). I'd like to be able to see all 26 when the table first loads (without having to toggle through the pages).
In my actual application, I have multiple columns of checkboxes, so row selection wouldn't be sufficient. Any tips or suggestions on how to register all 26 inputs at once?
1library(shiny)
2library(DT)
3
4shinyInput <- function (FUN, id_base, suffix, label = "", ...)
5{
6 inputId <- paste0(id_base, suffix)
7 args <- list(...)
8 args <- c(list(label = label), args)
9 args <- lapply(args, function(a) rep(a, length.out = length(inputId)))
10 rv <- character(length(inputId))
11 for (i in seq_along(rv)) {
12 this_arg <- lapply(args, `[`, i)
13 ctrl <- do.call(FUN, c(list(inputId = inputId[i]), this_arg))
14 rv[i] <- as.character(ctrl)
15 }
16 rv
17}
18
19X <- data.frame(id = LETTERS,
20 selected = sample(c(TRUE, FALSE),
21 size = length(LETTERS),
22 replace = TRUE))
23
24X$IsSelected <-
25 shinyInput(
26 shiny::checkboxInput,
27 id_base = "new_input_",
28 suffix = X$id,
29 value = X$selected
30 )
31
32shinyApp(
33 ui = fluidPage(
34 verbatimTextOutput("value_check"),
35 textOutput("input_a_value"),
36 DT::dataTableOutput("dt")
37 ),
38
39 server = shinyServer(function(input, output, session){
40
41 Data <- reactiveValues(
42 X = X
43 )
44
45 output$value_check <-
46 renderPrint({
47 sort(names(input))
48 })
49
50 output$dt <-
51 DT::renderDataTable({
52
53
54 DT::datatable(X,
55 selection = "none",
56 escape = FALSE,
57 filter = "top",
58 #rownames = FALSE,
59 class = "compact cell-border",
60 options = list(preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
61 drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')))
62 })
63 })
64)
65
This next example is a bit more complex, but illustrates a bit more of the motivation for the question. It seems the biggest issue is that I would like to utilize buttons such as "select all." Additionally, I'm not processing any actions immediately when a box is interacted with. Instead, the user makes their selections, and the selections are not saved until the "Save Selections" button is clicked.
What is happening is I click on the "Select All" button, and it checks all of the boxes for inputs that have been drawn already. If I've only viewed the first page of the table, it updates only those inputs, and none of the inputs on the next few pages. This is really the behavior I need to change.
1library(shiny)
2library(DT)
3
4shinyInput <- function (FUN, id_base, suffix, label = "", ...)
5{
6 inputId <- paste0(id_base, suffix)
7 args <- list(...)
8 args <- c(list(label = label), args)
9 args <- lapply(args, function(a) rep(a, length.out = length(inputId)))
10 rv <- character(length(inputId))
11 for (i in seq_along(rv)) {
12 this_arg <- lapply(args, `[`, i)
13 ctrl <- do.call(FUN, c(list(inputId = inputId[i]), this_arg))
14 rv[i] <- as.character(ctrl)
15 }
16 rv
17}
18
19X <- data.frame(id = LETTERS,
20 selected = sample(c(TRUE, FALSE),
21 size = length(LETTERS),
22 replace = TRUE))
23
24X$IsSelected <-
25 shinyInput(
26 shiny::checkboxInput,
27 id_base = "new_input_",
28 suffix = X$id,
29 value = X$selected
30 )
31
32shinyApp(
33 ui = fluidPage(
34 verbatimTextOutput("value_check"),
35 textOutput("input_a_value"),
36 DT::dataTableOutput("dt")
37 ),
38
39 server = shinyServer(function(input, output, session){
40
41 Data <- reactiveValues(
42 X = X
43 )
44
45 output$value_check <-
46 renderPrint({
47 sort(names(input))
48 })
49
50 output$dt <-
51 DT::renderDataTable({
52
53
54 DT::datatable(X,
55 selection = "none",
56 escape = FALSE,
57 filter = "top",
58 #rownames = FALSE,
59 class = "compact cell-border",
60 options = list(preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
61 drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')))
62 })
63 })
64)
65# Set up environment ------------------------------------------------
66library(shiny)
67library(DT)
68library(magrittr)
69
70# Example of data coming from the database. -------------------------
71
72set.seed(pi^2)
73
74SourceData <-
75 data.frame(sample_id = 1:25,
76 is_selected = sample(c(TRUE, FALSE), 25, replace = TRUE))
77
78
79# Support Functions -------------------------------------------------
80# These would exist, for example, in an internal package
81
82shinyInput <- function (FUN, id_base, suffix, label = "", ...)
83{
84 inputId <- paste0(id_base, suffix)
85 args <- list(...)
86 args <- c(list(label = label), args)
87 args <- lapply(args, function(a) rep(a, length.out = length(inputId)))
88 rv <- character(length(inputId))
89 for (i in seq_along(rv)) {
90 this_arg <- lapply(args, `[`, i)
91 ctrl <- do.call(FUN, c(list(inputId = inputId[i]), this_arg))
92 rv[i] <- as.character(ctrl)
93 }
94 rv
95}
96
97prepareDataForDisplay <- function(Data){
98 Data$is_selected <-
99 shinyInput(shiny::checkboxInput,
100 id_base = "is_selected_",
101 suffix = Data$sample_id,
102 value = Data$is_selected)
103
104 Data
105}
106
107# User Interface ----------------------------------------------------
108
109ui <-
110 fluidPage(
111 verbatimTextOutput("value_check"),
112
113 actionButton(inputId = "btn_saveSelection",
114 label = "Save Selection"),
115 actionButton(inputId = "btn_selectAll",
116 label = "Select All"),
117 actionButton(inputId = "btn_unselectAll",
118 label = "Unselect All"),
119 actionButton(inputId = "btn_restoreDefault",
120 label = "Restore Default (select odd only)"),
121
122 DT::dataTableOutput("dt")
123 )
124
125# Server ------------------------------------------------------------
126
127server <-
128 shinyServer(function(input, output, session){
129
130 # Event Observers -----------------------------------------------
131
132 observeEvent(
133 input$btn_selectAll,
134 {
135 check_input <- names(input)[grepl("is_selected_", names(input))]
136
137 lapply(check_input,
138 function(ci){
139 updateCheckboxInput(session = session,
140 inputId = ci,
141 value = TRUE)
142 })
143 }
144 )
145
146 observeEvent(
147 input$btn_unselectAll,
148 {
149 check_input <- names(input)[grepl("is_selected_", names(input))]
150
151 lapply(check_input,
152 function(ci){
153 updateCheckboxInput(session = session,
154 inputId = ci,
155 value = FALSE)
156 })
157 }
158 )
159
160 observeEvent(
161 input$btn_restoreDefault,
162 {
163 check_input <- names(input)[grepl("is_selected_", names(input))]
164
165 lapply(check_input,
166 function(ci){
167 id <- as.numeric(sub("is_selected_", "", ci))
168
169 updateCheckboxInput(session = session,
170 inputId = ci,
171 value = id %% 2 == 1)
172 })
173 }
174 )
175
176 observeEvent(
177 input$btn_saveSelection,
178 {
179 check_input <- names(input)[grepl("is_selected_", names(input))]
180
181 id <- as.numeric(sub("is_selected_", "", check_input))
182
183 for (i in seq_along(check_input)){
184 SourceData$is_selected[SourceData$sample_id == id[i]] <-
185 input[[check_input[i]]]
186 }
187
188 # At this point, I would also save changes to the remote database.
189
190 DT::replaceData(proxy = dt_proxy,
191 data = prepareDataForDisplay(SourceData))
192 }
193 )
194
195 # Output elements -----------------------------------------------
196
197 output$value_check <-
198 renderPrint({
199 sort(names(input))
200 })
201
202 output$dt <-
203 DT::renderDataTable({
204 SourceData %>%
205 prepareDataForDisplay() %>%
206 DT::datatable(selection = "none",
207 escape = FALSE,
208 filter = "top",
209 class = "compact cell-border",
210 options = list(preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
211 drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')))
212 })
213
214 dt_proxy <- DT::dataTableProxy("dt")
215
216 })
217
218# Run the application -----------------------------------------------
219
220shinyApp(
221 ui = ui,
222 server = server
223)
224
ANSWER
Answered 2021-Dec-17 at 16:15Here is a workaround based on your addendum (not sure if you need the changes regarding btn_restoreDefault
and btn_saveSelection
), but the general procedure should be clear:
1library(shiny)
2library(DT)
3
4shinyInput <- function (FUN, id_base, suffix, label = "", ...)
5{
6 inputId <- paste0(id_base, suffix)
7 args <- list(...)
8 args <- c(list(label = label), args)
9 args <- lapply(args, function(a) rep(a, length.out = length(inputId)))
10 rv <- character(length(inputId))
11 for (i in seq_along(rv)) {
12 this_arg <- lapply(args, `[`, i)
13 ctrl <- do.call(FUN, c(list(inputId = inputId[i]), this_arg))
14 rv[i] <- as.character(ctrl)
15 }
16 rv
17}
18
19X <- data.frame(id = LETTERS,
20 selected = sample(c(TRUE, FALSE),
21 size = length(LETTERS),
22 replace = TRUE))
23
24X$IsSelected <-
25 shinyInput(
26 shiny::checkboxInput,
27 id_base = "new_input_",
28 suffix = X$id,
29 value = X$selected
30 )
31
32shinyApp(
33 ui = fluidPage(
34 verbatimTextOutput("value_check"),
35 textOutput("input_a_value"),
36 DT::dataTableOutput("dt")
37 ),
38
39 server = shinyServer(function(input, output, session){
40
41 Data <- reactiveValues(
42 X = X
43 )
44
45 output$value_check <-
46 renderPrint({
47 sort(names(input))
48 })
49
50 output$dt <-
51 DT::renderDataTable({
52
53
54 DT::datatable(X,
55 selection = "none",
56 escape = FALSE,
57 filter = "top",
58 #rownames = FALSE,
59 class = "compact cell-border",
60 options = list(preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
61 drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')))
62 })
63 })
64)
65# Set up environment ------------------------------------------------
66library(shiny)
67library(DT)
68library(magrittr)
69
70# Example of data coming from the database. -------------------------
71
72set.seed(pi^2)
73
74SourceData <-
75 data.frame(sample_id = 1:25,
76 is_selected = sample(c(TRUE, FALSE), 25, replace = TRUE))
77
78
79# Support Functions -------------------------------------------------
80# These would exist, for example, in an internal package
81
82shinyInput <- function (FUN, id_base, suffix, label = "", ...)
83{
84 inputId <- paste0(id_base, suffix)
85 args <- list(...)
86 args <- c(list(label = label), args)
87 args <- lapply(args, function(a) rep(a, length.out = length(inputId)))
88 rv <- character(length(inputId))
89 for (i in seq_along(rv)) {
90 this_arg <- lapply(args, `[`, i)
91 ctrl <- do.call(FUN, c(list(inputId = inputId[i]), this_arg))
92 rv[i] <- as.character(ctrl)
93 }
94 rv
95}
96
97prepareDataForDisplay <- function(Data){
98 Data$is_selected <-
99 shinyInput(shiny::checkboxInput,
100 id_base = "is_selected_",
101 suffix = Data$sample_id,
102 value = Data$is_selected)
103
104 Data
105}
106
107# User Interface ----------------------------------------------------
108
109ui <-
110 fluidPage(
111 verbatimTextOutput("value_check"),
112
113 actionButton(inputId = "btn_saveSelection",
114 label = "Save Selection"),
115 actionButton(inputId = "btn_selectAll",
116 label = "Select All"),
117 actionButton(inputId = "btn_unselectAll",
118 label = "Unselect All"),
119 actionButton(inputId = "btn_restoreDefault",
120 label = "Restore Default (select odd only)"),
121
122 DT::dataTableOutput("dt")
123 )
124
125# Server ------------------------------------------------------------
126
127server <-
128 shinyServer(function(input, output, session){
129
130 # Event Observers -----------------------------------------------
131
132 observeEvent(
133 input$btn_selectAll,
134 {
135 check_input <- names(input)[grepl("is_selected_", names(input))]
136
137 lapply(check_input,
138 function(ci){
139 updateCheckboxInput(session = session,
140 inputId = ci,
141 value = TRUE)
142 })
143 }
144 )
145
146 observeEvent(
147 input$btn_unselectAll,
148 {
149 check_input <- names(input)[grepl("is_selected_", names(input))]
150
151 lapply(check_input,
152 function(ci){
153 updateCheckboxInput(session = session,
154 inputId = ci,
155 value = FALSE)
156 })
157 }
158 )
159
160 observeEvent(
161 input$btn_restoreDefault,
162 {
163 check_input <- names(input)[grepl("is_selected_", names(input))]
164
165 lapply(check_input,
166 function(ci){
167 id <- as.numeric(sub("is_selected_", "", ci))
168
169 updateCheckboxInput(session = session,
170 inputId = ci,
171 value = id %% 2 == 1)
172 })
173 }
174 )
175
176 observeEvent(
177 input$btn_saveSelection,
178 {
179 check_input <- names(input)[grepl("is_selected_", names(input))]
180
181 id <- as.numeric(sub("is_selected_", "", check_input))
182
183 for (i in seq_along(check_input)){
184 SourceData$is_selected[SourceData$sample_id == id[i]] <-
185 input[[check_input[i]]]
186 }
187
188 # At this point, I would also save changes to the remote database.
189
190 DT::replaceData(proxy = dt_proxy,
191 data = prepareDataForDisplay(SourceData))
192 }
193 )
194
195 # Output elements -----------------------------------------------
196
197 output$value_check <-
198 renderPrint({
199 sort(names(input))
200 })
201
202 output$dt <-
203 DT::renderDataTable({
204 SourceData %>%
205 prepareDataForDisplay() %>%
206 DT::datatable(selection = "none",
207 escape = FALSE,
208 filter = "top",
209 class = "compact cell-border",
210 options = list(preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
211 drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')))
212 })
213
214 dt_proxy <- DT::dataTableProxy("dt")
215
216 })
217
218# Run the application -----------------------------------------------
219
220shinyApp(
221 ui = ui,
222 server = server
223)
224# Set up environment ------------------------------------------------
225library(shiny)
226library(DT)
227library(magrittr)
228
229# Example of data coming from the database. -------------------------
230
231set.seed(pi^2)
232
233SourceData <-
234 data.frame(sample_id = 1:25,
235 is_selected = sample(c(TRUE, FALSE), 25, replace = TRUE))
236
237
238# Support Functions -------------------------------------------------
239# These would exist, for example, in an internal package
240
241shinyInput <- function (FUN, id_base, suffix, label = "", ...)
242{
243 inputId <- paste0(id_base, suffix)
244 args <- list(...)
245 args <- c(list(label = label), args)
246 args <- lapply(args, function(a) rep(a, length.out = length(inputId)))
247 rv <- character(length(inputId))
248 for (i in seq_along(rv)) {
249 this_arg <- lapply(args, `[`, i)
250 ctrl <- do.call(FUN, c(list(inputId = inputId[i]), this_arg))
251 rv[i] <- as.character(ctrl)
252 }
253 rv
254}
255
256prepareDataForDisplay <- function(Data){
257 Data$is_selected <-
258 shinyInput(shiny::checkboxInput,
259 id_base = "is_selected_",
260 suffix = Data$sample_id,
261 value = Data$is_selected)
262
263 Data
264}
265
266# User Interface ----------------------------------------------------
267
268ui <-
269 fluidPage(
270 verbatimTextOutput("value_check"),
271
272 actionButton(inputId = "btn_saveSelection",
273 label = "Save Selection"),
274 actionButton(inputId = "btn_selectAll",
275 label = "Select All"),
276 actionButton(inputId = "btn_unselectAll",
277 label = "Unselect All"),
278 actionButton(inputId = "btn_restoreDefault",
279 label = "Restore Default (select odd only)"),
280
281 DT::dataTableOutput("dt")
282 )
283
284# Server ------------------------------------------------------------
285
286server <-
287 shinyServer(function(input, output, session){
288
289 # Event Observers -----------------------------------------------
290
291 observeEvent(
292 input$btn_selectAll,
293 {
294 TmpData <- SourceData
295 TmpData$is_selected <- TRUE
296 replaceData(dt_proxy, prepareDataForDisplay(TmpData))
297 }
298 )
299
300 observeEvent(
301 input$btn_unselectAll,
302 {
303 TmpData <- SourceData
304 TmpData$is_selected <- FALSE
305 replaceData(dt_proxy, prepareDataForDisplay(TmpData))
306 }
307 )
308
309 observeEvent(
310 input$btn_restoreDefault,
311 {
312 replaceData(dt_proxy, prepareDataForDisplay(SourceData))
313 }
314 )
315
316 observeEvent(
317 input$btn_saveSelection,
318 {
319
320 check_input <- names(input)[grepl("is_selected_", names(input))]
321
322 id <- as.numeric(sub("is_selected_", "", check_input))
323
324 TmpData <- SourceData
325
326 for (i in seq_along(check_input)){
327 TmpData$is_selected[TmpData$sample_id == id[i]] <-
328 input[[check_input[i]]]
329 }
330
331 # At this point, I would also save changes to the remote database.
332
333 DT::replaceData(proxy = dt_proxy,
334 data = prepareDataForDisplay(TmpData))
335 }
336 )
337
338 # Output elements -----------------------------------------------
339
340 output$value_check <-
341 renderPrint({
342 sort(names(input))
343 })
344
345 output$dt <-
346 DT::renderDataTable({
347 SourceData %>%
348 prepareDataForDisplay() %>%
349 DT::datatable(selection = "none",
350 escape = FALSE,
351 filter = "top",
352 class = "compact cell-border",
353 options = list(preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
354 drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')))
355 })
356
357 dt_proxy <- DT::dataTableProxy("dt")
358
359 })
360
361# Run the application -----------------------------------------------
362
363shinyApp(
364 ui = ui,
365 server = server
366)
367
Community Discussions contain sources that include Stack Exchange Network