Explore all Gaming open source software, libraries, packages, source code, cloud functions and APIs.

Explore Related Topics

Popular New Releases in Gaming

godot

3.4.4-stable

phaser

Phaser v3.55.2

libgdx

1.10.0

Proton

Proton 7.0-2

aseprite

Aseprite v1.3-beta14

Popular Libraries in Gaming

godot

by godotengine doticonc++doticon

star image 47538 doticonNOASSERTION

Godot Engine – Multi-platform 2D and 3D game engine

phaser

by photonstorm doticonjavascriptdoticon

star image 30320 doticonMIT

Phaser is a fun, free and fast 2D game framework for making HTML5 games for desktop and mobile web browsers, supporting Canvas and WebGL rendering.

libgdx

by libgdx doticonjavadoticon

star image 19612 doticonNOASSERTION

Desktop/Android/HTML5/iOS Java game development framework

Proton

by ValveSoftware doticonc++doticon

star image 16918 doticonNOASSERTION

Compatibility tool for Steam Play based on Wine and additional components

aseprite

by aseprite doticonc++doticon

star image 16876 doticon

Animated sprite editor & pixel art tool (Windows, macOS, Linux)

Babylon.js

by BabylonJS doticontypescriptdoticon

star image 16566 doticonApache-2.0

Babylon.js is a powerful, beautiful, simple, and open game and rendering engine packed into a friendly JavaScript framework.

bevy

by bevyengine doticonrustdoticon

star image 15512 doticonNOASSERTION

A refreshingly simple data-driven game engine built in Rust

cocos2d-x

by cocos2d doticonc++doticon

star image 15461 doticon

Cocos2d-x is a suite of open-source, cross-platform, game-development tools used by millions of developers all over the world.

Mindustry

by Anuken doticonjavadoticon

star image 14308 doticonGPL-3.0

The automation tower defense game

Trending New libraries in Gaming

bevy

by bevyengine doticonrustdoticon

star image 15512 doticonNOASSERTION

A refreshingly simple data-driven game engine built in Rust

shapez.io

by tobspr doticonjavascriptdoticon

star image 4851 doticonGPL-3.0

shapez.io is an open source base building game inspired by factorio! Available on web & steam

jynew

by jynew doticoncsharpdoticon

star image 4611 doticonNOASSERTION

金庸群侠传3D重制版

o3de

by o3de doticonc++doticon

star image 4538 doticonNOASSERTION

Open 3D Engine (O3DE) is an Apache 2.0-licensed multi-platform 3D engine that enables developers and content creators to build AAA games, cinema-quality 3D worlds, and high-fidelity simulations without any fees or commercial obligations.

open-project-1

by UnityTechnologies doticoncsharpdoticon

star image 3966 doticonApache-2.0

Unity Open Project #1: Chop Chop

FlaxEngine

by FlaxEngine doticonc++doticon

star image 3219 doticonNOASSERTION

Flax Engine – multi-platform 3D game engine

sodium-fabric

by CaffeineMC doticonjavadoticon

star image 3168 doticonLGPL-3.0

A Fabric mod designed to improve frame rates and reduce micro-stutter

legendary

by derrod doticonpythondoticon

star image 2928 doticonGPL-3.0

Legendary - A free and open-source replacement for the Epic Games Launcher

HeroicGamesLauncher

by Heroic-Games-Launcher doticontypescriptdoticon

star image 2830 doticonGPL-3.0

A Native GOG and Epic Games Launcher for Linux, Windows and Mac.

Top Authors in Gaming

1

svn2github

157 Libraries

star icon1392

2

keijiro

110 Libraries

star icon10096

3

Unity-Technologies

63 Libraries

star icon33694

4

PacktPublishing

56 Libraries

star icon1041

5

microsoft

51 Libraries

star icon12412

6

Terasology

39 Libraries

star icon206

7

baba-s

33 Libraries

star icon149

8

KDE

33 Libraries

star icon243

9

MinecraftModDevelopmentMods

31 Libraries

star icon214

10

thebigsmileXD

29 Libraries

star icon479

1

157 Libraries

star icon1392

2

110 Libraries

star icon10096

3

63 Libraries

star icon33694

4

56 Libraries

star icon1041

5

51 Libraries

star icon12412

6

39 Libraries

star icon206

7

33 Libraries

star icon149

8

33 Libraries

star icon243

10

29 Libraries

star icon479

Trending Kits in Gaming

Here are some of the famous C# Game Development Libraries. C# Game Development Libraries use cases include 2D & 3D Rendering, Physics Simulation, AI, Audio, and Networking. 


C# Game Development libraries refer to libraries of code specifically designed for the development of video games using the C# programming language. These libraries can provide developers with access to a wide range of features and functions, such as graphics, audio, physics, networking, and artificial intelligence, which can be used to create a rich and immersive gaming experience. 


Let us have a look at these libraries in detail. 

OpenRA 

  • Provides a powerful modding framework. 
  • A strong community of developers and players. 
  • Uses a powerful 3D rendering engine to create beautiful and detailed game worlds. 

MonoGame 

  • The content pipeline makes it easy to import and optimize assets for use in games.  
  • The active community of developers is willing to help with any questions or issues.  
  • Supports multiple platforms, including Windows, Mac, Linux, iOS, Android, Xbox, PlayStation, and Nintendo Switch. 

ET 

  • The powerful level editor lets you create custom game levels with ease.  
  • Built-in networking system that makes it easy to create and play multiplayer games.  
  • The built-in physics engine makes it easy to create realistic environments and objects. 

Entitas-CSharp 

  • Event-based Reactive System. 
  • Component-Based Entity System. 
  • Built-in Debugging Tools. 

Stride 

  • Provides an easy-to-use and powerful Scene System that allows developers to quickly and easily create 3D scenes. 
  • Provides an intuitive Material system that allows for easy customization of game objects. 
  • Offers a powerful and extensible audio system.  

GameFramework 

  • Extensive component system. 
  • Extensive documentation. 
  • Customizable game architecture. 

Opentk 

  • Provides an easy way to read user input from keyboards, mice, and joysticks. 
  • Provides a comprehensive math library, which includes functions for vector, matrix, and quaternion operations. 
  • Provides a threading library, which allows developers to create and manage multiple threads in their application. 

UnrealCLR 

  • Allows developers to create complex game mechanics with a minimal amount of code. 
  • Allows developers to access all of the features of Unreal Engine with a single API. 
  • Allows developers to create games for both Windows and MacOS.  

gosu 

  • Built-in support for gamepad and joystick controls. 
  • Built-in game loop and event system make handling user input and game logic easy.  
  • The built-in physics engine allows for realistic collisions and movement in games. 

ezy-slice 

  • Supports custom shaders. 
  • Provides an advanced scene management system. 
  • Designed to be easy to integrate with existing C# game development projects.  

ForgeNetworkingRemastered 

  • Built-in support for both authoritative server and client-side prediction. 
  • Allows developers to integrate real-time chat and streaming services into their games easily.  
  • It makes it easy for developers to add networking functionality to their games quickly. 

Duality 

  • Built around a data-oriented approach to game development. 
  • Offers a wide range of features, such as a built-in scene editor. 
  • Codebase is available for developers to inspect and modify as needed. 

UtilityGameFramework 

  • Powerful modularity and extensibility. 
  • Efficient resource management. 
  • Robust game debugging tools. 

Osu-Framework 

  • Large library of premade game objects, like characters, levels, and objects. 
  • Includes a powerful scripting language, allowing developers to prototype new game ideas quickly. 
  • Designed to be completely cross-platform. 

OpenSAGE 

  • Built on top of the .NET Core platform. 
  • Designed for the development of real-time strategy (RTS) games. 
  • Provides high-performance game development tools. 

SadConsole 

  • Supports a range of input methods, including keyboard, mouse, and controller. 
  • Provides an integrated debugging console for developers to monitor their game’s performance easily.   
  • Specifically built for console-style RPG games, providing a unique retro look and feel. 

Here are some of the famous C# Networking Libraries. C# Networking Libraries use cases include Building a Chat Application, Building an Online Multiplayer Game, building a Networked File Sharing Application, building a Networked Database Application, and Building a Networked Streaming Media Application.  


C# networking libraries are the collection of classes and functions used to develop C# programming language network applications. These libraries provide functionality such as networking protocols, data transfer, encryption, and data storage. Examples of C# networking libraries include the .NET Framework Network Classes, System.Net, and OpenNETCF.  


Let us have a look at these libraries in detail below. 

mRemoteNG 

  • Supports many protocols such as RDP, VNC, SSH, Telnet, HTTP/HTTPS, and ICA/HDX. 
  • Rich plugin system to extend the functionality of the application. 
  • Powerful scripting engine to automate common tasks. 

websocket-sharp 

  • Supports the latest websocket protocol specifications. 
  • Supports compression of websocket frames using the Per-Message Deflate extension. 
  • Actively maintained and regularly updated with new features and bug fixes. 

protobuf-net 

  • Serialization and Deserialization. 
  • Compact Binary Format. 
  • Supports Multiple Platforms. 

DotNetty 

  • Event-driven API. 
  • Protocol Agnostic. 
  • Built-in Pipeline. 

NETworkManager 

  • Built-in packet inspection tool that can be used to troubleshoot and diagnose network problems.  
  • Powerful tools for developers, such as a network traffic simulator. 
  • Allows users to configure, monitor, and control their network traffic quickly. 

Mirror 

  • High-performance, extensible, and lightweight. 
  • Designed to be platform-agnostic. 
  • Supports Unity’s built-in Networking. 

surging 

  • High-performance TCP/IP networking stack. 
  • Pluggable architecture that allows developers to easily customize and extend the library to meet their specific needs. 
  • Provides a range of built-in security features. 

BruteShark 

  • Supports many protocols such as HTTP, FTP, SMTP, DNS, and SSL/TLS.  
  • Integrated packet capture engine to capture network traffic and save it in various formats.  
  • Monitor multiple networks simultaneously and can detect MITM attacks. 

LiteNetLib 

  • Supports both client-server and peer-to-peer architectures. 
  • Provides reliable UDP messaging with the help of its own packet fragmentation and reassembly mechanism.  
  • Supports automatic NAT punchthrough for connecting to peers behind a firewall or router. 

MQTTnet 

  • Supports SSL/TLS encryption and authentication. 
  • Provides native support for Windows, Linux, and macOS platforms. 
  • Includes an integrated logging framework. 

LOIC 

  • Allows the user to select from a variety of attack types. 
  • Includes a graphical user interface. 
  • Includes a feature called “Hive Mind”, which allows users to join a “hive” and send requests in unison with other users. 

SteamKit 

  • Support for various languages, including C#, C++, and JavaScript. 
  • Highly extensible and can be used to create custom network protocols for games.  
  • Various functions are designed to facilitate communication between applications and the Steam network. 

NetCoreServer 

  • Flexible API. 
  • Robust Security.
  • Cross-Platform Compatibility. 


DotNetOpenAuth 

  • Provides strong cryptography algorithms and secure communications protocols. 
  • Written in C#, it is easy to port to other platforms.  
  • Allows developers to extend the library for their specific use cases. 

lidgren-network-gen3 

  • Binary Serialization. 
  • Peer-to-peer Networking. 
  • Reliability. 

BeetleX 

  • Built-in support for Cross-Origin Resource Sharing (CORS). 
  • Deep integration with the .Net Core platform. 
  • Provides an asynchronous, non-blocking programming model with no callbacks and no threads. 

BedrockFramework 

  • Provides a distributed object model that allows for objects to be shared across different instances without creating extra copies.  
  • Provides a unique set of tools for debugging and monitoring network traffic and performance. 
  • Allows for a more robust and reliable system than other libraries written in other languages.   

EvilFOCA 

  • Spoofing allows users to hide their IP address when making network requests.   
  • The port scanning feature allows users to scan for open ports on a network.  
  • The mapping feature allows users to map a network and identify various devices, services, and connections. 

Here are some famous Android Game Development Libraries. Android Game Development Libraries' use cases include Multiplayer Support, Graphics Engine Support, AI Support, Physics Engine Support, and Audio Support. 

 

Android game development libraries refer to a collection of programming tools and pre-written codes that make it easier for developers to create games for the Android operating system. These libraries can provide basic game functions, such as physics, graphics, sound, and input, as well as more advanced features, such as artificial intelligence, networked multiplayer, and 3D rendering.  


Let us look at the libraries in detail below. 

cocos2d-x 

  • Allows developers to build their games for multiple platforms.  
  • Written in C++ and optimized for performance.   
  • Intuitive and easy-to-learn syntax.  

Unity-Design-Pattern 

  • Designed to create high-quality 3D and 2D games and interactive experiences. 
  • Offers a range of graphics options for developers. 
  • Highly extensible and can be customized to a wide range of development needs. 

small3d 

  • Includes a powerful scripting language. 
  • Has a full set of tools for debugging, profiling, and optimization.  
  • Includes a built-in audio engine, allowing developers to create music and sound effects for their games easily. 

engine 

  • Allows developers to export their games to multiple platforms without additional coding. 
  • Developers can create realistic interactions between objects in their games. 
  • Provides a high-performance 3D engine. 

mathfu 

  • Offers an optimized implementation of linear algebra operations. 
  • Built-in vector math library. 
  • Designed to be platform agnostic. 

libgdx 

  • Allows developers to write code one more and deploy it across multiple platforms. 
  • Built-in tools include a particle editor, a sprite editor, and a UI designer.  
  • Comes with an extensive set of audio, networking, and physics APIs. 


scala-game-library 

  • Use Scala programming language, which is designed for scalability and productivity. 
  • Easy for developers to extend the library and integrate it with their own code. 
  • Offers a cross-platform API. 

HutMovie

  • Offers a wide range of tools, such as sprites, animations, and sound effects. 
  • Supports a wide range of integrated game mechanics. 
  • Powerful rendering engine that supports a wide range of devices and screen resolutions. 

playn 

  • Provides a unified game services API. 
  • Provides a game state management system. 
  • Enables developers to build rich, interactive experiences with advanced graphics support. 

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.

Playing games has always been fun, just like coding! There is something about games, which grabs everyone towards it with its fascinating visuals, engaging obstacles to reach victory. You could have played plenty of games like these which were terrific, but how about creating your very own game? How about designing a racing game? Here is one of the most exciting games called Unity 2D Racing. Unity 2D Racing is a single-player game in which a player controls the car on a road path. Some hazards like clouds will pass by the road to make the game bit tough for the player. Besides, a player must also be cautious about not getting into the potholes that appear on the road. Listed below are the best libraries that can be reused. This kit aids the development of the Unity 2D racing game by following the below steps : 1. Pick a Development Environment! 2. Begin with Unity 2D project 3. Set up background sprite 4. Create a script to do the background scroll 5. Add cloud materials 6. Create a 2D controller 7. Sort the layers 8. Create a script for the controller 9. Add Canvas in the UI 10. Create a script for managing the UI 11. Design a Graphic Raycaster in Unity.

Controller for our unity 2d racing game

Scripting is one of the critical parts of Unity 2D racing, in which we do scripting for controlling an object. A controller is a crucial element that handles the input from a player and then holds an object in a game accordingly.

Development Environment

Unity Hub is used for development. Unity is generally a game engine framework that allows you to create two-dimensional(2D) and three-dimensional (3D) games. C# programming language has been used for scripting in Unity.

Graphic Raycaster

The graphic Raycaster will decide on the end of the game. Generally, Raycaster inspects the graphics to determine if any objects got hit by the canvas. If an object hits the hazard, the Graphic Raycaster will block that object and finish the game.

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 in the category of arcade game in that player uses paddles called flippers to launch the ball into the table. The player's goal is to prevent the ball from falling past your flippers for as long as 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.

As we are in the digital era, real-time video games are ruling the young generation. Tank games are one of the addictive games of this generation. The objective of this game is to destroy the enemy's tank with our tank, which will decrease the energy level of the opponent. Similarly, our energy level will be reduced when the opponent attacks us with their tank. The attacking capacity ultimately depends on the energy level. The more is the energy level, the high is the attacking capacity. Following are the steps to be followed for building Tank Fight Game, 1.Graphic design & Sound effects 2.Firing and exploiting the tanks 3.Customize control over keyboard 4.Multi-player 5.3D Tank game

Customize control over keyboard

Key mapper is an open-source library that allows users to use a key or combination of keys to perform a specific action, which can be used for navigating and shooting. The below libraries can help you to create your control.

Graphic design & Sound effects

Listed below libraries help in creating the best graphic design and sound effects for gaming applications using python, C#, JavaScript, which can be used to design tanks, animate the movement of tanks, explosion of tanks, and display energy level bars.

Firing and exploiting the tanks

Random module, an open-source library, generates a random number provided the range, which can be used for firing and exploiting the tanks, decides the playing turn at the start of every game.

3D Tank game

The tank game can be built in 3D by using the below library.

Multi-player

Tank game can be played as multiplayer by using the below libraries. Multiplayers will play on the game field they shoot each other. The more is the energy level. The high is the attacking capacity.

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 consists of 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.

Java is a popular and effective programming language frequently used to create various applications, from web and workplace to desktop and mobile. It is renowned for its object-oriented architecture and simplicity, and it has a sizable and vibrant community that offers a plethora of libraries and frameworks for various uses.  


The idea behind the number-guessing game is for the player to guess a number from a range. Assuming the player enters a valid number that falls within the range, if that number is less than, more significant than, or equal to, the player will know whether it is greater, lower, or equal so he can proceed further. To win, the player must predict the number within the allotted attempts in this game. A player wins the game if they correctly predict the number; else, they lose.  


Here is an example of how you might implement this game: 

Fig 1: Preview of code snippet in IDE.

Fig 2: Preview of the output that you will get on running this code from your IDE. Example usage where I choose to guess 513.

Code

Instructions

Follow the steps carefully to get the output easily:

  1. Copy the code using the "Copy" button above, and paste it in a Java file in your IDE(IntelliJ Preferable).
  2. Run the file to generate the output.


I hope you found this useful.


I found this code snippet by searching for "Guessing Number Game using Java" 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.

  1. The solution is created in IntelliJ IDE and Java jdk-'11.0.17'.
  2. The solution is tested on Java 11.0.17.


Using this solution, we are able to develop an guessing number game using java 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 guessing number game using Java.

Support

  1. For any support on kandi solution kits, please use the chat
  2. For further learning resources, visit the Open Weaver Community learning page.


Here are the best JavaScript game development libraries for your web application. You can use these libraries in JavaScript to build features such as animations, physical movements, collision detection, sound effects, and more.


Open-source JavaScript game development libraries provide various tools and frameworks for game developers of all levels. Whether you're looking to create a simple casual game or a complex 3D game, there is an open-source JavaScript library that can help. These libraries support both 2D and 3D game development and are known for their ease of use and flexibility. Using JavaScript libraries, you can create rich 3D worlds in your games with compelling motion and various moving objects. Also, you can incorporate built-in physics and real-time lighting effects in the games.


We have handpicked top and trending JavaScript libraries for game development based on popularity, licensing, and unique features to help you build video gaming applications:

Impact:

  • Used mainly for 2D game development with HTML5 and JavaScript
  • Provides various tools, including sprite animations, particle effects, and physics. 
  • Includes powerful plugins for adding extra functionality and a 3D environment to your games.

Babylon:

  • Used for its incredibly powerful Web rendering capabilities.
  • Provides tools such as physics-based collisions and particle effects.
  • Supports a wide range of 3D formats.

Phaser:

  • Used for building HTML5 games for desktop and mobile web browsers.
  • Provides features such as sprite animation, particle effects, and physics.
  • Offers WebGL and Canvas rendering.

PixiJS

  • Used for building beautiful web and visual experiences in games.
  • It is a fast and lightweight 2D rendering library for HTML5 games.
  • Includes powerful features such as sprite animations and a fast WebGL renderer.

Engine/PlayCanvas:

  • Used for writing and testing code, setting up different scenes, and exporting the games.
  • It’s a cloud-based game engine for creating 3D HTML5 games.
  • Provides a range of performance optimizations.
  • Also offers VR compatibility.

MelonJS:

  • Used generally for 2D game development.
  • It’s a lightweight yet powerful HTML5 game engine.
  • Provides a simple and flexible set of tools for building 2D games.
  • Offers support for sprite animations, tilemaps, and physics-based collisions. 

Godot:

  • Used for creating 2D and 3D games.
  • Provides a set of tools, including a visual editor and a scripting API.
  • Supports a wide range of platforms. 

p5.js:

  • Used typically in User Interface and Graphics applications.
  • Focuses on creative coding for artists, designers, educators, and beginners.
  • Provides simple and intuitive tools for building interactive animations and games.
  • Offers support for 2D graphics with input handling and sound.

Build custom programs to create character generators for video games and applications by using these open-source character generator libraries.


Character Generator is used to generate characters in video games, smartphone and desktop applications, websites, etc. in various different patterns. You can create 3D and 2D characters for your games and application by using a variety of models, textures and animations. With the help of character generator, you can allow the user to determine aspects of a digital character like attributes, skills, strengths and weaknesses, life events, etc. Also, you can allow them to add animation, text, as well as audio and video effects.


Mentioned below are some of the best and most trending reusable character generator libraries that you can implement in your next project:

Hangman! - a great game for improving your vocabulary and spelling. How to play? Hangman is a guessing game for two or more players. One player thinks of a word, phrase or sentence and the other(s) tries to guess it by suggesting letters before the man hangs completely. Next part is how to make this game via python such that we enjoy playing it? So, don't worry, we have various open source python gaming libraries that actually helps to provide amazing user interface, providing us a better experience.

IDE Download

Pycharm, and other jetbrains tool guide

main.py

The source code of the hangman game is here, just click to explore. Also you can make your own version of hangman, maybe you can add meaning of words as well, to learn different words and improve upon your vocabulary with fun. GitHub

hangman_words.py

To make the game interesting and engaging, we used some of the difficult to guess words in this game, source to that module is GitHub

hangman_arts.py

To keep it simple, yet interesting, we have started with the very basic implementation of Hangman using ascii art symbols, the file code is GitHub

The Modules and code used in Hangman

The randint() method returns an integer number selected element from the specified range. This module helps us to make our game quite unpredictive for users.

Python gaming Module

Python PyGame library is used to create video games. This library includes several modules for playing sound, drawing graphics, handling mouse inputs, etc. So, let's level up our hangman game using this awesome module.

Open sources to make hangman and other games using pycharm

To make your hangman game more interesting, you can use pygame module, here is some of the amazing open sources to make some of the most famous and interesting games using pygame module.

Loading and playing background music in Pygame means that you can load music or sound files into your Pygame program, and then play them while the game is running. This could be used to create a more immersive gaming experience or to add a soundtrack to your game.


Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Pygame is highly portable and runs on nearly every platform and operating system. It is one of the most popular libraries for game development with Python.


Here is an example of loading and playing background music in Pygame


Code


In this solution, we use mixer class of Pygame.

Instructions

Follow the steps carefully to get the output easily.

  1. Install Jupyter Notebook on your computer.
  2. Open terminal and install the required libraries with following commands.
  3. Install Pygame - pip install pygame.
  4. Copy the code using the "Copy" button above, and paste it into your IDE's Python file.
  5. Import pygame.
  6. Add pygame.mixer.init() for initializing mixer.
  7. Add your audio file.
  8. Run the file to get the 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 "Loading and playing background music in Pygame" in kandi. You can try any such use case!

Dependent Libraries


If you do not have Pygame that is required to run this code, you can install it by clicking on the above link and copying the pip Install command from the Pygame page in kandi.


You can search for any dependent library on kandi like pygame

Environment Tested


I tested this solution in the following versions. Be mindful of changes when working with other versions.

  1. The solution is created in Python 3.9.6
  2. The solution is tested on pygame version 2.3.0


Support


  1. For any support on kandi solution kits, please use the chat
  2. For further learning resources, visit the Open Weaver Community learning page.


Here are some famous Java Game Development Libraries. Some of the use cases of Java Game Development Libraries include creating various types of games such as 2D and 3D Games, Educational Games, Mobile Games, or Multiplayer Games.


Java game development libraries are collections of pre-built code that allow developers to quickly and easily create complex games. These libraries provide a wide range of features, such as animations, audio, graphics, physics, artificial intelligence, user inputs, and much more. By using these libraries, developers can create high-quality games in less time than it would take to build them from scratch.


Let us look at the libraries in detail below.

libgdx

  • Cross-platform game development library.
  • Built-in tools such as a particle editor, a sprite editor, and UI designer.
  • Supports 3D game development.

jmonkeyengine

  • Offers a flexible scene graph to provide an intuitive and powerful way to create, arrange, and animate 3D objects.
  • Built-in physics engine that allows developers to easily add physics-driven elements into their games.
  • Has a large and active community of developers.

lwjgl 

  • Platform-independent. 
  • No bugs. 
  • Allows developers to create and run applications written in multiple languages. 

playn 

  • Provides a unified game services API. 
  • Provides a game state management system. 
  • Enables developers to build rich, interactive experiences with advanced graphics support. 

jbox2d 

  • Allows for more realistic and complex motion simulation. 
  • A unique get/set interface for setting and reading the properties of objects. 
  • A broad set of features, including collision detection, etc. 

slick2d 

  • Easy to develop 2D games quickly and efficiently. 
  • Wide features such as a GUI library, audio support, and more. 
  • Provides an OpenGL backend for hardware accelerated graphics and Cross-platform compatibility. 

AndEngine 

  • Offers a wide variety of graphical effects and shader support. 
  • Has built-in support for multiplayer gaming. 
  • Has built-in support for virtual reality.  

corona_sdk 

  • Features the Corona Simulator, which allows developers to quickly test and debug their games on multiple platforms without having to deploy them. 
  • Based on the Lua scripting language. 
  • Offers an extensive library of plugins. 

java-sdk 

  • Support for the JavaFX library for creating modern, dynamic user interfaces. 
  • Comprehensive documentation with tutorials and sample code. 
  • High-level APIs for advanced game AI and physics. 

Stellar  

  • Advanced networking capabilities. 
  • Comprehensive audio support. 
  • Support for 2D and 3D graphics. 

afroman-client 

  • Supports both DirectX and OpenGL graphics APIs. 
  • Fully compatible with other popular game development libraries. 
  • Provides support for multi-threaded programming. 

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, and various 3d solid libraries are available to assist developers in meeting their objectives. 


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. 

Here are some of the C++ Game Development Libraries. Some use cases of C++ Game Development Libraries include the Creation of 2D and 3D Games, Game Engine Development, Optimization of Existing Games, and Game Prototyping.  


C++ game development libraries are a set of libraries or frameworks, usually written in the C++ programming language, that provide tools and functions to help developers create video games and other interactive applications. They typically provide functions such as graphics and audio libraries, physics and collision detection libraries, AI libraries, and game-specific libraries. 


Let us look at the libraries in detail below. 

SFML (Simple and Fast Multimedia Library) 

  • Provides an easy-to-use interface for creating multithreaded games with high-performance graphics.  
  • Written in C++ and has bindings for various languages, such as C#, Java, and Python. 
  • Cross-platform offers features such as audio, networking, and input support.  

SDL (Simple DirectMedia Layer) 

  • Low-level access to system hardware such as audio, mouse, joystick, and graphics. 
  • High portability since the code can be easily adapted to different platforms.   
  • Provides a comprehensive set of APIs that makes game development simpler and easier. 

Ogre 3D (Object-Oriented Graphics Rendering Engine) 

  • Has a powerful rendering engine that is optimized for both DirectX and OpenGL.  
  • Has a robust and versatile material system. 
  • Has an intuitive and user-friendly UI system that makes it easy to prototype and develop games. 

UnrealEnginePython 

  • Allows developers to easily access and modify the powerful features of UE4. 
  • Allows developers to create custom tools and plugins for the UE4 editor. 
  • Has advanced graphics capabilities, allowing developers to create stunning visuals for their games.  

Cocos2D-x 

  • Allows developers to build their games for multiple platforms. 
  • Written in C++ and is optimized for performance.  
  • Intuitive and easy-to-learn syntax. 

Qt 

  • Supports GUI development with its powerful set of widgets. 
  • Based the QML scripting language and enables developers to create user interfaces quickly. 
  • Is a library for creating 3D applications and games. 

lumberyard 

  • Optimized for both performance and scalability. 
  • Makes the developers use the same codebase to create PC and console games.   
  • Highly extensible and can be easily incorporated into existing game engines. 

NoahGameFrame 

  • Full-featured, open-source game development framework. 
  • Intuitive and comprehensive engine structure.  
  • Supports a wide range of input devices. 

JoltPhysics 

  • Support for multiple physics engines, including Havok, PhysX, and Bullet. 
  • Has a built-in collision detection system. 
  • Has a built-in network synchronization system for multiplayer game development. 

Everyone loves to play games, especially online games. Sudoku is one of the great and prominent online games that helps us to develop problem-solving skills. Sudoku is one of the logic-based, combinatorial number-placement puzzles. The benefits of playing sudoku are that it improves concentration, promotes a healthy mind. The ultimate goal of the sudoku game is to fill a 9×9 grid with numbers. Python is preferable for building sudoku games; the reason behind that is python is free and open-source, with vast library support. Before technology evolution, we could play sudoku in magazines, article books. Modern technology has brought the opportunity to digitally create and play sudoku, so let's get started with the bellow libraries without delay. This kit aids the development of the Sudoku game using python by following the below steps. 1. Select a development environment of your choice 2. knowledge of Graphical user interface 3. Idea of the key binding controller 4. Fill the grid with default numbers. 5. Assign a specific key for each operation and listen to it. 6. Implement sudoku solver 7. Conjoin the backtracking algorithm into it. 8. Apply a set of colors to visualize auto-solving.

Graphical user interface

The graphical user interface is a user interface that permits users to interact with electronic devices through graphical icons and an audio indicator. Tkinter is the standard GUI library for Python. Python, when combined with Tkinter, provides a fast and easy way to create GUI applications.

Puzzle generator

Sudoku Generator algorithm uses the standard type of Sudoku Solver Algorithm, which is a backtracking algorithm. A backtracking algorithm is used to investigate all possible solutions of a given grid.

Development Environment

Pycharm and Jupyter NoteBook are used for development. Pycharm offers code analysis, an integrated unit tester, a graphical debugger. Jupyter Notebook is a tremendous web application that allows us to share and create documents that consist of live code and collaboration.

Puzzle Solver

A Sudoku Solver is implemented using Python and PyGame Library by visualizing the Sudoku Board using the Backtracking Algorithm.

Creating a window using pygame means using the pygame library to create a graphical window for a game or other graphical application. This window can display graphics and receive user input from the keyboard and mouse. 


  • Pygame is a free and open-source library of Python modules designed for writing video games. It provides functions such as sound, graphics, and input, allowing programmers to create fully-featured games and multimedia programs using Python. Pygame is portable and runs on every platform and operating system. 


You can create a window in pygame by following some basic steps: 

  • Import the Pygame module. Initialize the game engine 
  • Set the window size. Create the window and Set the window title 
  • Load images, sounds, and other assets and also Set up the game loop 
  • Handle events and Update game logic 
  • Draw the game and then Refresh the screen 


Here is an example of Creating a new window with pygame. 



Fig 1: Preview of the output that you will get on running this code from your IDE

Code


In this solution, we create a new window with pygame

Instructions

Follow the steps carefully to get the output easily.

  1. Install Jupyter Notebook on your computer.
  2. Open terminal and install the required libraries with following commands.
  3. Install pygame - pip install pygame.
  4. Copy the code using the "Copy" button above, and paste it into your IDE's Python file.
  5. Run the file to create a new window using pygame.



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 "Creating a window with pygame" in kandi. You can try any such use case!

Dependent Libraries

If you do not have Pygame that is required to run this code, you can install it by clicking on the above link and copying the pip Install command from the Pygame page in kandi.


You can search for any dependent library on kandi like pygame

Environment Tested


I tested this solution in the following versions. Be mindful of changes when working with other versions.

  1. The solution is created in Python 3.9.6
  2. The solution is tested on pygame version 2.3.0


Using this solution, we are able to create a new window with pygame. It is also used for creating graphical applications.

Game programming is very rewarding nowadays and it can also be used in advertising and as a teaching tool too. Game development includes mathematics, logic, physics, AI, and much more and it can be amazingly fun. In python, game programming is done in pygame and it is one of the best modules for doing so.

Code

In this solution, we use the render function of the pygame library

  1. Copy the code using the "Copy" button above, and paste it in a Python file in your IDE.
  2. Modify the name, location of the image to be resized in the code.
  3. Run the file to resize the image.


I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.

Dependent Libraries


Environment Tested 

I tested this solution in the following versions. Be mindful of changes when working with other versions. 

  1. The solution is created in Python3.11. 
  2. The solution is tested on pygame 2.3.0 version. 

Support

  1. For any support on kandi solution kits, please use the chat
  2. For further learning resources, visit the Open Weaver Community learning page.

Trending Discussions on Gaming

Refactoring Laravel isset params to eloquent when condition

Even though they are logically the same, why am I getting different outputs?

Add commas every digits in numbers of kable()

Add commas between numbers in label and legend of ggplot2 plot

Misspecifying argument error in shiny app

Boxes are not displayed in ggplot2 boxplot

Apply mean and median in every row of a dataframe and add them as separated columns to the dataframe

Why is my XPath returning only text without tags?

Create columns from row values and fill - pandas

Implementing 3 modals triggered by 3 buttons

QUESTION

Refactoring Laravel isset params to eloquent when condition

Asked 2022-Apr-03 at 05:12

I am trying to clean up my code, so i have decided to start using the when option instead of isset in my querys ... But it doesnt seem to be working and I cant see where I am going wrong.

My original code looks like so;

1$params['game'] = 'fallout';
2
3$gameQuery = Gaming::query();
4
5$gameSelect = isset($params['game']) ? $params['game'] : null;
6if ($gameSelect) {
7    $gameQuery = $gameQuery->where('game' $gameSelect);
8}
9

This has been working in the codebase now for a number of years.

I tried refactoring to the following, using the when keyword

1$params['game'] = 'fallout';
2
3$gameQuery = Gaming::query();
4
5$gameSelect = isset($params['game']) ? $params['game'] : null;
6if ($gameSelect) {
7    $gameQuery = $gameQuery->where('game' $gameSelect);
8}
9$params['game'] = 'fallout';
10
11$gameQuery = Gaming::query();
12
13$gameQuery->when($params['game'], function ($query) use ($params) {
14    $query->where('game', $params['game']);
15});
16

But for some reason it just skips over there where statement.

Any help would be greatly appreciated.

ANSWER

Answered 2022-Apr-03 at 05:12
1$params['game'] = 'fallout';
2
3$gameQuery = Gaming::query();
4
5$gameSelect = isset($params['game']) ? $params['game'] : null;
6if ($gameSelect) {
7    $gameQuery = $gameQuery->where('game' $gameSelect);
8}
9$params['game'] = 'fallout';
10
11$gameQuery = Gaming::query();
12
13$gameQuery->when($params['game'], function ($query) use ($params) {
14    $query->where('game', $params['game']);
15});
16$gameQuery->when(isset($params['game']) 
17, function ($query) use ($params) {
18     $query->where('game', $params['game']);
19 });
20

Source https://stackoverflow.com/questions/71722490

QUESTION

Even though they are logically the same, why am I getting different outputs?

Asked 2022-Apr-02 at 10:08

It's my first time asking a question here, so I apologize if the question has been repeated earlier.

This is my official solution for freeCodeCamp JS problem:

1const contacts = [
2  {
3    firstName: "Akira",
4    lastName: "Laine",
5    number: "0543236543",
6    likes: ["Pizza", "Coding", "Brownie Points"],
7  },
8  {
9    firstName: "Harry",
10    lastName: "Potter",
11    number: "0994372684",
12    likes: ["Hogwarts", "Magic", "Hagrid"],
13  },
14  {
15    firstName: "Sherlock",
16    lastName: "Holmes",
17    number: "0487345643",
18    likes: ["Intriguing Cases", "Violin"],
19  },
20  {
21    firstName: "Kristian",
22    lastName: "Vos",
23    number: "unknown",
24    likes: ["JavaScript", "Gaming", "Foxes"],
25  },
26];
27
28
29function lookUpProfile(name, prop) {
30
31  for(let i = 0; i<contacts.length;i++){
32    if(contacts[i].firstName == name && contacts[i].hasOwnProperty(prop)){
33        return contacts[i][prop];
34      }
35      else {
36        return "No such property"
37      } 
38    }
39  return "No such contact";
40}
41
42console.log(lookUpProfile("Kristian", "lastName")); //Output: No such property
43

And this is the official solution with changes in the 'nested-if' loop:

1const contacts = [
2  {
3    firstName: "Akira",
4    lastName: "Laine",
5    number: "0543236543",
6    likes: ["Pizza", "Coding", "Brownie Points"],
7  },
8  {
9    firstName: "Harry",
10    lastName: "Potter",
11    number: "0994372684",
12    likes: ["Hogwarts", "Magic", "Hagrid"],
13  },
14  {
15    firstName: "Sherlock",
16    lastName: "Holmes",
17    number: "0487345643",
18    likes: ["Intriguing Cases", "Violin"],
19  },
20  {
21    firstName: "Kristian",
22    lastName: "Vos",
23    number: "unknown",
24    likes: ["JavaScript", "Gaming", "Foxes"],
25  },
26];
27
28
29function lookUpProfile(name, prop) {
30
31  for(let i = 0; i<contacts.length;i++){
32    if(contacts[i].firstName == name && contacts[i].hasOwnProperty(prop)){
33        return contacts[i][prop];
34      }
35      else {
36        return "No such property"
37      } 
38    }
39  return "No such contact";
40}
41
42console.log(lookUpProfile("Kristian", "lastName")); //Output: No such property
43function lookUpProfile(name, prop) {
44
45  for(let i = 0; i<contacts.length;i++){
46    if(contacts[i].firstName == name){
47      if(contacts[i].hasOwnProperty(prop)){
48        return contacts[i][prop];
49      }
50      else {
51        return "No such property"
52      } 
53    }
54  }
55  return "No such contact";
56}
57
58console.log(lookUpProfile("Kristian", "lastName")); //Output: Vos
59

Why am I getting different solutions even if the logic behind nested-if in the official solution is similar to mine?

ANSWER

Answered 2022-Apr-02 at 10:08

They aren't logically the same.

Theirs is this:

1const contacts = [
2  {
3    firstName: "Akira",
4    lastName: "Laine",
5    number: "0543236543",
6    likes: ["Pizza", "Coding", "Brownie Points"],
7  },
8  {
9    firstName: "Harry",
10    lastName: "Potter",
11    number: "0994372684",
12    likes: ["Hogwarts", "Magic", "Hagrid"],
13  },
14  {
15    firstName: "Sherlock",
16    lastName: "Holmes",
17    number: "0487345643",
18    likes: ["Intriguing Cases", "Violin"],
19  },
20  {
21    firstName: "Kristian",
22    lastName: "Vos",
23    number: "unknown",
24    likes: ["JavaScript", "Gaming", "Foxes"],
25  },
26];
27
28
29function lookUpProfile(name, prop) {
30
31  for(let i = 0; i<contacts.length;i++){
32    if(contacts[i].firstName == name && contacts[i].hasOwnProperty(prop)){
33        return contacts[i][prop];
34      }
35      else {
36        return "No such property"
37      } 
38    }
39  return "No such contact";
40}
41
42console.log(lookUpProfile("Kristian", "lastName")); //Output: No such property
43function lookUpProfile(name, prop) {
44
45  for(let i = 0; i<contacts.length;i++){
46    if(contacts[i].firstName == name){
47      if(contacts[i].hasOwnProperty(prop)){
48        return contacts[i][prop];
49      }
50      else {
51        return "No such property"
52      } 
53    }
54  }
55  return "No such contact";
56}
57
58console.log(lookUpProfile("Kristian", "lastName")); //Output: Vos
59for (/*...*/) {
60    if (a) {
61        if (b) {
62            return X;
63        } else {
64            return Y;
65        }
66    }
67}
68

Notice that if a is not true, neither return happens, and the loop continues with the next iteration.

But yours is:

1const contacts = [
2  {
3    firstName: "Akira",
4    lastName: "Laine",
5    number: "0543236543",
6    likes: ["Pizza", "Coding", "Brownie Points"],
7  },
8  {
9    firstName: "Harry",
10    lastName: "Potter",
11    number: "0994372684",
12    likes: ["Hogwarts", "Magic", "Hagrid"],
13  },
14  {
15    firstName: "Sherlock",
16    lastName: "Holmes",
17    number: "0487345643",
18    likes: ["Intriguing Cases", "Violin"],
19  },
20  {
21    firstName: "Kristian",
22    lastName: "Vos",
23    number: "unknown",
24    likes: ["JavaScript", "Gaming", "Foxes"],
25  },
26];
27
28
29function lookUpProfile(name, prop) {
30
31  for(let i = 0; i<contacts.length;i++){
32    if(contacts[i].firstName == name && contacts[i].hasOwnProperty(prop)){
33        return contacts[i][prop];
34      }
35      else {
36        return "No such property"
37      } 
38    }
39  return "No such contact";
40}
41
42console.log(lookUpProfile("Kristian", "lastName")); //Output: No such property
43function lookUpProfile(name, prop) {
44
45  for(let i = 0; i<contacts.length;i++){
46    if(contacts[i].firstName == name){
47      if(contacts[i].hasOwnProperty(prop)){
48        return contacts[i][prop];
49      }
50      else {
51        return "No such property"
52      } 
53    }
54  }
55  return "No such contact";
56}
57
58console.log(lookUpProfile("Kristian", "lastName")); //Output: Vos
59for (/*...*/) {
60    if (a) {
61        if (b) {
62            return X;
63        } else {
64            return Y;
65        }
66    }
67}
68for (/*...*/) {
69    if (a && b) {
70        return X;
71    } else {
72        return Y;
73    }
74}
75

It returns even when a is false, never moving on to the next loop iteration.

If you wanted to combine the outer test with the inner ones, it would be:

1const contacts = [
2  {
3    firstName: "Akira",
4    lastName: "Laine",
5    number: "0543236543",
6    likes: ["Pizza", "Coding", "Brownie Points"],
7  },
8  {
9    firstName: "Harry",
10    lastName: "Potter",
11    number: "0994372684",
12    likes: ["Hogwarts", "Magic", "Hagrid"],
13  },
14  {
15    firstName: "Sherlock",
16    lastName: "Holmes",
17    number: "0487345643",
18    likes: ["Intriguing Cases", "Violin"],
19  },
20  {
21    firstName: "Kristian",
22    lastName: "Vos",
23    number: "unknown",
24    likes: ["JavaScript", "Gaming", "Foxes"],
25  },
26];
27
28
29function lookUpProfile(name, prop) {
30
31  for(let i = 0; i<contacts.length;i++){
32    if(contacts[i].firstName == name && contacts[i].hasOwnProperty(prop)){
33        return contacts[i][prop];
34      }
35      else {
36        return "No such property"
37      } 
38    }
39  return "No such contact";
40}
41
42console.log(lookUpProfile("Kristian", "lastName")); //Output: No such property
43function lookUpProfile(name, prop) {
44
45  for(let i = 0; i<contacts.length;i++){
46    if(contacts[i].firstName == name){
47      if(contacts[i].hasOwnProperty(prop)){
48        return contacts[i][prop];
49      }
50      else {
51        return "No such property"
52      } 
53    }
54  }
55  return "No such contact";
56}
57
58console.log(lookUpProfile("Kristian", "lastName")); //Output: Vos
59for (/*...*/) {
60    if (a) {
61        if (b) {
62            return X;
63        } else {
64            return Y;
65        }
66    }
67}
68for (/*...*/) {
69    if (a && b) {
70        return X;
71    } else {
72        return Y;
73    }
74}
75for (/*...*/) {
76    if (a && b) {
77        return X;
78    } else if (a) { // <===
79        return Y;
80    }
81}
82

But that's not as clear as the original, and ends up testing a twice unnecessarily.

Source https://stackoverflow.com/questions/71716579

QUESTION

Add commas every digits in numbers of kable()

Asked 2022-Mar-21 at 16:36

I have the dataframe below and I create a kable out of this. How could I add commas between numbers every 3 digits?

1Descs<-structure(list(Mean = c(NaN, 943330388, NaN, NaN, NaN, 543234645, 
245831420, NaN, 27301292, 160818771), Median = c(NaN, 943330388, 
3NaN, NaN, NaN, 543234645, 45831420, NaN, 27301292, 160818771), 
4    SD = c(NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, 
5    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), MAD = c(NA, 
6    0, NA, NA, NA, 0, 0, NA, 0, 0), MIN = c(NA, 943330388, NA, 
7    NA, NA, 543234645, 45831420, NA, 27301292, 160818771), MAX = c(NA, 
8    943330388, NA, NA, NA, 543234645, 45831420, NA, 27301292, 
9    160818771), VAR = c(NA_real_, NA_real_, NA_real_, NA_real_, 
10    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_
11    ), RANGE = structure(c(NA, 943330388, NA, NA, NA, 543234645, 
12    45831420, NA, 27301292, 160818771, NA, 943330388, NA, NA, 
13    NA, 543234645, 45831420, NA, 27301292, 160818771), .Dim = c(10L, 
14    2L)), QUANTILES = structure(c(NA, 943330388, NA, NA, NA, 
15    543234645, 45831420, NA, 27301292, 160818771, NA, 943330388, 
16    NA, NA, NA, 543234645, 45831420, NA, 27301292, 160818771), .Dim = c(10L, 
17    2L), .Dimnames = list(NULL, c("25%", "75%")))), row.names = c("Comedy", 
18"Education", "Entertainment", "Film & Animation", "Gaming", "Howto & Style", 
19"Music", "People & Blogs", "Science & Technology", "Sports"), class = "data.frame")
20
21library(kableExtra)
22
23kable(Descs) %>%
24    kable_styling(
25      font_size = 15,
26      bootstrap_options = c("striped", "hover", "condensed")
27    ) 
28

ANSWER

Answered 2022-Mar-21 at 16:36

You could use the kable format argument, this avoids mucking around with the data prior to putting into the table.

And if you want to clear up the NAs and NaNs you could add in this line of code: options(knitr.kable.NA = '')

1Descs<-structure(list(Mean = c(NaN, 943330388, NaN, NaN, NaN, 543234645, 
245831420, NaN, 27301292, 160818771), Median = c(NaN, 943330388, 
3NaN, NaN, NaN, 543234645, 45831420, NaN, 27301292, 160818771), 
4    SD = c(NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, 
5    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), MAD = c(NA, 
6    0, NA, NA, NA, 0, 0, NA, 0, 0), MIN = c(NA, 943330388, NA, 
7    NA, NA, 543234645, 45831420, NA, 27301292, 160818771), MAX = c(NA, 
8    943330388, NA, NA, NA, 543234645, 45831420, NA, 27301292, 
9    160818771), VAR = c(NA_real_, NA_real_, NA_real_, NA_real_, 
10    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_
11    ), RANGE = structure(c(NA, 943330388, NA, NA, NA, 543234645, 
12    45831420, NA, 27301292, 160818771, NA, 943330388, NA, NA, 
13    NA, 543234645, 45831420, NA, 27301292, 160818771), .Dim = c(10L, 
14    2L)), QUANTILES = structure(c(NA, 943330388, NA, NA, NA, 
15    543234645, 45831420, NA, 27301292, 160818771, NA, 943330388, 
16    NA, NA, NA, 543234645, 45831420, NA, 27301292, 160818771), .Dim = c(10L, 
17    2L), .Dimnames = list(NULL, c("25%", "75%")))), row.names = c("Comedy", 
18"Education", "Entertainment", "Film & Animation", "Gaming", "Howto & Style", 
19"Music", "People & Blogs", "Science & Technology", "Sports"), class = "data.frame")
20
21library(kableExtra)
22
23kable(Descs) %>%
24    kable_styling(
25      font_size = 15,
26      bootstrap_options = c("striped", "hover", "condensed")
27    ) 
28library(kableExtra)
29
30kable(Descs,
31      format.args = list(big.mark = ",")) %>%
32  kable_styling(
33    font_size = 15,
34    bootstrap_options = c("striped", "hover", "condensed")
35  ) 
36
37

enter image description here

Source https://stackoverflow.com/questions/71560787

QUESTION

Add commas between numbers in label and legend of ggplot2 plot

Asked 2022-Mar-21 at 16:07

I have the dataframe below and I create a boxplot. I would like to format the numbers in y-axis and legend in order to have commas or .

1df_long<-structure(list(WORDS = c("Comedy", "Education", "Entertainment", 
2"Film & Animation", "Gaming", "Howto & Style", "Music", "People & Blogs", 
3"Science & Technology", "Sports"), TOTALS = c(0, 943330388, 0, 
40, 0, 543234645, 45831420, 0, 27301292, 160818771)), row.names = c(NA, 
5-10L), class = c("tbl_df", "tbl", "data.frame"))
6
7p <- ggplot(df_long, aes(x = WORDS, y = TOTALS, fill = WORDS)) + 
8  geom_boxplot()
9
10p  +  
11  theme_minimal()+ 
12  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, 
13                                   hjust=1))+ 
14  xlab("Industries") +
15  ylab("Value")+ guides(fill=guide_legend(title="Industries"))
16+
17  scale_y_continuous(formatter = comma)+scale_fill_continuous(formatter = comma)
18

ANSWER

Answered 2022-Mar-21 at 16:07

One way is using scales::comma.

Note I've removed scale_fill_continuous as this is incorrect: the fill aesthetic relates to a discrete variable: WORDS

1df_long<-structure(list(WORDS = c("Comedy", "Education", "Entertainment", 
2"Film & Animation", "Gaming", "Howto & Style", "Music", "People & Blogs", 
3"Science & Technology", "Sports"), TOTALS = c(0, 943330388, 0, 
40, 0, 543234645, 45831420, 0, 27301292, 160818771)), row.names = c(NA, 
5-10L), class = c("tbl_df", "tbl", "data.frame"))
6
7p <- ggplot(df_long, aes(x = WORDS, y = TOTALS, fill = WORDS)) + 
8  geom_boxplot()
9
10p  +  
11  theme_minimal()+ 
12  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, 
13                                   hjust=1))+ 
14  xlab("Industries") +
15  ylab("Value")+ guides(fill=guide_legend(title="Industries"))
16+
17  scale_y_continuous(formatter = comma)+scale_fill_continuous(formatter = comma)
18library(ggplot2)
19library(scales)
20
21ggplot(df_long, aes(x = WORDS, y = TOTALS, fill = WORDS)) + 
22  geom_boxplot()  +  
23  theme_minimal()+ 
24  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, 
25                                   hjust=1))+ 
26  xlab("Industries") +
27  ylab("Value")+ 
28  guides(fill = guide_legend(title="Industries")) +
29  scale_y_continuous(labels = comma)
30

Created on 2022-03-21 by the reprex package (v2.0.1)

Source https://stackoverflow.com/questions/71560148

QUESTION

Misspecifying argument error in shiny app

Asked 2022-Mar-18 at 16:53

I have the shiny app below in which I try to present a descriptives table but my app breaks down with error:

1Did you misspecify an argument?
2  54: <Anonymous>
3Error : `...` is not empty.
4
5
6
7
8
9library(tidyverse)
10library(shiny)
11library(matrixStats)
12library(tibble)
13library(knitr)
14library(kableExtra)
15    Abstract_50<-structure(list(ID = c("UC_Ba9vCsY19LF7-gc46lWQQ", "UC_k6e2PPDUnxEdMJC9Q044g"
16), AbstractName = c("ABC 1", "ABC 2"), Country = c("US", "US"
17), Category = c("Gaming", "Comedy"), MadeK = c("No", "No"), SChan = c("Yes", 
18"Yes"), Language = c("en", "EN"), URL1 = c("NA", "NA"), URL2 = c("NA", 
19"NA"), `2018-03` = c(NA_real_, NA_real_), `2018-04` = c(NA_real_, 
20NA_real_), `2018-05` = c(NA_real_, NA_real_), `2018-06` = c(NA_real_, 
21NA_real_), `2018-07` = c(NA_real_, NA_real_), `2018-08` = c(NA_real_, 
22NA_real_), `2018-09` = c(NA_real_, NA_real_), `2018-10` = c(NA_real_, 
23NA_real_), `2018-11` = c(NA_real_, NA_real_), `2018-12` = c(NA_real_, 
24NA_real_), `2019-01` = c(NA_real_, NA_real_), `2019-02` = c(NA_real_, 
25NA_real_), `2019-03` = c(NA_real_, NA_real_), `2019-04` = c(NA_real_, 
26NA_real_), `2019-05` = c(NA_real_, NA_real_), `2019-06` = c(NA_real_, 
27NA_real_), `2019-07` = c(NA_real_, NA_real_), `2019-08` = c(NA_real_, 
28NA_real_), `2019-09` = c(NA_real_, NA_real_), `2019-10` = c(NA_real_, 
29NA_real_), `2019-11` = c(NA_real_, NA_real_), `2019-12` = c(NA_real_, 
30NA_real_), `2020-01` = c(NA_real_, NA_real_), `2020-02` = c(NA_real_, 
31NA_real_), `2020-03` = c(NA_real_, NA_real_), `2020-04` = c(NA_real_, 
32NA_real_), `2020-05` = c(NA_real_, NA_real_), `2020-06` = c(NA, 
3387710), `2020-07` = c(NA, 162416), `2020-08` = c(NA, 187892), 
34    `2020-09` = c(NA, 374661), `2020-10` = c(NA, 449634), `2020-12` = c(NA, 
35    1328523), `2021-01` = c(NA, 1525466), `2021-02` = c(NA, 1836399
36    ), `2021-03` = c(NA, 2752575), `2021-04` = c(86334, 1520546
37    ), `2021-05` = c(165124612, 3205193), `2021-06` = c(392264433,1534225), `2021-07` = c(282087438, 704348), `2021-08` = c(142305290, 
38    49416984), `2021-09` = c(103659781, 49469088), `2021-10` = c(124671803, 
39    20090134), `2021-11` = c(195965776, 363679038), `2021-12` = c(216612017, 
40    774113580), `2022-01` = c(376009215, 796724246), `2022-02` = c(193946191, 
41    599590598)), row.names = c(NA, -2L), class = c("tbl_df", 
42"tbl", "data.frame"))
43    
44shinyApp(
45  
46  ui = fluidPage(
47    selectInput("month", "Month:",
48                choices = colnames(Abstract_50)[10:56],multiple=T,selected=colnames(Abstract_50)[10:14]),
49    htmlOutput("tableset")
50  ),
51  
52  server = function(input, output) {
53    Ind<-Abstract_50[,c(4,10:56)] %>% 
54      group_by(Category) %>%
55      summarise(across(everything(), sum))
56    
57    Ind2<-reactive({
58      Ind <- Ind[,c("Category",input$month), drop = FALSE]
59      
60    })
61    Ind3<-reactive(Ind2() %>% remove_rownames %>% column_to_rownames(var="Category"))
62
63    Descs<-reactive(
64      Descs2<-tibble(Mean = rowMeans(Ind3(), na.rm = TRUE), 
65                     Median = rowMedians(as.matrix(Ind3()), na.rm = TRUE),
66                     SD=rowSds(as.matrix(Ind3()),na.rm = T),
67                     MAD=rowMads(as.matrix(Ind3(),na.rm=T)),
68                     MIN=rowMins(as.matrix(Ind3(),na.rm=T)),
69                     MAX=rowMaxs(as.matrix(Ind3(),na.rm=T)),
70                     VAR=rowVars(as.matrix(Ind3(),na.rm=T)),
71                     RANGE=rowRanges(as.matrix(Ind3(),na.rm=T)),
72                     QUANTILES=rowQuantiles(as.matrix(Ind3()), na.rm = TRUE)[, c(2, 4)]),
73      
74      Descs2<-as.data.frame(Descs2),
75      rownames(Descs2)<-rownames(Ind3()),
76      Descs2
77    )
78    
79    
80    
81    
82    output$tableset <- renderText({
83      kable(Descs()) %>%
84        kable_styling(
85          font_size = 15,
86          bootstrap_options = c("striped", "hover", "condensed")
87        ) 
88    })
89  },
90  
91  options = list(height = 500)
92  
93)
94

ANSWER

Answered 2022-Mar-18 at 16:53

In the code, there are places where the OP specified , at the end of a line e.g.

1Did you misspecify an argument?
2  54: <Anonymous>
3Error : `...` is not empty.
4
5
6
7
8
9library(tidyverse)
10library(shiny)
11library(matrixStats)
12library(tibble)
13library(knitr)
14library(kableExtra)
15    Abstract_50<-structure(list(ID = c("UC_Ba9vCsY19LF7-gc46lWQQ", "UC_k6e2PPDUnxEdMJC9Q044g"
16), AbstractName = c("ABC 1", "ABC 2"), Country = c("US", "US"
17), Category = c("Gaming", "Comedy"), MadeK = c("No", "No"), SChan = c("Yes", 
18"Yes"), Language = c("en", "EN"), URL1 = c("NA", "NA"), URL2 = c("NA", 
19"NA"), `2018-03` = c(NA_real_, NA_real_), `2018-04` = c(NA_real_, 
20NA_real_), `2018-05` = c(NA_real_, NA_real_), `2018-06` = c(NA_real_, 
21NA_real_), `2018-07` = c(NA_real_, NA_real_), `2018-08` = c(NA_real_, 
22NA_real_), `2018-09` = c(NA_real_, NA_real_), `2018-10` = c(NA_real_, 
23NA_real_), `2018-11` = c(NA_real_, NA_real_), `2018-12` = c(NA_real_, 
24NA_real_), `2019-01` = c(NA_real_, NA_real_), `2019-02` = c(NA_real_, 
25NA_real_), `2019-03` = c(NA_real_, NA_real_), `2019-04` = c(NA_real_, 
26NA_real_), `2019-05` = c(NA_real_, NA_real_), `2019-06` = c(NA_real_, 
27NA_real_), `2019-07` = c(NA_real_, NA_real_), `2019-08` = c(NA_real_, 
28NA_real_), `2019-09` = c(NA_real_, NA_real_), `2019-10` = c(NA_real_, 
29NA_real_), `2019-11` = c(NA_real_, NA_real_), `2019-12` = c(NA_real_, 
30NA_real_), `2020-01` = c(NA_real_, NA_real_), `2020-02` = c(NA_real_, 
31NA_real_), `2020-03` = c(NA_real_, NA_real_), `2020-04` = c(NA_real_, 
32NA_real_), `2020-05` = c(NA_real_, NA_real_), `2020-06` = c(NA, 
3387710), `2020-07` = c(NA, 162416), `2020-08` = c(NA, 187892), 
34    `2020-09` = c(NA, 374661), `2020-10` = c(NA, 449634), `2020-12` = c(NA, 
35    1328523), `2021-01` = c(NA, 1525466), `2021-02` = c(NA, 1836399
36    ), `2021-03` = c(NA, 2752575), `2021-04` = c(86334, 1520546
37    ), `2021-05` = c(165124612, 3205193), `2021-06` = c(392264433,1534225), `2021-07` = c(282087438, 704348), `2021-08` = c(142305290, 
38    49416984), `2021-09` = c(103659781, 49469088), `2021-10` = c(124671803, 
39    20090134), `2021-11` = c(195965776, 363679038), `2021-12` = c(216612017, 
40    774113580), `2022-01` = c(376009215, 796724246), `2022-02` = c(193946191, 
41    599590598)), row.names = c(NA, -2L), class = c("tbl_df", 
42"tbl", "data.frame"))
43    
44shinyApp(
45  
46  ui = fluidPage(
47    selectInput("month", "Month:",
48                choices = colnames(Abstract_50)[10:56],multiple=T,selected=colnames(Abstract_50)[10:14]),
49    htmlOutput("tableset")
50  ),
51  
52  server = function(input, output) {
53    Ind<-Abstract_50[,c(4,10:56)] %>% 
54      group_by(Category) %>%
55      summarise(across(everything(), sum))
56    
57    Ind2<-reactive({
58      Ind <- Ind[,c("Category",input$month), drop = FALSE]
59      
60    })
61    Ind3<-reactive(Ind2() %>% remove_rownames %>% column_to_rownames(var="Category"))
62
63    Descs<-reactive(
64      Descs2<-tibble(Mean = rowMeans(Ind3(), na.rm = TRUE), 
65                     Median = rowMedians(as.matrix(Ind3()), na.rm = TRUE),
66                     SD=rowSds(as.matrix(Ind3()),na.rm = T),
67                     MAD=rowMads(as.matrix(Ind3(),na.rm=T)),
68                     MIN=rowMins(as.matrix(Ind3(),na.rm=T)),
69                     MAX=rowMaxs(as.matrix(Ind3(),na.rm=T)),
70                     VAR=rowVars(as.matrix(Ind3(),na.rm=T)),
71                     RANGE=rowRanges(as.matrix(Ind3(),na.rm=T)),
72                     QUANTILES=rowQuantiles(as.matrix(Ind3()), na.rm = TRUE)[, c(2, 4)]),
73      
74      Descs2<-as.data.frame(Descs2),
75      rownames(Descs2)<-rownames(Ind3()),
76      Descs2
77    )
78    
79    
80    
81    
82    output$tableset <- renderText({
83      kable(Descs()) %>%
84        kable_styling(
85          font_size = 15,
86          bootstrap_options = c("striped", "hover", "condensed")
87        ) 
88    })
89  },
90  
91  options = list(height = 500)
92  
93)
94 Descs2<-as.data.frame(Descs2),
95 rownames(Descs2)<-rownames(Ind3()),
96

-full code

1Did you misspecify an argument?
2  54: <Anonymous>
3Error : `...` is not empty.
4
5
6
7
8
9library(tidyverse)
10library(shiny)
11library(matrixStats)
12library(tibble)
13library(knitr)
14library(kableExtra)
15    Abstract_50<-structure(list(ID = c("UC_Ba9vCsY19LF7-gc46lWQQ", "UC_k6e2PPDUnxEdMJC9Q044g"
16), AbstractName = c("ABC 1", "ABC 2"), Country = c("US", "US"
17), Category = c("Gaming", "Comedy"), MadeK = c("No", "No"), SChan = c("Yes", 
18"Yes"), Language = c("en", "EN"), URL1 = c("NA", "NA"), URL2 = c("NA", 
19"NA"), `2018-03` = c(NA_real_, NA_real_), `2018-04` = c(NA_real_, 
20NA_real_), `2018-05` = c(NA_real_, NA_real_), `2018-06` = c(NA_real_, 
21NA_real_), `2018-07` = c(NA_real_, NA_real_), `2018-08` = c(NA_real_, 
22NA_real_), `2018-09` = c(NA_real_, NA_real_), `2018-10` = c(NA_real_, 
23NA_real_), `2018-11` = c(NA_real_, NA_real_), `2018-12` = c(NA_real_, 
24NA_real_), `2019-01` = c(NA_real_, NA_real_), `2019-02` = c(NA_real_, 
25NA_real_), `2019-03` = c(NA_real_, NA_real_), `2019-04` = c(NA_real_, 
26NA_real_), `2019-05` = c(NA_real_, NA_real_), `2019-06` = c(NA_real_, 
27NA_real_), `2019-07` = c(NA_real_, NA_real_), `2019-08` = c(NA_real_, 
28NA_real_), `2019-09` = c(NA_real_, NA_real_), `2019-10` = c(NA_real_, 
29NA_real_), `2019-11` = c(NA_real_, NA_real_), `2019-12` = c(NA_real_, 
30NA_real_), `2020-01` = c(NA_real_, NA_real_), `2020-02` = c(NA_real_, 
31NA_real_), `2020-03` = c(NA_real_, NA_real_), `2020-04` = c(NA_real_, 
32NA_real_), `2020-05` = c(NA_real_, NA_real_), `2020-06` = c(NA, 
3387710), `2020-07` = c(NA, 162416), `2020-08` = c(NA, 187892), 
34    `2020-09` = c(NA, 374661), `2020-10` = c(NA, 449634), `2020-12` = c(NA, 
35    1328523), `2021-01` = c(NA, 1525466), `2021-02` = c(NA, 1836399
36    ), `2021-03` = c(NA, 2752575), `2021-04` = c(86334, 1520546
37    ), `2021-05` = c(165124612, 3205193), `2021-06` = c(392264433,1534225), `2021-07` = c(282087438, 704348), `2021-08` = c(142305290, 
38    49416984), `2021-09` = c(103659781, 49469088), `2021-10` = c(124671803, 
39    20090134), `2021-11` = c(195965776, 363679038), `2021-12` = c(216612017, 
40    774113580), `2022-01` = c(376009215, 796724246), `2022-02` = c(193946191, 
41    599590598)), row.names = c(NA, -2L), class = c("tbl_df", 
42"tbl", "data.frame"))
43    
44shinyApp(
45  
46  ui = fluidPage(
47    selectInput("month", "Month:",
48                choices = colnames(Abstract_50)[10:56],multiple=T,selected=colnames(Abstract_50)[10:14]),
49    htmlOutput("tableset")
50  ),
51  
52  server = function(input, output) {
53    Ind<-Abstract_50[,c(4,10:56)] %>% 
54      group_by(Category) %>%
55      summarise(across(everything(), sum))
56    
57    Ind2<-reactive({
58      Ind <- Ind[,c("Category",input$month), drop = FALSE]
59      
60    })
61    Ind3<-reactive(Ind2() %>% remove_rownames %>% column_to_rownames(var="Category"))
62
63    Descs<-reactive(
64      Descs2<-tibble(Mean = rowMeans(Ind3(), na.rm = TRUE), 
65                     Median = rowMedians(as.matrix(Ind3()), na.rm = TRUE),
66                     SD=rowSds(as.matrix(Ind3()),na.rm = T),
67                     MAD=rowMads(as.matrix(Ind3(),na.rm=T)),
68                     MIN=rowMins(as.matrix(Ind3(),na.rm=T)),
69                     MAX=rowMaxs(as.matrix(Ind3(),na.rm=T)),
70                     VAR=rowVars(as.matrix(Ind3(),na.rm=T)),
71                     RANGE=rowRanges(as.matrix(Ind3(),na.rm=T)),
72                     QUANTILES=rowQuantiles(as.matrix(Ind3()), na.rm = TRUE)[, c(2, 4)]),
73      
74      Descs2<-as.data.frame(Descs2),
75      rownames(Descs2)<-rownames(Ind3()),
76      Descs2
77    )
78    
79    
80    
81    
82    output$tableset <- renderText({
83      kable(Descs()) %>%
84        kable_styling(
85          font_size = 15,
86          bootstrap_options = c("striped", "hover", "condensed")
87        ) 
88    })
89  },
90  
91  options = list(height = 500)
92  
93)
94 Descs2<-as.data.frame(Descs2),
95 rownames(Descs2)<-rownames(Ind3()),
96 ui = fluidPage(
97    selectInput("month", "Month:",
98                choices = colnames(Abstract_50)[10:56],multiple=TRUE,selected=colnames(Abstract_50)[10:14]),
99    htmlOutput("tableset")
100  )
101  
102  server = function(input, output) {
103    Ind<-Abstract_50[,c(4,10:56)] %>% 
104      group_by(Category) %>%
105      summarise(across(everything(), sum))
106    
107    Ind2<-reactive({
108      Ind <- Ind[,c("Category",input$month), drop = FALSE]
109      
110    })
111    Ind3<-reactive({
112         req(Ind2())
113         Ind2() %>% remove_rownames %>% column_to_rownames(var="Category")
114    }
115         
116         )
117    
118    
119    Descs<-reactive({
120         req(Ind3())
121         tmp <- Ind3()
122      Descs2<-tibble(Mean = rowMeans(tmp, na.rm = TRUE), 
123                     Median = rowMedians(as.matrix(tmp), na.rm = TRUE),
124                     SD=rowSds(as.matrix(tmp),na.rm = TRUE),
125                     MAD=rowMads(as.matrix(tmp,na.rm=TRUE)),
126                     MIN=rowMins(as.matrix(tmp,na.rm=TRUE)),
127                     MAX=rowMaxs(as.matrix(tmp,na.rm=TRUE)),
128                     VAR=rowVars(as.matrix(tmp,na.rm=TRUE)),
129                     RANGE=rowRanges(as.matrix(tmp,na.rm=TRUE)),
130                     QUANTILES=rowQuantiles(as.matrix(tmp), na.rm = TRUE)[, c(2, 4)])
131      
132      Descs2<-as.data.frame(Descs2)
133      rownames(Descs2)<-rownames(tmp)
134      Descs2
135    }
136    )
137    
138    
139    
140    
141    output$tableset <- renderText({
142      kable(Descs()) %>%
143        kable_styling(
144          font_size = 15,
145          bootstrap_options = c("striped", "hover", "condensed")
146        ) 
147    })
148  }
149  
150shinyApp(ui = ui, server = server, options = list(height = 500))
151

Source https://stackoverflow.com/questions/71530456

QUESTION

Boxes are not displayed in ggplot2 boxplot

Asked 2022-Mar-17 at 17:47

I have the dataframe below and I create a box plot but I cannot see the boxes for some reason.Is it because of my values? How can I display them?

1    df<-structure(list(Comedy = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
30, 0, 0, 0, 0, 0, 192993657, 2027127534, 1826083072, 1128287155, 
41757374990, 2694138537, 3190204219, 2038778526), Education = c(943330388, 
51155823837, 1360355713, 1826278073, 2188996970, 2021212414, 2289941566, 
62127165749, 1783936602, 2872498991, 2853872150, 3064968119, 3215161644, 
73049311469, 2820083900, 2044822024, 3779135880, 2844133676, 3376034265, 
83041618231, 3105665413, 3550804553, 3539721850, 4456458622, 4991538788, 
95828853483, 4966268171, 4512424020, 4502737563, 4375577460, 4552548135, 
103738145324, 3995222561, 3953186608, 3594443364, 3585009005, 2700428379, 
112902711237, 2359179701, 2740895126, 1867652957, 2048359210, 2314370309, 
122998250015, 3491065357, 3903773976, 2935444472), Entertainment = c(0, 
130, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
140, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7788928842, 7204965173, 
156992191235, 5457111773, 6860197195, 8855099815, 10013159307, 
1610474839762, 9524669175), `Film & Animation` = c(0, 0, 0, 0, 
170, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 759717307, 
18615753280, 318711634, 333904916, -693533921, 2091024234, 950022270, 
191001308730, 1026354524, 1081811412, 1199434291, 1433216491, 1442529761, 
201532974436, 1395606514, 1363861251, 1389014794, 1593050956, 1685049970, 
211547131073, 1518807877, 1233700577, 1218615927, 1454858377, 1352274781
22), Gaming = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
230, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2510727459, 2443299082, 3488510114, 5039516826, 3532430927, 3672818367, 3326539144, 
243130946776, 3280046870, 3691388930, 2605046632), `Howto & Style` = c(543234645, 
25637460061, 715598918, 853921148, 863342506, 795767480, 746997762, 
26653842221, 788862290, 591282170, 568671091, 548087579, 485300284, 
27436535293, 568286241, 478040015, 521541708, 405161168, 319837479, 
28280725401, 360157763, 165904320, 212343880, 327743010, 395400144, 
29426654776, 366884505, 357665076, 364828829, 345995485, 297049174, 
30240780776, 274207911, 273912428, 319470376, 392600212, 360147433, 
31264181288, 251605545, 236415550, 204441940, 421922863, 256820429, 
32424107264, 431256372, 390931344, 274420963), Music = c(45831420, 
3338904148, 73012836, 84645886, 111060240, 57262179, 26950500, 
3439134840, 60187872, 47610185, 23140910, 25985719, 28712442, 25722654, 
3547876708, 25865517, 32238860, 40636947, 44902937, 55838200, 36025492, 
3628671767, 82421655, 31274307, 42413334, 7507664, 35619244, -11045119, 
3737486877, 20923182, 27529830, 30924536, 28565411, 39739293, 23233821, 
38115184742, 25449369, 23944670, 41185546, -16964201, 47813282, 
3921983523, 17880023, 13962494, 12342364, 13356074, 13021208), 
40    `People & Blogs` = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
41    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
42    0, 0, 0, 0, 398375824, 454784769, 370688348, 369779164, 500101683,833749803, 1063138342, 1479795070, 1619160390, 1834784208, 
43    2111705491, 1350498139), `Science & Technology` = c(27301292, 
44    39573248, 48043856, 39855934, 52061005, 49053872, 49842103, 
45    44976795, 124632168, 50023068, 62941217, 47587876, 77099065, 
46    84765100, 58321781, 91284611, 96894838, 94260454, 72295712, 
47    102476421, 127194669, 67833402, 83318605, 114770114, 65328120, 
48    142092816, 123237585, 88539117, 176004414, 125341790, 142739116, 
49    86111812, 160017617, 131590671, 112033237, 129916112, 122655167, 
50    135571501, 63475989, 116497124, 94155011, 100342778, 90332692, 
51    88069070, 138735396, 76689085, 48123575), Sports = c(160818771, 
52    208830991, 189706047, 254772059, 310324223, 175281803, 245742536, 
53    213430460, 221505212, 231476966, 175724338, 258531007, 190968565, 
54    223061017, 210376637, 260369412, 289167706, 200040944, 260041965, 
55    200611576, 169604151, 276707678, 215539732, 214705917, 175674357, 
56    278796775, 285834056, 181252193, 270411741, 188726163, 189031053, 
57    155748840, 195702049, 160777215, 163685423, 191998118, 150304968, 
58    133674014, 162583897, 142010262, 123440234, 99242284, 100782041, 
59    81297079, 94100459, 123463360, 104218370)), class = "data.frame", row.names = c("2018-03", 
60"2018-04", "2018-05", "2018-06", "2018-07", "2018-08", "2018-09", 
61"2018-10", "2018-11", "2018-12", "2019-01", "2019-02", "2019-03","2019-04", "2019-05", "2019-06", "2019-07", "2019-08", "2019-09", 
62"2019-10", "2019-11", "2019-12", "2020-01", "2020-02", "2020-03", 
63"2020-04", "2020-05", "2020-06", "2020-07", "2020-08", "2020-09", 
64"2020-10", "2020-12", "2021-01", "2021-02", "2021-03", "2021-04", 
65"2021-05", "2021-06", "2021-07", "2021-08", "2021-09", "2021-10", 
66"2021-11", "2021-12", "2022-01", "2022-02"))
67    
68
69p<-ggplot(df, aes(x=WORDS, y=TOTALS, fill=WORDS)) +
70      geom_boxplot()
71    p+theme_minimal()+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))+ 
72      xlab("Industries") + ylab("Value")
73

ANSWER

Answered 2022-Mar-17 at 17:47

With the new data, it is in 'wide' format. We can reshape to 'long' with pivot_longer and it should work

1    df<-structure(list(Comedy = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
30, 0, 0, 0, 0, 0, 192993657, 2027127534, 1826083072, 1128287155, 
41757374990, 2694138537, 3190204219, 2038778526), Education = c(943330388, 
51155823837, 1360355713, 1826278073, 2188996970, 2021212414, 2289941566, 
62127165749, 1783936602, 2872498991, 2853872150, 3064968119, 3215161644, 
73049311469, 2820083900, 2044822024, 3779135880, 2844133676, 3376034265, 
83041618231, 3105665413, 3550804553, 3539721850, 4456458622, 4991538788, 
95828853483, 4966268171, 4512424020, 4502737563, 4375577460, 4552548135, 
103738145324, 3995222561, 3953186608, 3594443364, 3585009005, 2700428379, 
112902711237, 2359179701, 2740895126, 1867652957, 2048359210, 2314370309, 
122998250015, 3491065357, 3903773976, 2935444472), Entertainment = c(0, 
130, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
140, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7788928842, 7204965173, 
156992191235, 5457111773, 6860197195, 8855099815, 10013159307, 
1610474839762, 9524669175), `Film & Animation` = c(0, 0, 0, 0, 
170, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 759717307, 
18615753280, 318711634, 333904916, -693533921, 2091024234, 950022270, 
191001308730, 1026354524, 1081811412, 1199434291, 1433216491, 1442529761, 
201532974436, 1395606514, 1363861251, 1389014794, 1593050956, 1685049970, 
211547131073, 1518807877, 1233700577, 1218615927, 1454858377, 1352274781
22), Gaming = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
230, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2510727459, 2443299082, 3488510114, 5039516826, 3532430927, 3672818367, 3326539144, 
243130946776, 3280046870, 3691388930, 2605046632), `Howto & Style` = c(543234645, 
25637460061, 715598918, 853921148, 863342506, 795767480, 746997762, 
26653842221, 788862290, 591282170, 568671091, 548087579, 485300284, 
27436535293, 568286241, 478040015, 521541708, 405161168, 319837479, 
28280725401, 360157763, 165904320, 212343880, 327743010, 395400144, 
29426654776, 366884505, 357665076, 364828829, 345995485, 297049174, 
30240780776, 274207911, 273912428, 319470376, 392600212, 360147433, 
31264181288, 251605545, 236415550, 204441940, 421922863, 256820429, 
32424107264, 431256372, 390931344, 274420963), Music = c(45831420, 
3338904148, 73012836, 84645886, 111060240, 57262179, 26950500, 
3439134840, 60187872, 47610185, 23140910, 25985719, 28712442, 25722654, 
3547876708, 25865517, 32238860, 40636947, 44902937, 55838200, 36025492, 
3628671767, 82421655, 31274307, 42413334, 7507664, 35619244, -11045119, 
3737486877, 20923182, 27529830, 30924536, 28565411, 39739293, 23233821, 
38115184742, 25449369, 23944670, 41185546, -16964201, 47813282, 
3921983523, 17880023, 13962494, 12342364, 13356074, 13021208), 
40    `People & Blogs` = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
41    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
42    0, 0, 0, 0, 398375824, 454784769, 370688348, 369779164, 500101683,833749803, 1063138342, 1479795070, 1619160390, 1834784208, 
43    2111705491, 1350498139), `Science & Technology` = c(27301292, 
44    39573248, 48043856, 39855934, 52061005, 49053872, 49842103, 
45    44976795, 124632168, 50023068, 62941217, 47587876, 77099065, 
46    84765100, 58321781, 91284611, 96894838, 94260454, 72295712, 
47    102476421, 127194669, 67833402, 83318605, 114770114, 65328120, 
48    142092816, 123237585, 88539117, 176004414, 125341790, 142739116, 
49    86111812, 160017617, 131590671, 112033237, 129916112, 122655167, 
50    135571501, 63475989, 116497124, 94155011, 100342778, 90332692, 
51    88069070, 138735396, 76689085, 48123575), Sports = c(160818771, 
52    208830991, 189706047, 254772059, 310324223, 175281803, 245742536, 
53    213430460, 221505212, 231476966, 175724338, 258531007, 190968565, 
54    223061017, 210376637, 260369412, 289167706, 200040944, 260041965, 
55    200611576, 169604151, 276707678, 215539732, 214705917, 175674357, 
56    278796775, 285834056, 181252193, 270411741, 188726163, 189031053, 
57    155748840, 195702049, 160777215, 163685423, 191998118, 150304968, 
58    133674014, 162583897, 142010262, 123440234, 99242284, 100782041, 
59    81297079, 94100459, 123463360, 104218370)), class = "data.frame", row.names = c("2018-03", 
60"2018-04", "2018-05", "2018-06", "2018-07", "2018-08", "2018-09", 
61"2018-10", "2018-11", "2018-12", "2019-01", "2019-02", "2019-03","2019-04", "2019-05", "2019-06", "2019-07", "2019-08", "2019-09", 
62"2019-10", "2019-11", "2019-12", "2020-01", "2020-02", "2020-03", 
63"2020-04", "2020-05", "2020-06", "2020-07", "2020-08", "2020-09", 
64"2020-10", "2020-12", "2021-01", "2021-02", "2021-03", "2021-04", 
65"2021-05", "2021-06", "2021-07", "2021-08", "2021-09", "2021-10", 
66"2021-11", "2021-12", "2022-01", "2022-02"))
67    
68
69p<-ggplot(df, aes(x=WORDS, y=TOTALS, fill=WORDS)) +
70      geom_boxplot()
71    p+theme_minimal()+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))+ 
72      xlab("Industries") + ylab("Value")
73library(dplyr)
74library(tidyr)
75library(ggplot2)
76df_long <- pivot_longer(df, cols = everything(), names_to = 'WORDS', 
77       values_to = 'TOTALS') 
78
79p <- ggplot(df_long, aes(x = WORDS, y = TOTALS, fill = WORDS)) + 
80      geom_boxplot()
81
82p  +  
83   theme_minimal()+ 
84    theme(axis.text.x = element_text(angle = 90, vjust = 0.5, 
85        hjust=1))+ 
86     xlab("Industries") +
87     ylab("Value")
88

-output

enter image description here

Source https://stackoverflow.com/questions/71516703

QUESTION

Apply mean and median in every row of a dataframe and add them as separated columns to the dataframe

Asked 2022-Mar-17 at 16:40

I have the dataframe below:

1structure(list(`2018-03` = c(NA, 943330388, NA, NA, NA, 543234645, 
245831420, NA, 27301292, 160818771), `2018-04` = c(NA, 1155823837, 
3NA, NA, NA, 637460061, 38904148, NA, 39573248, 208830991), `2018-05` = c(NA, 
41360355713, NA, NA, NA, 715598918, 73012836, NA, 48043856, 189706047
5)), class = "data.frame", row.names = c("Comedy", "Education", 
6"Entertainment", "Film & Animation", "Gaming", "Howto & Style", 
7"Music", "People & Blogs", "Science & Technology", "Sports"))
8

and I want to create a new dataframe with row names the same as now and the 2 new columns should be the mean for every row, and the median of every row.

ANSWER

Answered 2022-Mar-17 at 16:40

We could use rowMeans with rowMedians (from matrixStats)

1structure(list(`2018-03` = c(NA, 943330388, NA, NA, NA, 543234645, 
245831420, NA, 27301292, 160818771), `2018-04` = c(NA, 1155823837, 
3NA, NA, NA, 637460061, 38904148, NA, 39573248, 208830991), `2018-05` = c(NA, 
41360355713, NA, NA, NA, 715598918, 73012836, NA, 48043856, 189706047
5)), class = "data.frame", row.names = c("Comedy", "Education", 
6"Entertainment", "Film & Animation", "Gaming", "Howto & Style", 
7"Music", "People & Blogs", "Science & Technology", "Sports"))
8library(matrixStats)
9library(tibble)
10tibble(Mean = rowMeans(df1, na.rm = TRUE), 
11      Median = rowMedians(as.matrix(df1), na.rm = TRUE))
12

Source https://stackoverflow.com/questions/71515620

QUESTION

Why is my XPath returning only text without tags?

Asked 2022-Mar-17 at 02:34

I am using Google Sheets to send an update to my Discord server every time there is an update from a forum site.

However, when I scrape this link,

https://forum.mir4global.com/board/patchnote

using this XPath,

1string((//*[@id="viewContent"])[1])
2

via use IMPORTXML I get this result:

"  We strive to provide a fun and fair gaming experience for all our players. Our team carefully monitors and actively removes players who do not adhere to the Operational Policy and Terms of Use.>> Operational Policy>> Terms of UseWe maintain a zero-tolerance policy against the use of unauthorized programs or software, manipulation or tampering of game data, and intentional exploitation of game systems. To date, we have permanently restricted more than 11,062,000 accounts. [Accounts Banned or Restricted]- Applicable Date: Wednesday, Mar. 16th, 2022- Number of Accounts: 114,952 (Total 11,062,063) - Reason: Use of unauthorized programs & Violation of Operational Policy*If you wish to make an appeal for the restriction imposed onto your account, please submit a support ticket through our official website. (https://cs.mir4global.com/customer)Inquiry Route : Contact Us > Account > Objection of restriction※ Please note that it may take a long time to receive an answer if you don't submit your inquiry ticket through the route above. We will continue to do our best in order to ensure a safe, fair, and fun gaming environment for all our players. "

How can I get the same format like in the forum site?

ANSWER

Answered 2022-Mar-17 at 02:34

The whole point of the XPath function, string(), is to return the string-value (just the text without any markup) of the given node.

If you want the markup, remove the wrapping string() function.

Source https://stackoverflow.com/questions/71506248

QUESTION

Create columns from row values and fill - pandas

Asked 2022-Mar-04 at 09:57

I have a dataframe that looks like this:

df=pd.read_csv('https://raw.githubusercontent.com/amanaroratc/hello-world/master/ask_git.csv')

1    Channel_ID  Video_Category_Name score_pct
20   UC--bUZc5c9WseZNqGR6KLxA    Autos & Vehicles    0.213702
31   UC--bUZc5c9WseZNqGR6KLxA    Entertainment   0.786298
42   UC-B1L3oT81XgeeGh6S12qgQ    People & Blogs  1.000000
53   UC-N_7HFKrSsYxCSA_kfdRSA    People & Blogs  0.137261
64   UC-N_7HFKrSsYxCSA_kfdRSA    Pets & Animals  0.862739
7... ... ... ...
8819 UCzsNLZ9GrGXRjt0QmvWFm2Q    Entertainment   0.945243
9820 UCzsNLZ9GrGXRjt0QmvWFm2Q    Film & Animation    0.002046
10821 UCzsNLZ9GrGXRjt0QmvWFm2Q    Music   0.002797
11822 UCzsNLZ9GrGXRjt0QmvWFm2Q    News & Politics 0.000433
12823 UCzsNLZ9GrGXRjt0QmvWFm2Q    People & Blogs  0.000358
13

There are 15 distinct values in Video_Category_Name:

1    Channel_ID  Video_Category_Name score_pct
20   UC--bUZc5c9WseZNqGR6KLxA    Autos & Vehicles    0.213702
31   UC--bUZc5c9WseZNqGR6KLxA    Entertainment   0.786298
42   UC-B1L3oT81XgeeGh6S12qgQ    People & Blogs  1.000000
53   UC-N_7HFKrSsYxCSA_kfdRSA    People & Blogs  0.137261
64   UC-N_7HFKrSsYxCSA_kfdRSA    Pets & Animals  0.862739
7... ... ... ...
8819 UCzsNLZ9GrGXRjt0QmvWFm2Q    Entertainment   0.945243
9820 UCzsNLZ9GrGXRjt0QmvWFm2Q    Film & Animation    0.002046
10821 UCzsNLZ9GrGXRjt0QmvWFm2Q    Music   0.002797
11822 UCzsNLZ9GrGXRjt0QmvWFm2Q    News & Politics 0.000433
12823 UCzsNLZ9GrGXRjt0QmvWFm2Q    People & Blogs  0.000358
13df.Video_Category_Name.unique()
14

gives

1    Channel_ID  Video_Category_Name score_pct
20   UC--bUZc5c9WseZNqGR6KLxA    Autos & Vehicles    0.213702
31   UC--bUZc5c9WseZNqGR6KLxA    Entertainment   0.786298
42   UC-B1L3oT81XgeeGh6S12qgQ    People & Blogs  1.000000
53   UC-N_7HFKrSsYxCSA_kfdRSA    People & Blogs  0.137261
64   UC-N_7HFKrSsYxCSA_kfdRSA    Pets & Animals  0.862739
7... ... ... ...
8819 UCzsNLZ9GrGXRjt0QmvWFm2Q    Entertainment   0.945243
9820 UCzsNLZ9GrGXRjt0QmvWFm2Q    Film & Animation    0.002046
10821 UCzsNLZ9GrGXRjt0QmvWFm2Q    Music   0.002797
11822 UCzsNLZ9GrGXRjt0QmvWFm2Q    News & Politics 0.000433
12823 UCzsNLZ9GrGXRjt0QmvWFm2Q    People & Blogs  0.000358
13df.Video_Category_Name.unique()
14array(['Autos & Vehicles', 'Entertainment', 'People & Blogs',
15       'Pets & Animals', 'Howto & Style', 'Education', 'Gaming', 'Music',
16       'Comedy', 'Travel & Events', 'Science & Technology',
17       'Nonprofits & Activism', 'Sports', 'Film & Animation',
18       'News & Politics'], dtype=object)
19
1    Channel_ID  Video_Category_Name score_pct
20   UC--bUZc5c9WseZNqGR6KLxA    Autos & Vehicles    0.213702
31   UC--bUZc5c9WseZNqGR6KLxA    Entertainment   0.786298
42   UC-B1L3oT81XgeeGh6S12qgQ    People & Blogs  1.000000
53   UC-N_7HFKrSsYxCSA_kfdRSA    People & Blogs  0.137261
64   UC-N_7HFKrSsYxCSA_kfdRSA    Pets & Animals  0.862739
7... ... ... ...
8819 UCzsNLZ9GrGXRjt0QmvWFm2Q    Entertainment   0.945243
9820 UCzsNLZ9GrGXRjt0QmvWFm2Q    Film & Animation    0.002046
10821 UCzsNLZ9GrGXRjt0QmvWFm2Q    Music   0.002797
11822 UCzsNLZ9GrGXRjt0QmvWFm2Q    News & Politics 0.000433
12823 UCzsNLZ9GrGXRjt0QmvWFm2Q    People & Blogs  0.000358
13df.Video_Category_Name.unique()
14array(['Autos & Vehicles', 'Entertainment', 'People & Blogs',
15       'Pets & Animals', 'Howto & Style', 'Education', 'Gaming', 'Music',
16       'Comedy', 'Travel & Events', 'Science & Technology',
17       'Nonprofits & Activism', 'Sports', 'Film & Animation',
18       'News & Politics'], dtype=object)
19 In [3]: iwantthis
20  Out[3]:
21     Channel_ID  Autos & Vehicles Entertainment People & Blogs ...
22  0  UC--bUZc5c9WseZNqGR6KLxA  0.213702 0.786298 0 ...
23  1  UC-B1L3oT81XgeeGh6S12qgQ  0        0        1.0000 ...
24

How do I create a column for each of these 15 and fill value from score_pct (0 if it does not exist)? Not sure how to use unstack/melt/pivot or something else

ANSWER

Answered 2022-Mar-04 at 09:57

I think pivot() is the right function for your problem. It takes the categorial values of Video_Category_Name and creates new columns, which are filled with the value of score_pct. Non existing values are replaced by zero with `filna(0):

1    Channel_ID  Video_Category_Name score_pct
20   UC--bUZc5c9WseZNqGR6KLxA    Autos & Vehicles    0.213702
31   UC--bUZc5c9WseZNqGR6KLxA    Entertainment   0.786298
42   UC-B1L3oT81XgeeGh6S12qgQ    People & Blogs  1.000000
53   UC-N_7HFKrSsYxCSA_kfdRSA    People & Blogs  0.137261
64   UC-N_7HFKrSsYxCSA_kfdRSA    Pets & Animals  0.862739
7... ... ... ...
8819 UCzsNLZ9GrGXRjt0QmvWFm2Q    Entertainment   0.945243
9820 UCzsNLZ9GrGXRjt0QmvWFm2Q    Film & Animation    0.002046
10821 UCzsNLZ9GrGXRjt0QmvWFm2Q    Music   0.002797
11822 UCzsNLZ9GrGXRjt0QmvWFm2Q    News & Politics 0.000433
12823 UCzsNLZ9GrGXRjt0QmvWFm2Q    People & Blogs  0.000358
13df.Video_Category_Name.unique()
14array(['Autos & Vehicles', 'Entertainment', 'People & Blogs',
15       'Pets & Animals', 'Howto & Style', 'Education', 'Gaming', 'Music',
16       'Comedy', 'Travel & Events', 'Science & Technology',
17       'Nonprofits & Activism', 'Sports', 'Film & Animation',
18       'News & Politics'], dtype=object)
19 In [3]: iwantthis
20  Out[3]:
21     Channel_ID  Autos & Vehicles Entertainment People & Blogs ...
22  0  UC--bUZc5c9WseZNqGR6KLxA  0.213702 0.786298 0 ...
23  1  UC-B1L3oT81XgeeGh6S12qgQ  0        0        1.0000 ...
24df = df.pivot(index='Channel_ID', columns='Video_Category_Name', values='score_pct').fillna(0).reset_index()
25

Output:

1    Channel_ID  Video_Category_Name score_pct
20   UC--bUZc5c9WseZNqGR6KLxA    Autos & Vehicles    0.213702
31   UC--bUZc5c9WseZNqGR6KLxA    Entertainment   0.786298
42   UC-B1L3oT81XgeeGh6S12qgQ    People & Blogs  1.000000
53   UC-N_7HFKrSsYxCSA_kfdRSA    People & Blogs  0.137261
64   UC-N_7HFKrSsYxCSA_kfdRSA    Pets & Animals  0.862739
7... ... ... ...
8819 UCzsNLZ9GrGXRjt0QmvWFm2Q    Entertainment   0.945243
9820 UCzsNLZ9GrGXRjt0QmvWFm2Q    Film & Animation    0.002046
10821 UCzsNLZ9GrGXRjt0QmvWFm2Q    Music   0.002797
11822 UCzsNLZ9GrGXRjt0QmvWFm2Q    News & Politics 0.000433
12823 UCzsNLZ9GrGXRjt0QmvWFm2Q    People & Blogs  0.000358
13df.Video_Category_Name.unique()
14array(['Autos & Vehicles', 'Entertainment', 'People & Blogs',
15       'Pets & Animals', 'Howto & Style', 'Education', 'Gaming', 'Music',
16       'Comedy', 'Travel & Events', 'Science & Technology',
17       'Nonprofits & Activism', 'Sports', 'Film & Animation',
18       'News & Politics'], dtype=object)
19 In [3]: iwantthis
20  Out[3]:
21     Channel_ID  Autos & Vehicles Entertainment People & Blogs ...
22  0  UC--bUZc5c9WseZNqGR6KLxA  0.213702 0.786298 0 ...
23  1  UC-B1L3oT81XgeeGh6S12qgQ  0        0        1.0000 ...
24df = df.pivot(index='Channel_ID', columns='Video_Category_Name', values='score_pct').fillna(0).reset_index()
25Video_Category_Name Channel_ID  Autos & Vehicles    Comedy  Education   Entertainment   Film & Animation    Gaming  Howto & Style   Music   News & Politics Nonprofits & Activism   People & Blogs  Pets & Animals  Science & Technology    Sports  Travel & Events
260   UC--bUZc5c9WseZNqGR6KLxA    0.213702    0.0 0.0 0.786298    0.0 0.0 0.0 0.0 0.0 0.0 0.000000    0.000000    0.0 0.0 0.0
271   UC-B1L3oT81XgeeGh6S12qgQ    0.000000    0.0 0.0 0.000000    0.0 0.0 0.0 0.0 0.0 0.0 1.000000    0.000000    0.0 0.0 0.0
282   UC-N_7HFKrSsYxCSA_kfdRSA    0.000000    0.0 0.0 0.000000    0.0 0.0 0.0 0.0 0.0 0.0 0.137261    0.862739    0.0 0.0 0.0
293   UC-T4JheeuNl2DVg-B-v7McA    0.000000    0.0 0.0 0.000000    0.0 0.0 1.0 0.0 0.0 0.0 0.000000    0.000000    0.0 0.0 0.0
304   UC-WG1VP4am6NaUtANEJxRQw    0.000000    0.0 0.0 0.000000    0.0 0.0 0.0 0.0 0.0 0.0 1.000000    0.000000    0.0 0.0 0.0
31

Edit 1: As the comment mentions this only works if Channel_ID is unique. If it is not (or to be safe) you can also include the index in the pivot operation. Afterwards restore the index again:

1    Channel_ID  Video_Category_Name score_pct
20   UC--bUZc5c9WseZNqGR6KLxA    Autos & Vehicles    0.213702
31   UC--bUZc5c9WseZNqGR6KLxA    Entertainment   0.786298
42   UC-B1L3oT81XgeeGh6S12qgQ    People & Blogs  1.000000
53   UC-N_7HFKrSsYxCSA_kfdRSA    People & Blogs  0.137261
64   UC-N_7HFKrSsYxCSA_kfdRSA    Pets & Animals  0.862739
7... ... ... ...
8819 UCzsNLZ9GrGXRjt0QmvWFm2Q    Entertainment   0.945243
9820 UCzsNLZ9GrGXRjt0QmvWFm2Q    Film & Animation    0.002046
10821 UCzsNLZ9GrGXRjt0QmvWFm2Q    Music   0.002797
11822 UCzsNLZ9GrGXRjt0QmvWFm2Q    News & Politics 0.000433
12823 UCzsNLZ9GrGXRjt0QmvWFm2Q    People & Blogs  0.000358
13df.Video_Category_Name.unique()
14array(['Autos & Vehicles', 'Entertainment', 'People & Blogs',
15       'Pets & Animals', 'Howto & Style', 'Education', 'Gaming', 'Music',
16       'Comedy', 'Travel & Events', 'Science & Technology',
17       'Nonprofits & Activism', 'Sports', 'Film & Animation',
18       'News & Politics'], dtype=object)
19 In [3]: iwantthis
20  Out[3]:
21     Channel_ID  Autos & Vehicles Entertainment People & Blogs ...
22  0  UC--bUZc5c9WseZNqGR6KLxA  0.213702 0.786298 0 ...
23  1  UC-B1L3oT81XgeeGh6S12qgQ  0        0        1.0000 ...
24df = df.pivot(index='Channel_ID', columns='Video_Category_Name', values='score_pct').fillna(0).reset_index()
25Video_Category_Name Channel_ID  Autos & Vehicles    Comedy  Education   Entertainment   Film & Animation    Gaming  Howto & Style   Music   News & Politics Nonprofits & Activism   People & Blogs  Pets & Animals  Science & Technology    Sports  Travel & Events
260   UC--bUZc5c9WseZNqGR6KLxA    0.213702    0.0 0.0 0.786298    0.0 0.0 0.0 0.0 0.0 0.0 0.000000    0.000000    0.0 0.0 0.0
271   UC-B1L3oT81XgeeGh6S12qgQ    0.000000    0.0 0.0 0.000000    0.0 0.0 0.0 0.0 0.0 0.0 1.000000    0.000000    0.0 0.0 0.0
282   UC-N_7HFKrSsYxCSA_kfdRSA    0.000000    0.0 0.0 0.000000    0.0 0.0 0.0 0.0 0.0 0.0 0.137261    0.862739    0.0 0.0 0.0
293   UC-T4JheeuNl2DVg-B-v7McA    0.000000    0.0 0.0 0.000000    0.0 0.0 1.0 0.0 0.0 0.0 0.000000    0.000000    0.0 0.0 0.0
304   UC-WG1VP4am6NaUtANEJxRQw    0.000000    0.0 0.0 0.000000    0.0 0.0 0.0 0.0 0.0 0.0 1.000000    0.000000    0.0 0.0 0.0
31df = df.reset_index().pivot(index=['index', 'Channel_ID'], columns='Video_Category_Name', values='score_pct').fillna(0).reset_index(level=1)
32

Edit 2: The Video_Category_Name in the dataframe is only the label of the columns and should not change anything. However, you can easily remove it with this line:

1    Channel_ID  Video_Category_Name score_pct
20   UC--bUZc5c9WseZNqGR6KLxA    Autos & Vehicles    0.213702
31   UC--bUZc5c9WseZNqGR6KLxA    Entertainment   0.786298
42   UC-B1L3oT81XgeeGh6S12qgQ    People & Blogs  1.000000
53   UC-N_7HFKrSsYxCSA_kfdRSA    People & Blogs  0.137261
64   UC-N_7HFKrSsYxCSA_kfdRSA    Pets & Animals  0.862739
7... ... ... ...
8819 UCzsNLZ9GrGXRjt0QmvWFm2Q    Entertainment   0.945243
9820 UCzsNLZ9GrGXRjt0QmvWFm2Q    Film & Animation    0.002046
10821 UCzsNLZ9GrGXRjt0QmvWFm2Q    Music   0.002797
11822 UCzsNLZ9GrGXRjt0QmvWFm2Q    News & Politics 0.000433
12823 UCzsNLZ9GrGXRjt0QmvWFm2Q    People & Blogs  0.000358
13df.Video_Category_Name.unique()
14array(['Autos & Vehicles', 'Entertainment', 'People & Blogs',
15       'Pets & Animals', 'Howto & Style', 'Education', 'Gaming', 'Music',
16       'Comedy', 'Travel & Events', 'Science & Technology',
17       'Nonprofits & Activism', 'Sports', 'Film & Animation',
18       'News & Politics'], dtype=object)
19 In [3]: iwantthis
20  Out[3]:
21     Channel_ID  Autos & Vehicles Entertainment People & Blogs ...
22  0  UC--bUZc5c9WseZNqGR6KLxA  0.213702 0.786298 0 ...
23  1  UC-B1L3oT81XgeeGh6S12qgQ  0        0        1.0000 ...
24df = df.pivot(index='Channel_ID', columns='Video_Category_Name', values='score_pct').fillna(0).reset_index()
25Video_Category_Name Channel_ID  Autos & Vehicles    Comedy  Education   Entertainment   Film & Animation    Gaming  Howto & Style   Music   News & Politics Nonprofits & Activism   People & Blogs  Pets & Animals  Science & Technology    Sports  Travel & Events
260   UC--bUZc5c9WseZNqGR6KLxA    0.213702    0.0 0.0 0.786298    0.0 0.0 0.0 0.0 0.0 0.0 0.000000    0.000000    0.0 0.0 0.0
271   UC-B1L3oT81XgeeGh6S12qgQ    0.000000    0.0 0.0 0.000000    0.0 0.0 0.0 0.0 0.0 0.0 1.000000    0.000000    0.0 0.0 0.0
282   UC-N_7HFKrSsYxCSA_kfdRSA    0.000000    0.0 0.0 0.000000    0.0 0.0 0.0 0.0 0.0 0.0 0.137261    0.862739    0.0 0.0 0.0
293   UC-T4JheeuNl2DVg-B-v7McA    0.000000    0.0 0.0 0.000000    0.0 0.0 1.0 0.0 0.0 0.0 0.000000    0.000000    0.0 0.0 0.0
304   UC-WG1VP4am6NaUtANEJxRQw    0.000000    0.0 0.0 0.000000    0.0 0.0 0.0 0.0 0.0 0.0 1.000000    0.000000    0.0 0.0 0.0
31df = df.reset_index().pivot(index=['index', 'Channel_ID'], columns='Video_Category_Name', values='score_pct').fillna(0).reset_index(level=1)
32df = df.rename_axis(None, axis=1) 
33

For the solution of Edit 1 you might also want to remove the index name, which can be done with the same operation and a different axis:

1    Channel_ID  Video_Category_Name score_pct
20   UC--bUZc5c9WseZNqGR6KLxA    Autos & Vehicles    0.213702
31   UC--bUZc5c9WseZNqGR6KLxA    Entertainment   0.786298
42   UC-B1L3oT81XgeeGh6S12qgQ    People & Blogs  1.000000
53   UC-N_7HFKrSsYxCSA_kfdRSA    People & Blogs  0.137261
64   UC-N_7HFKrSsYxCSA_kfdRSA    Pets & Animals  0.862739
7... ... ... ...
8819 UCzsNLZ9GrGXRjt0QmvWFm2Q    Entertainment   0.945243
9820 UCzsNLZ9GrGXRjt0QmvWFm2Q    Film & Animation    0.002046
10821 UCzsNLZ9GrGXRjt0QmvWFm2Q    Music   0.002797
11822 UCzsNLZ9GrGXRjt0QmvWFm2Q    News & Politics 0.000433
12823 UCzsNLZ9GrGXRjt0QmvWFm2Q    People & Blogs  0.000358
13df.Video_Category_Name.unique()
14array(['Autos & Vehicles', 'Entertainment', 'People & Blogs',
15       'Pets & Animals', 'Howto & Style', 'Education', 'Gaming', 'Music',
16       'Comedy', 'Travel & Events', 'Science & Technology',
17       'Nonprofits & Activism', 'Sports', 'Film & Animation',
18       'News & Politics'], dtype=object)
19 In [3]: iwantthis
20  Out[3]:
21     Channel_ID  Autos & Vehicles Entertainment People & Blogs ...
22  0  UC--bUZc5c9WseZNqGR6KLxA  0.213702 0.786298 0 ...
23  1  UC-B1L3oT81XgeeGh6S12qgQ  0        0        1.0000 ...
24df = df.pivot(index='Channel_ID', columns='Video_Category_Name', values='score_pct').fillna(0).reset_index()
25Video_Category_Name Channel_ID  Autos & Vehicles    Comedy  Education   Entertainment   Film & Animation    Gaming  Howto & Style   Music   News & Politics Nonprofits & Activism   People & Blogs  Pets & Animals  Science & Technology    Sports  Travel & Events
260   UC--bUZc5c9WseZNqGR6KLxA    0.213702    0.0 0.0 0.786298    0.0 0.0 0.0 0.0 0.0 0.0 0.000000    0.000000    0.0 0.0 0.0
271   UC-B1L3oT81XgeeGh6S12qgQ    0.000000    0.0 0.0 0.000000    0.0 0.0 0.0 0.0 0.0 0.0 1.000000    0.000000    0.0 0.0 0.0
282   UC-N_7HFKrSsYxCSA_kfdRSA    0.000000    0.0 0.0 0.000000    0.0 0.0 0.0 0.0 0.0 0.0 0.137261    0.862739    0.0 0.0 0.0
293   UC-T4JheeuNl2DVg-B-v7McA    0.000000    0.0 0.0 0.000000    0.0 0.0 1.0 0.0 0.0 0.0 0.000000    0.000000    0.0 0.0 0.0
304   UC-WG1VP4am6NaUtANEJxRQw    0.000000    0.0 0.0 0.000000    0.0 0.0 0.0 0.0 0.0 0.0 1.000000    0.000000    0.0 0.0 0.0
31df = df.reset_index().pivot(index=['index', 'Channel_ID'], columns='Video_Category_Name', values='score_pct').fillna(0).reset_index(level=1)
32df = df.rename_axis(None, axis=1) 
33df = df.rename_axis(None, axis=0)
34

Source https://stackoverflow.com/questions/71349085

QUESTION

Implementing 3 modals triggered by 3 buttons

Asked 2022-Feb-19 at 19:42

I have 3 modal buttons. All three buttons have different inputs. But when I press the first button, everything is showing completely fine but when I press the 2nd and 3rd button, it shows the same results as the first button. Please have a look, I am attaching my code below.

Extra: It would be very helpful for me if you can suggest me, how I can put multiple photos stacked in the modal body without losing the shape of the modal. It will show a single photo in the modal body but if someone swap over the picture then the next picture will arrive. Thank you so much.

1// Modal
2// Get DOM Elements
3const modal = document.querySelector('#my-modal');
4const modalBtn = document.querySelectorAll('.button');
5const closeBtn = document.querySelector('.close');
6
7// Events
8modalBtn.forEach(btn => btn.addEventListener('click', openModal));
9closeBtn.addEventListener('click', closeModal);
10window.addEventListener('click', outsideClick);
11
12// Open
13function openModal() {
14  modal.style.display = 'block';
15}
16
17// Close
18function closeModal() {
19  modal.style.display = 'none';
20}
21
22// Close If Outside Click
23function outsideClick(e) {
24  if (e.target == modal) {
25    modal.style.display = 'none';
26  }
27}
1// Modal
2// Get DOM Elements
3const modal = document.querySelector('#my-modal');
4const modalBtn = document.querySelectorAll('.button');
5const closeBtn = document.querySelector('.close');
6
7// Events
8modalBtn.forEach(btn => btn.addEventListener('click', openModal));
9closeBtn.addEventListener('click', closeModal);
10window.addEventListener('click', outsideClick);
11
12// Open
13function openModal() {
14  modal.style.display = 'block';
15}
16
17// Close
18function closeModal() {
19  modal.style.display = 'none';
20}
21
22// Close If Outside Click
23function outsideClick(e) {
24  if (e.target == modal) {
25    modal.style.display = 'none';
26  }
27}/* Modal section styling */
28
29:root {
30    --modal-duration: 1s;
31    --modal-color: crimson;
32  }
33  
34  .button {
35    font-family: 'poppins', sans-serif;
36    display: inline-block;
37    background: crimson;
38    color: #fff;
39    font-size: 18px;
40    font-weight: 500;
41    padding: 8px 16px;
42    margin-top: 20px;
43    border-radius: 6px;
44    border: 2px solid crimson;
45    transition: all 0.3s ease;
46  }
47  
48  .button:hover {
49    color: crimson;
50    background: none;
51  }
52  
53  .modal {
54    display: none;
55    position: fixed;
56    z-index: 99999;
57    left: 0;
58    top: 0;
59    height: 100%;
60    width: 100%;
61    overflow: auto;
62    background-color: rgba(0, 0, 0, 0.5);
63  }
64  
65  .modal-content {
66    margin: 50px auto;
67    width: 60%;
68    box-shadow: 0 5px 8px 0 rgba(0, 0, 0, 0.2), 0 7px 20px 0 rgba(0, 0, 0, 0.17);
69    animation-name: modalopen;
70    animation-duration: var(--modal-duration);
71  }
72  
73  .modal-header h2,
74  .modal-footer h3 {
75    margin: 0;
76  }
77  
78  .modal-header {
79    background: var(--modal-color);
80    text-align: center;
81    padding: 10px;
82    color: #fff;
83    border-top-left-radius: 5px;
84    border-top-right-radius: 5px;
85  }
86  
87  .modal-body {
88    padding: 10px 5px 1px 5px;
89    background: #fff;
90  }
91  
92  .modal-footer {
93    background: var(--modal-color);
94    padding: 10px;
95    font-size: 15px;
96    font-weight: lighter;
97    color: #fff;
98    text-align: center;
99    border-bottom-left-radius: 5px;
100    border-bottom-right-radius: 5px;
101  }
102  
103  .close {
104    color: #ccc;
105    float: right;
106    font-size: 30px;
107    color: #fff;
108  }
109  
110  .close:hover,
111  .close:focus {
112    color: #000;
113    text-decoration: none;
114    cursor: pointer;
115  }
116  .responsive {
117    width: 100%;
118    height: auto;
119  }
120  @keyframes modalopen {
121    from {
122      opacity: 0;
123    }
124    to {
125      opacity: 1;
126    }
127  }
1// Modal
2// Get DOM Elements
3const modal = document.querySelector('#my-modal');
4const modalBtn = document.querySelectorAll('.button');
5const closeBtn = document.querySelector('.close');
6
7// Events
8modalBtn.forEach(btn => btn.addEventListener('click', openModal));
9closeBtn.addEventListener('click', closeModal);
10window.addEventListener('click', outsideClick);
11
12// Open
13function openModal() {
14  modal.style.display = 'block';
15}
16
17// Close
18function closeModal() {
19  modal.style.display = 'none';
20}
21
22// Close If Outside Click
23function outsideClick(e) {
24  if (e.target == modal) {
25    modal.style.display = 'none';
26  }
27}/* Modal section styling */
28
29:root {
30    --modal-duration: 1s;
31    --modal-color: crimson;
32  }
33  
34  .button {
35    font-family: 'poppins', sans-serif;
36    display: inline-block;
37    background: crimson;
38    color: #fff;
39    font-size: 18px;
40    font-weight: 500;
41    padding: 8px 16px;
42    margin-top: 20px;
43    border-radius: 6px;
44    border: 2px solid crimson;
45    transition: all 0.3s ease;
46  }
47  
48  .button:hover {
49    color: crimson;
50    background: none;
51  }
52  
53  .modal {
54    display: none;
55    position: fixed;
56    z-index: 99999;
57    left: 0;
58    top: 0;
59    height: 100%;
60    width: 100%;
61    overflow: auto;
62    background-color: rgba(0, 0, 0, 0.5);
63  }
64  
65  .modal-content {
66    margin: 50px auto;
67    width: 60%;
68    box-shadow: 0 5px 8px 0 rgba(0, 0, 0, 0.2), 0 7px 20px 0 rgba(0, 0, 0, 0.17);
69    animation-name: modalopen;
70    animation-duration: var(--modal-duration);
71  }
72  
73  .modal-header h2,
74  .modal-footer h3 {
75    margin: 0;
76  }
77  
78  .modal-header {
79    background: var(--modal-color);
80    text-align: center;
81    padding: 10px;
82    color: #fff;
83    border-top-left-radius: 5px;
84    border-top-right-radius: 5px;
85  }
86  
87  .modal-body {
88    padding: 10px 5px 1px 5px;
89    background: #fff;
90  }
91  
92  .modal-footer {
93    background: var(--modal-color);
94    padding: 10px;
95    font-size: 15px;
96    font-weight: lighter;
97    color: #fff;
98    text-align: center;
99    border-bottom-left-radius: 5px;
100    border-bottom-right-radius: 5px;
101  }
102  
103  .close {
104    color: #ccc;
105    float: right;
106    font-size: 30px;
107    color: #fff;
108  }
109  
110  .close:hover,
111  .close:focus {
112    color: #000;
113    text-decoration: none;
114    cursor: pointer;
115  }
116  .responsive {
117    width: 100%;
118    height: auto;
119  }
120  @keyframes modalopen {
121    from {
122      opacity: 0;
123    }
124    to {
125      opacity: 1;
126    }
127  }<!-- Modal Button 1 start -->
128<button id="modal-btn" class="button">Parkit</button>
129<div id="my-modal" class="modal">
130  <div class="modal-content">
131    <div class="modal-header">
132      <span class="close">×</span>
133      <h3>Vehicle Parking Application</h3>
134    </div>
135    <div class="modal-body">
136      <img src="https://thefinancialexpress.com.bd/uploads/1575560371.jpg" alt="Vehicle Parking Application" class="responsive">
137    </div>
138    <div class="modal-footer">
139      <p>
140      Footer
141      </p>
142    </div>
143  </div>
144</div>
145<!-- Modal Button 1 end -->
146
147<!-- Modal Button 2 start -->
148<button id="modal-btn2" class="button">IPDC IMS</button>
149<div id="my-modal2" class="modal">
150  <div class="modal-content">
151    <div class="modal-header">
152      <span class="close">×</span>
153      <h3>Asset Management System</h3>
154    </div>
155    <div class="modal-body">
156      <img src="#" alt="Asset Management System" class="responsive">
157    </div>
158    <div class="modal-footer">
159      ...
160    </div>
161  </div>
162</div>
163<!-- Modal Button 2 end -->
164
165<!-- Modal Button 3 start -->
166<button id="modal-btn3" class="button">Gaming Website</button>
167<div id="my-modal3" class="modal">
168  <div class="modal-content">
169    <div class="modal-header">
170      <span class="close">×</span>
171      <h3>Gaming Website</h3>
172    </div>
173    <div class="modal-body">
174      ...
175    </div>
176    <div class="modal-footer">
177
178    </div>
179  </div>
180</div>
181<!-- Modal Button 3 end -->

ANSWER

Answered 2022-Feb-19 at 19:42

This would solve the problem where every button triggering the same modal. You should be getting all modals and all buttons.

1// Modal
2// Get DOM Elements
3const modal = document.querySelector('#my-modal');
4const modalBtn = document.querySelectorAll('.button');
5const closeBtn = document.querySelector('.close');
6
7// Events
8modalBtn.forEach(btn => btn.addEventListener('click', openModal));
9closeBtn.addEventListener('click', closeModal);
10window.addEventListener('click', outsideClick);
11
12// Open
13function openModal() {
14  modal.style.display = 'block';
15}
16
17// Close
18function closeModal() {
19  modal.style.display = 'none';
20}
21
22// Close If Outside Click
23function outsideClick(e) {
24  if (e.target == modal) {
25    modal.style.display = 'none';
26  }
27}/* Modal section styling */
28
29:root {
30    --modal-duration: 1s;
31    --modal-color: crimson;
32  }
33  
34  .button {
35    font-family: 'poppins', sans-serif;
36    display: inline-block;
37    background: crimson;
38    color: #fff;
39    font-size: 18px;
40    font-weight: 500;
41    padding: 8px 16px;
42    margin-top: 20px;
43    border-radius: 6px;
44    border: 2px solid crimson;
45    transition: all 0.3s ease;
46  }
47  
48  .button:hover {
49    color: crimson;
50    background: none;
51  }
52  
53  .modal {
54    display: none;
55    position: fixed;
56    z-index: 99999;
57    left: 0;
58    top: 0;
59    height: 100%;
60    width: 100%;
61    overflow: auto;
62    background-color: rgba(0, 0, 0, 0.5);
63  }
64  
65  .modal-content {
66    margin: 50px auto;
67    width: 60%;
68    box-shadow: 0 5px 8px 0 rgba(0, 0, 0, 0.2), 0 7px 20px 0 rgba(0, 0, 0, 0.17);
69    animation-name: modalopen;
70    animation-duration: var(--modal-duration);
71  }
72  
73  .modal-header h2,
74  .modal-footer h3 {
75    margin: 0;
76  }
77  
78  .modal-header {
79    background: var(--modal-color);
80    text-align: center;
81    padding: 10px;
82    color: #fff;
83    border-top-left-radius: 5px;
84    border-top-right-radius: 5px;
85  }
86  
87  .modal-body {
88    padding: 10px 5px 1px 5px;
89    background: #fff;
90  }
91  
92  .modal-footer {
93    background: var(--modal-color);
94    padding: 10px;
95    font-size: 15px;
96    font-weight: lighter;
97    color: #fff;
98    text-align: center;
99    border-bottom-left-radius: 5px;
100    border-bottom-right-radius: 5px;
101  }
102  
103  .close {
104    color: #ccc;
105    float: right;
106    font-size: 30px;
107    color: #fff;
108  }
109  
110  .close:hover,
111  .close:focus {
112    color: #000;
113    text-decoration: none;
114    cursor: pointer;
115  }
116  .responsive {
117    width: 100%;
118    height: auto;
119  }
120  @keyframes modalopen {
121    from {
122      opacity: 0;
123    }
124    to {
125      opacity: 1;
126    }
127  }<!-- Modal Button 1 start -->
128<button id="modal-btn" class="button">Parkit</button>
129<div id="my-modal" class="modal">
130  <div class="modal-content">
131    <div class="modal-header">
132      <span class="close">×</span>
133      <h3>Vehicle Parking Application</h3>
134    </div>
135    <div class="modal-body">
136      <img src="https://thefinancialexpress.com.bd/uploads/1575560371.jpg" alt="Vehicle Parking Application" class="responsive">
137    </div>
138    <div class="modal-footer">
139      <p>
140      Footer
141      </p>
142    </div>
143  </div>
144</div>
145<!-- Modal Button 1 end -->
146
147<!-- Modal Button 2 start -->
148<button id="modal-btn2" class="button">IPDC IMS</button>
149<div id="my-modal2" class="modal">
150  <div class="modal-content">
151    <div class="modal-header">
152      <span class="close">×</span>
153      <h3>Asset Management System</h3>
154    </div>
155    <div class="modal-body">
156      <img src="#" alt="Asset Management System" class="responsive">
157    </div>
158    <div class="modal-footer">
159      ...
160    </div>
161  </div>
162</div>
163<!-- Modal Button 2 end -->
164
165<!-- Modal Button 3 start -->
166<button id="modal-btn3" class="button">Gaming Website</button>
167<div id="my-modal3" class="modal">
168  <div class="modal-content">
169    <div class="modal-header">
170      <span class="close">×</span>
171      <h3>Gaming Website</h3>
172    </div>
173    <div class="modal-body">
174      ...
175    </div>
176    <div class="modal-footer">
177
178    </div>
179  </div>
180</div>
181<!-- Modal Button 3 end -->// Modal
182// Get DOM Elements
183const modals = document.querySelectorAll(".modal");
184const modalBtns = document.querySelectorAll(".button");
185const closeBtns = document.querySelectorAll(".close");
186
187// Events
188modalBtns.forEach((btn, index) =>
189  btn.addEventListener("click", () => openModal(index))
190);
191closeBtns.forEach((btn, index) =>
192  btn.addEventListener("click", () => closeModal(index))
193);
194// for closing when you click outside
195modals.forEach((modal, index) =>
196  modal.addEventListener("click", (e) => {
197   if(e.target === e.currentTarget){
198     closeModal(index);
199   }
200})
201);
202
203// Open
204function openModal(index) {
205  modals[index].style.display = "block";
206}
207
208// Close
209function closeModal(index) {
210  modals[index].style.display = "none";
211}
1// Modal
2// Get DOM Elements
3const modal = document.querySelector('#my-modal');
4const modalBtn = document.querySelectorAll('.button');
5const closeBtn = document.querySelector('.close');
6
7// Events
8modalBtn.forEach(btn => btn.addEventListener('click', openModal));
9closeBtn.addEventListener('click', closeModal);
10window.addEventListener('click', outsideClick);
11
12// Open
13function openModal() {
14  modal.style.display = 'block';
15}
16
17// Close
18function closeModal() {
19  modal.style.display = 'none';
20}
21
22// Close If Outside Click
23function outsideClick(e) {
24  if (e.target == modal) {
25    modal.style.display = 'none';
26  }
27}/* Modal section styling */
28
29:root {
30    --modal-duration: 1s;
31    --modal-color: crimson;
32  }
33  
34  .button {
35    font-family: 'poppins', sans-serif;
36    display: inline-block;
37    background: crimson;
38    color: #fff;
39    font-size: 18px;
40    font-weight: 500;
41    padding: 8px 16px;
42    margin-top: 20px;
43    border-radius: 6px;
44    border: 2px solid crimson;
45    transition: all 0.3s ease;
46  }
47  
48  .button:hover {
49    color: crimson;
50    background: none;
51  }
52  
53  .modal {
54    display: none;
55    position: fixed;
56    z-index: 99999;
57    left: 0;
58    top: 0;
59    height: 100%;
60    width: 100%;
61    overflow: auto;
62    background-color: rgba(0, 0, 0, 0.5);
63  }
64  
65  .modal-content {
66    margin: 50px auto;
67    width: 60%;
68    box-shadow: 0 5px 8px 0 rgba(0, 0, 0, 0.2), 0 7px 20px 0 rgba(0, 0, 0, 0.17);
69    animation-name: modalopen;
70    animation-duration: var(--modal-duration);
71  }
72  
73  .modal-header h2,
74  .modal-footer h3 {
75    margin: 0;
76  }
77  
78  .modal-header {
79    background: var(--modal-color);
80    text-align: center;
81    padding: 10px;
82    color: #fff;
83    border-top-left-radius: 5px;
84    border-top-right-radius: 5px;
85  }
86  
87  .modal-body {
88    padding: 10px 5px 1px 5px;
89    background: #fff;
90  }
91  
92  .modal-footer {
93    background: var(--modal-color);
94    padding: 10px;
95    font-size: 15px;
96    font-weight: lighter;
97    color: #fff;
98    text-align: center;
99    border-bottom-left-radius: 5px;
100    border-bottom-right-radius: 5px;
101  }
102  
103  .close {
104    color: #ccc;
105    float: right;
106    font-size: 30px;
107    color: #fff;
108  }
109  
110  .close:hover,
111  .close:focus {
112    color: #000;
113    text-decoration: none;
114    cursor: pointer;
115  }
116  .responsive {
117    width: 100%;
118    height: auto;
119  }
120  @keyframes modalopen {
121    from {
122      opacity: 0;
123    }
124    to {
125      opacity: 1;
126    }
127  }<!-- Modal Button 1 start -->
128<button id="modal-btn" class="button">Parkit</button>
129<div id="my-modal" class="modal">
130  <div class="modal-content">
131    <div class="modal-header">
132      <span class="close">×</span>
133      <h3>Vehicle Parking Application</h3>
134    </div>
135    <div class="modal-body">
136      <img src="https://thefinancialexpress.com.bd/uploads/1575560371.jpg" alt="Vehicle Parking Application" class="responsive">
137    </div>
138    <div class="modal-footer">
139      <p>
140      Footer
141      </p>
142    </div>
143  </div>
144</div>
145<!-- Modal Button 1 end -->
146
147<!-- Modal Button 2 start -->
148<button id="modal-btn2" class="button">IPDC IMS</button>
149<div id="my-modal2" class="modal">
150  <div class="modal-content">
151    <div class="modal-header">
152      <span class="close">×</span>
153      <h3>Asset Management System</h3>
154    </div>
155    <div class="modal-body">
156      <img src="#" alt="Asset Management System" class="responsive">
157    </div>
158    <div class="modal-footer">
159      ...
160    </div>
161  </div>
162</div>
163<!-- Modal Button 2 end -->
164
165<!-- Modal Button 3 start -->
166<button id="modal-btn3" class="button">Gaming Website</button>
167<div id="my-modal3" class="modal">
168  <div class="modal-content">
169    <div class="modal-header">
170      <span class="close">×</span>
171      <h3>Gaming Website</h3>
172    </div>
173    <div class="modal-body">
174      ...
175    </div>
176    <div class="modal-footer">
177
178    </div>
179  </div>
180</div>
181<!-- Modal Button 3 end -->// Modal
182// Get DOM Elements
183const modals = document.querySelectorAll(".modal");
184const modalBtns = document.querySelectorAll(".button");
185const closeBtns = document.querySelectorAll(".close");
186
187// Events
188modalBtns.forEach((btn, index) =>
189  btn.addEventListener("click", () => openModal(index))
190);
191closeBtns.forEach((btn, index) =>
192  btn.addEventListener("click", () => closeModal(index))
193);
194// for closing when you click outside
195modals.forEach((modal, index) =>
196  modal.addEventListener("click", (e) => {
197   if(e.target === e.currentTarget){
198     closeModal(index);
199   }
200})
201);
202
203// Open
204function openModal(index) {
205  modals[index].style.display = "block";
206}
207
208// Close
209function closeModal(index) {
210  modals[index].style.display = "none";
211}/* Modal section styling */
212
213:root {
214    --modal-duration: 1s;
215    --modal-color: crimson;
216  }
217  
218  .button {
219    font-family: 'poppins', sans-serif;
220    display: inline-block;
221    background: crimson;
222    color: #fff;
223    font-size: 18px;
224    font-weight: 500;
225    padding: 8px 16px;
226    margin-top: 20px;
227    border-radius: 6px;
228    border: 2px solid crimson;
229    transition: all 0.3s ease;
230  }
231  
232  .button:hover {
233    color: crimson;
234    background: none;
235  }
236  
237  .modal {
238    display: none;
239    position: fixed;
240    z-index: 99999;
241    left: 0;
242    top: 0;
243    height: 100%;
244    width: 100%;
245    overflow: auto;
246    background-color: rgba(0, 0, 0, 0.5);
247  }
248  
249  .modal-content {
250    margin: 50px auto;
251    width: 60%;
252    box-shadow: 0 5px 8px 0 rgba(0, 0, 0, 0.2), 0 7px 20px 0 rgba(0, 0, 0, 0.17);
253    animation-name: modalopen;
254    animation-duration: var(--modal-duration);
255  }
256  
257  .modal-header h2,
258  .modal-footer h3 {
259    margin: 0;
260  }
261  
262  .modal-header {
263    background: var(--modal-color);
264    text-align: center;
265    padding: 10px;
266    color: #fff;
267    border-top-left-radius: 5px;
268    border-top-right-radius: 5px;
269  }
270  
271  .modal-body {
272    padding: 10px 5px 1px 5px;
273    background: #fff;
274  }
275  
276  .modal-footer {
277    background: var(--modal-color);
278    padding: 10px;
279    font-size: 15px;
280    font-weight: lighter;
281    color: #fff;
282    text-align: center;
283    border-bottom-left-radius: 5px;
284    border-bottom-right-radius: 5px;
285  }
286  
287  .close {
288    color: #ccc;
289    float: right;
290    font-size: 30px;
291    color: #fff;
292  }
293  
294  .close:hover,
295  .close:focus {
296    color: #000;
297    text-decoration: none;
298    cursor: pointer;
299  }
300  .responsive {
301    width: 100%;
302    height: auto;
303  }
304  @keyframes modalopen {
305    from {
306      opacity: 0;
307    }
308    to {
309      opacity: 1;
310    }
311  }
1// Modal
2// Get DOM Elements
3const modal = document.querySelector('#my-modal');
4const modalBtn = document.querySelectorAll('.button');
5const closeBtn = document.querySelector('.close');
6
7// Events
8modalBtn.forEach(btn => btn.addEventListener('click', openModal));
9closeBtn.addEventListener('click', closeModal);
10window.addEventListener('click', outsideClick);
11
12// Open
13function openModal() {
14  modal.style.display = 'block';
15}
16
17// Close
18function closeModal() {
19  modal.style.display = 'none';
20}
21
22// Close If Outside Click
23function outsideClick(e) {
24  if (e.target == modal) {
25    modal.style.display = 'none';
26  }
27}/* Modal section styling */
28
29:root {
30    --modal-duration: 1s;
31    --modal-color: crimson;
32  }
33  
34  .button {
35    font-family: 'poppins', sans-serif;
36    display: inline-block;
37    background: crimson;
38    color: #fff;
39    font-size: 18px;
40    font-weight: 500;
41    padding: 8px 16px;
42    margin-top: 20px;
43    border-radius: 6px;
44    border: 2px solid crimson;
45    transition: all 0.3s ease;
46  }
47  
48  .button:hover {
49    color: crimson;
50    background: none;
51  }
52  
53  .modal {
54    display: none;
55    position: fixed;
56    z-index: 99999;
57    left: 0;
58    top: 0;
59    height: 100%;
60    width: 100%;
61    overflow: auto;
62    background-color: rgba(0, 0, 0, 0.5);
63  }
64  
65  .modal-content {
66    margin: 50px auto;
67    width: 60%;
68    box-shadow: 0 5px 8px 0 rgba(0, 0, 0, 0.2), 0 7px 20px 0 rgba(0, 0, 0, 0.17);
69    animation-name: modalopen;
70    animation-duration: var(--modal-duration);
71  }
72  
73  .modal-header h2,
74  .modal-footer h3 {
75    margin: 0;
76  }
77  
78  .modal-header {
79    background: var(--modal-color);
80    text-align: center;
81    padding: 10px;
82    color: #fff;
83    border-top-left-radius: 5px;
84    border-top-right-radius: 5px;
85  }
86  
87  .modal-body {
88    padding: 10px 5px 1px 5px;
89    background: #fff;
90  }
91  
92  .modal-footer {
93    background: var(--modal-color);
94    padding: 10px;
95    font-size: 15px;
96    font-weight: lighter;
97    color: #fff;
98    text-align: center;
99    border-bottom-left-radius: 5px;
100    border-bottom-right-radius: 5px;
101  }
102  
103  .close {
104    color: #ccc;
105    float: right;
106    font-size: 30px;
107    color: #fff;
108  }
109  
110  .close:hover,
111  .close:focus {
112    color: #000;
113    text-decoration: none;
114    cursor: pointer;
115  }
116  .responsive {
117    width: 100%;
118    height: auto;
119  }
120  @keyframes modalopen {
121    from {
122      opacity: 0;
123    }
124    to {
125      opacity: 1;
126    }
127  }<!-- Modal Button 1 start -->
128<button id="modal-btn" class="button">Parkit</button>
129<div id="my-modal" class="modal">
130  <div class="modal-content">
131    <div class="modal-header">
132      <span class="close">×</span>
133      <h3>Vehicle Parking Application</h3>
134    </div>
135    <div class="modal-body">
136      <img src="https://thefinancialexpress.com.bd/uploads/1575560371.jpg" alt="Vehicle Parking Application" class="responsive">
137    </div>
138    <div class="modal-footer">
139      <p>
140      Footer
141      </p>
142    </div>
143  </div>
144</div>
145<!-- Modal Button 1 end -->
146
147<!-- Modal Button 2 start -->
148<button id="modal-btn2" class="button">IPDC IMS</button>
149<div id="my-modal2" class="modal">
150  <div class="modal-content">
151    <div class="modal-header">
152      <span class="close">×</span>
153      <h3>Asset Management System</h3>
154    </div>
155    <div class="modal-body">
156      <img src="#" alt="Asset Management System" class="responsive">
157    </div>
158    <div class="modal-footer">
159      ...
160    </div>
161  </div>
162</div>
163<!-- Modal Button 2 end -->
164
165<!-- Modal Button 3 start -->
166<button id="modal-btn3" class="button">Gaming Website</button>
167<div id="my-modal3" class="modal">
168  <div class="modal-content">
169    <div class="modal-header">
170      <span class="close">×</span>
171      <h3>Gaming Website</h3>
172    </div>
173    <div class="modal-body">
174      ...
175    </div>
176    <div class="modal-footer">
177
178    </div>
179  </div>
180</div>
181<!-- Modal Button 3 end -->// Modal
182// Get DOM Elements
183const modals = document.querySelectorAll(".modal");
184const modalBtns = document.querySelectorAll(".button");
185const closeBtns = document.querySelectorAll(".close");
186
187// Events
188modalBtns.forEach((btn, index) =>
189  btn.addEventListener("click", () => openModal(index))
190);
191closeBtns.forEach((btn, index) =>
192  btn.addEventListener("click", () => closeModal(index))
193);
194// for closing when you click outside
195modals.forEach((modal, index) =>
196  modal.addEventListener("click", (e) => {
197   if(e.target === e.currentTarget){
198     closeModal(index);
199   }
200})
201);
202
203// Open
204function openModal(index) {
205  modals[index].style.display = "block";
206}
207
208// Close
209function closeModal(index) {
210  modals[index].style.display = "none";
211}/* Modal section styling */
212
213:root {
214    --modal-duration: 1s;
215    --modal-color: crimson;
216  }
217  
218  .button {
219    font-family: 'poppins', sans-serif;
220    display: inline-block;
221    background: crimson;
222    color: #fff;
223    font-size: 18px;
224    font-weight: 500;
225    padding: 8px 16px;
226    margin-top: 20px;
227    border-radius: 6px;
228    border: 2px solid crimson;
229    transition: all 0.3s ease;
230  }
231  
232  .button:hover {
233    color: crimson;
234    background: none;
235  }
236  
237  .modal {
238    display: none;
239    position: fixed;
240    z-index: 99999;
241    left: 0;
242    top: 0;
243    height: 100%;
244    width: 100%;
245    overflow: auto;
246    background-color: rgba(0, 0, 0, 0.5);
247  }
248  
249  .modal-content {
250    margin: 50px auto;
251    width: 60%;
252    box-shadow: 0 5px 8px 0 rgba(0, 0, 0, 0.2), 0 7px 20px 0 rgba(0, 0, 0, 0.17);
253    animation-name: modalopen;
254    animation-duration: var(--modal-duration);
255  }
256  
257  .modal-header h2,
258  .modal-footer h3 {
259    margin: 0;
260  }
261  
262  .modal-header {
263    background: var(--modal-color);
264    text-align: center;
265    padding: 10px;
266    color: #fff;
267    border-top-left-radius: 5px;
268    border-top-right-radius: 5px;
269  }
270  
271  .modal-body {
272    padding: 10px 5px 1px 5px;
273    background: #fff;
274  }
275  
276  .modal-footer {
277    background: var(--modal-color);
278    padding: 10px;
279    font-size: 15px;
280    font-weight: lighter;
281    color: #fff;
282    text-align: center;
283    border-bottom-left-radius: 5px;
284    border-bottom-right-radius: 5px;
285  }
286  
287  .close {
288    color: #ccc;
289    float: right;
290    font-size: 30px;
291    color: #fff;
292  }
293  
294  .close:hover,
295  .close:focus {
296    color: #000;
297    text-decoration: none;
298    cursor: pointer;
299  }
300  .responsive {
301    width: 100%;
302    height: auto;
303  }
304  @keyframes modalopen {
305    from {
306      opacity: 0;
307    }
308    to {
309      opacity: 1;
310    }
311  }<!-- Modal Button 1 start -->
312<button id="modal-btn" class="button">Parkit</button>
313<div id="my-modal" class="modal">
314  <div class="modal-content">
315    <div class="modal-header">
316      <span class="close">×</span>
317      <h3>Vehicle Parking Application</h3>
318    </div>
319    <div class="modal-body">
320      <img src="https://thefinancialexpress.com.bd/uploads/1575560371.jpg" alt="Vehicle Parking Application" class="responsive">
321    </div>
322    <div class="modal-footer">
323      <p>
324      Footer
325      </p>
326    </div>
327  </div>
328</div>
329<!-- Modal Button 1 end -->
330
331<!-- Modal Button 2 start -->
332<button id="modal-btn2" class="button">IPDC IMS</button>
333<div id="my-modal2" class="modal">
334  <div class="modal-content">
335    <div class="modal-header">
336      <span class="close">×</span>
337      <h3>Asset Management System</h3>
338    </div>
339    <div class="modal-body">
340      <img src="#" alt="Asset Management System" class="responsive">
341    </div>
342    <div class="modal-footer">
343      ...
344    </div>
345  </div>
346</div>
347<!-- Modal Button 2 end -->
348
349<!-- Modal Button 3 start -->
350<button id="modal-btn3" class="button">Gaming Website</button>
351<div id="my-modal3" class="modal">
352  <div class="modal-content">
353    <div class="modal-header">
354      <span class="close">×</span>
355      <h3>Gaming Website</h3>
356    </div>
357    <div class="modal-body">
358      ...
359    </div>
360    <div class="modal-footer">
361
362    </div>
363  </div>
364</div>
365<!-- Modal Button 3 end -->

For the extra part where you want a slider inside your modals, I would suggest you to look at swper.js, a JavaScript library that will allow you to set it up easily.

Source https://stackoverflow.com/questions/71188133

Community Discussions contain sources that include Stack Exchange Network

Tutorials and Learning Resources in Gaming

Share this Page

share link

Get latest updates on Gaming