Online Music Hackathon

First Prize: $5000

Ends on Jul 22:

Learn to Code via Tutorials on

Using MongoDB with python (using PyMongo)
# How to use a MongoDB database with your python repl! (PyMongo) ## Why though? One of the most common uses of is to create discord bots and the most common way to store information like "user warnings" is to store it in files (JSON or even txt). But due to some reasons, does not save the changes made to these files programmatically, so one great alternative would be to use an external DB and as it stands, MongoDB is one of the easiest to learn and most efficient database services out there and `PyMongo` is an amazing library that allows you to store and retrieve and perform other functions with your MongoDB database in a really friendly way. So, that's why. ## Installation Although, if you were doing it locally, you'd need to open up a command line utility and use the following command: - ```shell $ python -m pip install pymongo ``` But makes it even easier allowing you to simply add packages using the package manager or by creating a requirements.txt file! We'll be using `requirements.txt` file for this tutorial. Feel free to check out the package manager as well. If you don't already know about it, all you need to know about the `requirements.txt` file is that it tells the interpreter which packages to install before running the program. And all the packages are named on different lines. For example, if we needed to use `` and `pymongo` and `flask` in a project, the requirements.txt would look something like this: - ``` pymongo flask ``` For now, we only need `pymongo` *(in this tutorial)* so get rid of the other two unless you need them *( for your own app )*. And we're done installing! ------ ### Setting up the Database Goto the [MongoDB website]( and sign-in (or register). Once signed-in, you should see a page as shown below: - ![MongoDB home]( Click on the `Build a Cluster` button which will eventually show you a page as shown below: - ![Create a cluster]( Choose your provider, region, plan and other stuff you might wanna have. If you don't know what something means, search on Google (or DDG) or leave it be. *Be sure to give it a name of your choice, nobody wants their DB to be named* `Cluster0`. Finally, click the `Create Cluster` button. And now you'll need to wait for around 5 - 10 minutes. After the long wait, you'll see the dashboard ![MongoDB Dashboard]( Click on the `Network Access` tab under the `Security` group in the sidebar. And then click the `ADD IP ADDRESS` button. Click on the button saying `Allow access from anywhere` and then click on `Confirm` which will essentially finish this section. Which means - we finally have everything setup and now we can get started with actually using the database in our program!!! ------ ### Setup (inside the code) Head back to the MongoDB Dashboard's `Clusters` tab under the `Atlas` group. And now click on the `CONNECT` button. It will ask you to choose a connection method, for which, you need to choose `Connect Your Application`. In the next, page you'll see two dropdowns: - 1. Driver - `Python` 2. Version - *<Whichever version of python you're using> ( uses latest anyways)* It will now show you your **connection string**. This is a very important thing so be sure to keep it safe. It is usually of the format - ``` mongodb+srv://<username>:<password>@<cluster> ``` Now come back to In the python file where you want to perform DB operations, type the following code ```py import pymongo # Define a new client. client = pymongo.MongoClient("<connection string here>") # Get the database (database name by default is "test") db = client.db_name # OR db = client.test ``` Now that we have our DB, next thing we need to get is a collection. A **collection of documents** in mongodb can be thought of as a *list of dictionaries* in python. By default, a DB doesn't have any collections. To see a list of collections that the database has, the following line of code can be written: - ```py print(db.list_collection_names()) ``` This will print a list of names (as strings) of all the existing collections in the DB. Since, there was no collection by default, we'll create one for us! Creating a new collection is very easy itself. All you need to do is ```py db.create_collection("collection_name") ``` > **NOTE**: *Try to avoid having spaces in collection names, use underscores( _ ) instead.* And now we have a collection where we can store documents which hold our data! *You can also delete an entire collection by using* `drop_collection` *instead of* `create_collection`. ------ ### Inserting data into a collection Now, we get to the serious part i.e. inserting data into a collection. For which we have a few choices. 1. Insert One Here, we just insert a single document in the collection. > **NOTE**: *Python dictionaries are also treated as documents by pymongo.* Example: - ```py # Getting the collection my_collection = db.collection_name # Inserting a sample document. my_collection.insert_one({"test": "document", "hello": "world"}) ``` And that's it! We've successfully inserted a document to our DB! Now let's have a look at the second possibility. 2. Insert Many This is to insert multiple documents to the collection ( Basically a list of dictionaries instead of a single dictionary ). Example: - ```py # Get the collection my_collection = db.collection_name # Define a list to insert documents = [ {"test": "document", "n": 1}, {"hello": "world", "n": 2} ] # Insert multiple documents my_collection.insert_many(documents) ``` And that's how you insert multiple documents at once. It will not create 1 new document and insert the list as it's value, instead, it will create new documents for each of the dicts inside that list! And those were the two ways of inserting data. ------ ### Searching for documents in a collection Now that we've inserted some stuff to a collection, we can fetch and view it whenever we want. This can also be done in two ways: - 1. Find One In this method, pymongo will return the first element it finds satisfying the *query*. The general syntax for this is: - ```py db.collection_name.find_one(query) ``` Example: - ```py # Get the collection my_collection = db.collection_name # Find the document x = my_collection.find_one({"field": "value"}) ``` This example will search for a document in the collection `collection_name` whose `field` field's value is `value`. 2. Find In this method, pymongo will return **all** the elements it finds satisfying the *query*. The general syntax for this is: - ```py db.collection_name.find(query) ``` Example: - ```py # Get the collection my_collection = db.collection_name # Find the document x = my_collection.find({"field": "value"}) ``` This example will search for **all** documents in the collection `collection_name` whose `field` field's value is `value` and return a object of the `Cursor` class which can be treated as a list of the resulting documents. And these were the two ways to search for documents that are there in a collection. ------ ### Deleting documents And now, we have some documents that we can get rid of (delete them of course). Deleting can also be done in two ways: - 1. Delete One For deleting just one document. Pretty similar to the `find_one` function, we need to provide a query object and then it will delete the very first item it finds that satisfies the query. Example: - ```python # Get the collection my_collection = db.collection_name # Delete the document my_collection.delete_one({"field": "value"}) ``` This will delete the **first** document it finds which has a field named `field` whose value is set to `value`. 2. Delete Many For deleting all similar documents. Pretty similar to the `find` function, we need to provide a query object and then it will delete the very first item it finds that satisfies the query. Example: - ```python # Get the collection my_collection = db.collection_name # Delete the document my_collection.delete_many({"field": "value"}) ``` This will delete **all** the documents it finds which has a field named `field` whose value is set to `value`. ------ ### Replacing existing documents Since we have some documents in our DB, sometimes we might need to delete one and add another document simultaneously. Instead of first deleting and then inserting a new document, we can simply use the `replace` function. This can be achieved by using the `replace_one` method of the collections which takes two parameters - the `query` which will allow it to find the existing document to be replaced **and** the `replacement` which will be inserted. Example: - ```python # Get the collection my_collection = db.collection_name # Replace a document my_collection.replace_one( {"some_field": "some_value"}, {"field_one": "value_one", "field_two": "value_two"} ) ``` This will first search for a document that has a field named `some_field` whose value is set to `some_value` and then replace it with the new document we provided. If it is unable to find the document to be replaced, it will throw an error. The error can be prevented if we pass the optional `upsert` parameter and set it's value to `True` as given below: - `my_collection.replace_one(query, new_document, upsert=True)` This will simply insert the `new_document` if the query did not return any results instead of throwing an error. ------ ### Some resources to learn more - [MongoDB documentation]( - [PyMongo Official Tutorial]( - [PyMongo Examples]( - [PyMongo API Documentation]( ------ # The End If you have any questions, let me know via the comments. If you found this tutorial to be helpful, please upvote. Thanks for reading it to the end!
posted by TheDrone7 (516) 4 days ago
Getting Started with HTML in 10 minutes.
This is a super easy guide to show you how to work with HTML and create your first pages in 10 minutes! **Disclaimer**: This tutorial will only cover the basic of HTML, you won't be able to style or make your professional website with this tutorial alone. But if you are a beginner who want to get started with Web Dev that this will be the perfect tutorial for you to get up and running with HTML. Ok, so let get started with everything you need to know about HTML. Also I will link to good resources that you can use to learn HTML deeper and also search what you want to do in HTML. **So what the heck is HTML?**: HTML stands for Hypertext Markup Language. Long name for a single meaning: The skeleton of Web pages. **ok? So what the heck is the skeleton of web pages?**: Well if you don't know, every website you visit is made of 3 technologies: HTML, Javascript and CSS. You can think about a webpage like this: It like a human body, wiith CSS as the skin, javascript at the brain and HTML as the Skeleton. HTML made up element of the page (like buttons, link, etc.) and CSS make it colorful and good-looking. And Javascript is the brain, so like when you comment on a youtube video, the javascript handle that part and send it to the web server which you don't need to care about it for now. (there is other technologies to create web pages like php, but for now the most popular is still HTML. **ok ok, i understand now, now what do I do to get started with html?**: As I told you before, a website is created with lots and lots of elements, so is HTML. There are lots of HTML *tags* that represent as the element for the webpage. But don't worry, you will only need to learn about 10 of them to create a really-good static website. And those I will explain right NOW! To set up your development environment you will need a text editor and a web browser (for text editor I recommend Visual Studio Code, and for Web Browser Firefox or Chrome will do). But if you don't want to setup stuff right now locally on your computer you can go ahead and use to set it up for you. Just click on that 'new repl' button on the nav bar and you will see this. ![image]( Just go ahead and put 'Html' in to the bar 'Search for a language , e.g C++' and select HTML, CSS, JS. ![image]( then just name your repl. (you can also put your Github repo in which you don't need to care right now, and also describe you repl which is extra but you can do it if you want to) ![image]( After fill them in you can click 'Create repl'. ![image]( You will be directed to that page but don't worry. Also you can see a file named `index.html` created for you and there is weird text inside of that file, don't worry I will explain it to ya. (there is also a css file named style.css and a js file named script.js, you don't need to care about any of those for now) The *weird text* in the `index.html` is this: ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title></title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <script src="script.js"></script> </body> </html> ``` Ok let do this quickly, `<!DOCTYPE html>` is basically just telling the web browser this is a HTML5 Document. Every website that use HTML5 will have that at the start of the document. `<head> and </head> or is it called a `head` tag. It just basiclly where you put your meta and website title and the link to css in.` Ok now we gonna slow down a little, a `tag` is basically the a element on a website like a button or a link. The open tag is like this <body> and the close tag is like the same as the open tag but with the `/` character next to the name of the tag. Like this: `</body>. Talking about the `body` tag, the body tag is a container of everything that is visible or not on a web page. The `script` tag is just a tag that link your js file with your html file. And the `html` tag is a tag that you put everything HTML inside. It just like a start of your webpage. And this is quite important to know that a file named `index.html` is your site's homepage, when open up a website the browser will look for this file name `index.html`. So that is why you would want to keep that file in the root directory. So let mess with the file a little, I want you to add this `<h1>Your message here</h1>` inside the `index.html` file inside the `body` tag right before the `<script>` tag. You should have something like this: ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title></title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <h1>Your message here</h1> <script src="script.js"></script> </body> </html> ``` After that you can click on the green 'Run' button. ![image]( And now you will be able to see your webpage next to the code editor ![image]( And this is an neat feature about, it automatically host your website! You can access the page that you create right in that code editor or through a domain. You can get your own here: ![image]( Yeah, lets talk a little bit more about the <h1> tag, well the <h1> tag is in its own family of headers tag. The `h` means header and 1 means the size of it. And 1 is the biggest of all header tag, and the size is from 1 to 6. That means there is 6 header tags like <h1>, <h2>, <h3>,... etc. You can mess with it yourself by using the same bit of code I give you earlier and copy and paste and change the number. I won't show you the code cause I want you to be able to mess with stuff your self, but I will give you the result. ![image]( And don't worry, you can change the text size later if you want to with CSS, we will do that in a later in another tutorial. But right now you don't really need to care about that :D. Ok so the important tag to remember is the paragraph tag. (`<p>`) Let go ahead and mess with the code right now. The paragraph tag do what it name tell us. Put paragraph in to the page. So let add this bit of code to our website: `<p>AHAHA I know how to put paragraph to my website with the <p> tag!</p> ` The result will looks like this: ![image]( Ok so you might ask how would I add links to my page. And to that I say you can go ahead and put links to your website with the `<a>` tag. Now you can go ahead and just put this to your website: `<a href="">Link to awesome page</a>` The result of adding it: ![image]( You may notice the href="" thingy, don't worry, I will explain it right now. That href thingy is one of lots of attribute. An attribute is a way to provide additional info, in this case is the link to the website. An attribute sits inside the opening tag. A tag can contain 1 or more attributes at a time. Don't worry, we will cover more attribute later! Ok lets move on to some more tags cause this is FUN! How do you add buttons to your web page? Well you do that with the <button> tag. Add this bit to your page and see the different: `<button>Click me plz</button>`. The result: ![image]( You also can add images to your website this the <img> tag `<img src="" alt=" logo">` Just add that bit to your file and see the result. The `src` attribute (or the source attribute) is like a url to point to your file, the file can be stored locally or on other websites. And `alt` is alternative text, it just a little text that pops up when you hover through the image. The result you should get after putting that `<img>` tag in. ![image]( Ok last thing you would want to know is how to create lists with HTML. This require 2 tags but everything is quite simple to do so here is the details. You can create 2 types of lists, ordered list (list with numbers) or unordered list ( list with dots). And the tags for it are <ol> for ordered and <ul> for unordered. To make a list we also need list items, the tag for it are <li>. I think I am talking to much and it super simple so here is the example. for unordered list: ``` <ul> <li></li> <li>Repl</li> <li>it</li> </ul> ``` and for ordered list ``` <ol> <li></li> <li>Repl</li> <li>it</li> </ol> ``` and see the results ![image]( Ok so that is the end for this tutorial. Thanks to you for reading till the end of it. And yeah, after this you have been able to do easy html stuff. Nothing too impressive, but one step of a time. Resources I recommend: Thanks again. You can check out the repl I created for this tutorial: . If you like this you can give me an upvote. Thanks again! Bye! Waddle On! - Josh
posted by joshhies (7) 22 hours ago
How basic SQL injection works - with a demo
In this tutorial, we are going to be targeting my 'vulnerable cloud storage' program ( The way it works is users can store and read data, with authentication. Usernames and passwords are stored in a sqlite3 database. For this demo, the user 'test' has been added with a password of 'test' and has 4 files containing irrelevant data. The first example of SQL injection can be seen on line 13. In the request, you are supposed to supply a username and password. However, as you can see, this is not a regular password. We gave the password "x' OR '1'='1" with the username "test". When inserted into the SQL command on the server, the command will look like this: SELECT ID FROM USERS WHERE USERNAME='test' AND PASSWORD='x' OR '1'='1' What we have just done is taken advantage of poorly written code to make the server execute commands that were not intended. The simple mistake I (purposefully) made in my code is using %s to format a string. In sqlite3, there is a way to do this correctly by not using any quotation marks and having question marks in place of data and passing a tuple with the data in the arguments. To learn more about input sanitization and good practice, look here: Anyway, this script uses SQL injection to bypass all authentication and replaces all the user's data with random characters. SQL injection is the most common vulnerability found in websites. It is an easy mistake to allow and can have devastating results like someone taking complete access of your server or looking at confidential information (eg passwords).
posted by MarcusWeinberger (21) 11 days ago
🌚🕶 How to Enable Site-Wide Dark Theme 🕶🌚
# Site-Wide Dark Theme Do you like being blinded while browsing Well me neither! ![Repl talk on dark theme]( *** First, you might not have the editor dark theme enabled, so make sure you enable that. 1. Click the settings button at the left of the editor screen. ![Settings Button]( 2. Find the theme dropdown, and select *dark* ![theme dark]( *** Now that you have the editor dark theme enabled, we will enable the site-wide dark theme. 1. Download Tampermonkey for [Chrome]( or [Firefox]( 2. Choose a theme from [the list of themes]( or [create your own]( 3. Click the `install` button. 4. Upvote and post a comment on this tutorial. 5. Profit!
posted by mat1 (2255) 3 months ago
🚀 A Starter Guide to Pygame 📀
# 🚀 A Starter Guide to Pygame 📀 Pygame is an open-source library for making graphical applications with Python. Learn more about it on the official [website]( This tutorial is intended to help you setup a very basic Pygame interface. It's for Python beginners or people who want to quickly bootstrap a Pygame project. Find more about's GFX public beta announcement [here]( So let's get started! We're going to be building a simple screen saver. The final result will look like the following ![programProgress4]( ## Starting out When creating a new project, be sure to select "PyGame" when creating a project. ![image]( Now we're ready to start writing some code! ## Painting the Screen Red 🎨 First, we're importing Pygame and initializing all the imported pygame modules with [`pygame.init()`]( Second, we're declaring `width` and `height` variables that represent the size of the screen. Third, we're setting `backgroundColor` to a tuple of 3 elements that represent the RGB numbers. Fourth, `screen` is a display Surface, or an initialized window or screen for display with the [`set_mode()`]( method. Lastly, in the infinite loop, we're filling the screen to the `backGroundColor` and updatiang the display Surface to the screen. In other words [`pygame.display.flip()`]( "refreshes" the screen with changes you made to the grahpics. ```python import pygame pygame.init() width, height = 800, 600 backgroundColor = 255, 0, 0 screen = pygame.display.set_mode((width, height)) while True: screen.fill(backgroundColor) pygame.display.flip() ``` So, we get a red background! ![programProgress1]( ## Adding the DVD Right before you while loop, import an image of your DVD. Feel free to use the same image I used, in the repl below. ```python dvdLogo = pygame.image.load("dvd-logo-white.png") ``` Then, create a rectangle from the Surface, or from the image you just loaded with [`get_rect()`]( ```python dvdLogoRect = dvdLogo.get_rect() ``` Now, inside of the `while` loop (after filling the background color), "map" the imported image to the `dvdLogoRect` rectangle using the [`blit()`]( method. That way, the image stays inside of the invisible `dvdLogoRect` rectangle. ```python screen.blit(dvdLogo, dvdLogoRect) ``` Now, we get a DVD! ![programProgress2]( ## Moving the DVD Logo To move the DVD logo, simply use `move()` by a speed: ```python dvdLogoRect = dvdLogoRect.move(dvdLogoSpeed) ``` Make sure you also declare and initialie dvdLogoSpeed at the top of the file. `dvdLogoSpeed[0]` represents the speed in the `x` direction. ```python dvdLogoSpeed = [1, 1] ``` Finally, I added a `time.sleep(10 / 1000)` so the logo moves slower. So my code ended up looking like ![programProgress3]( The DVD logo *will* move off the screen because there is no bouncing. To implement a check for bouncing, add the following: ```python if dvdLogoRect.left < 0 or dvdLogoRect.right > width: dvdLogoSpeed[0] = -dvdLogoSpeed[0] if < 0 or dvdLogoRect.bottom > height: dvdLogoSpeed[1] = -dvdLogoSpeed[1] ``` The `.left` and `.right` properties don't seem to be [documented](, but it's implied that `.left` measures the distance from the left part of the `dvdLogoRect` Rect (rectangle) to the left part of the `screen.` And so on and so fourth for `.right`, `.top`, and `.bottom`. Here is the final result ![programProgress4]( Now let me know when the logo hits the corner!
posted by eankeen (529) 4 months ago
How I solved the Secret Announcement
# A Detailed Solution to Secret Announcement ### Background: You are most likely busy creating a game for the game jam and you probably know that an announcement came 2 weeks before the jam as a secret message using [steganography]( I was one of those chaps who actually solved the secret, but didn't do anything. The challenge can be found [here]( There was a solution, but that was not very explanatory.This post will explain how ~I~ solved the announcement. This post assumes basic knowledge of the binary system. *** The first thing I did after seeing the newsletter was to read up on steganography.I found this on wikipedia: >Concealing messages within the lowest bits of noisy images or sound files Interesting... ## Reverse Engineering: Then, I looked at the code.Apart from imports and loops to go through all pixels,this was the crux of the code: ```py secret_red = secret_pix[0] >> shift_amt secret_green = secret_pix[1] >> shift_amt secret_blue = secret_pix[2] >> shift_amt public_red = public_pix[0] & all_except_LSB_mask public_green = public_pix[1] & all_except_LSB_mask public_blue = public_pix[2] & all_except_LSB_mask final = ( secret_red + public_red, secret_green + public_green, secret_blue + public_blue ) ``` `>>` and `&` are [binary operators]( was 7 and all_except_LSB_mask was 254 What does the >> operator do? It shifts the bits towards towards right.For example: `11100010101 >> 6` outputs `11100` i.e. the last 6 bits are removed. In our case, all the 8 bit data(because 255 is the maximum in RGB color format and 255 is 8 bits) is shifted by 7 bits so that would leave only the highest bit as one or zero. This would also imply that anything greater than 127.5 (255 / 2) would leave 1 while anything lesser would leave zero. `10101010 >> 7 == 1` `01010000 >> 7 == 0` So that's our secret pixel Then, we see the `&` operator with all_except_LSB_mask as 254.The & operator is called bitwise and. Basically, it returns one only if both expressions are one.Like `1&1 == 1` `1&0 == 0` `0&0 == 0` An important property of the & operator is that `something & all 1s = something` another one is that `something & 0 = 0` `10100100`&`11111111`==`10100100` 254 in binary is `11111110` So,all the bits except the last one would remain intact `10011011 & 11111110 ==10011010` So,this would turn all public pixels into even numbers as the last bit is 2**0=1 and if it is absent, the number must be even. The final pixel is secret_pix + public_pix.We know that public pix is either 0 or 1.Since the last bit of public pix is always zero,The last bit of final pixel must reflect the secret image. So here's my code: ```py from PIL import Image'out.png').convert('RGB')'RGB',(600,600)) for x in range(600): for y in range(600): secret.putpixel((x,y),tuple((i%2)*255 for i in public.getpixel((x,y))))'secret.png') ``` All the juicy stuff is in one line:`(i%2)*255 for i in public.getpixel((x,y)` What this does is: + take the public pixel + compute modulo two (returns 1 if odd and 0 if even) + multiply that by 255 because 00000001 or 00000000 show no visible difference but 11111111 and 00000000 do + put this in the secret image, pixel by pixel And Heres my output: ![secret]( waow indeed
posted by Lord_Poseidon (109) 4 months ago
Learning Web Development w/ Python Part 1
# Learning Web Development with Python and Django ## Part 1 *If you already know a bit about web development, then check out [Gareth Dwyer's Tutorial]( This tutorial is intended for beginners, and takes things a bit more slowly.* ## Welcome! In this tutorial, I'm going to be teaching you how you can use the `Django` web framework to make your own web apps with Python. ### Prerequisites For this tutorial, you should have a decent understanding of Python. Knowing some `HTML` and `CSS` helps. ## The Client and the Server Before we can start coding our own web app, we need to know a little of how the internet actually works - clients and servers. **Servers** Servers are basically the computers that 'run the websites'. Each website has its own server (in reality, large websites have lots of servers). Each server has its own **domain name**, e.g. or **Clients** Clients are computers that connect to servers - i.e. people who visit the website. ### How do Clients connect to Servers? This depends largely on what **protocol** is being used. The most common protocols are `http` (hyper-text transfer protocol) and `https` (secure hyper-text transfer protocol). On a very basic level, what happens is: * The client sends out a message saying "I want to see this page on this website, my address is xxxxx". * The message arrives at the server. * The server checks which page to send and then sends it back in the form of `html` (and often other filetypes, but we will be focusing on html here). * The browser of the client interprets the html to give a visual output. ### How does this apply to Django? When we use Django, we're basically writing our own server. Django takes care of all the sending and stuff, all we have to do is add our pages, and put them in a place Django can find them. ------------------------------------------------------------------------------------------ By now, you'll be itching to write some code, so lets get started! When you create a Django project on repl, there is already some code in there, so I have made a [basic template]( which has the bare minimum. Open the template, and click the `fork` button at the top to make your own copy. ![image]( You can now rename it to `hello-world` (or something else if you prefer). ## Creating your very first app Before we make any changes, you can click the square icon in the top right of the view panel: ![image]( This will open the page in a new tab so you can see the fullscreen version of it. You should get a page like this: ![image]( This is just the standard Django page, which appears when you haven't written any code yet. ### Creating our first web page When you type in a URL (such as on a browser, there are three parts: * **Protocol** - almost always `http` or `https`. * **Domain name** - looks like ``. * **Page name** - looks like `languages/python`, and is after the domain name. With our project, we don't need to worry about the domain, because `repl` creates one for us to use (in the form `<repl-name>--<username>`). However, we will need to think about our page names. #### URLs and Views There are 2 parts to displaying a page on Django - the URL, and the `view`. The `view` is what the client will see when they visit the page. ##### Writing our view For this first project, we will be using **function-based views**. This means that each view is a Python `function`. Navigate to the `` file, and add the following code: ```python from django.http import HttpResponse def homePageView(request): html = "Hello, World!" return HttpResponse(html) ``` So, what does this code do? `Line 1` imports HttpResponse , which we will need in order to return the html in the correct format. On `Lines 3-5` we create our view. * `Line 3` - this is our function, called `homePageView`, because it will be the homepage of our website. It takes `request` as an argument - for more advanced projects, you will use `request` in your function, but we don't need to worry about it right now. `request` is a request **object**, that carries information about the request for the page. * `Line 4` - this is the html for the website. This is extremely simple hmtl - it doesn't have any tags, all it has is the text `"Hello, World!"`. * `Line 5` - this is where we return the html, in a form Django can understand (`HttpResponse`) If we run this code, we get...nothing! The reason for this is that Django doesn't know what to do with the view. ##### Adding the URL (Page name) We need to tell Django where the view should be displayed. Navigate to the `` file, and add the following: ```python from .views import homePageView ``` Then change `urlpatterns` to: ```python urlpatterns = [ url(r'^admin/',, url('',homePageView,name="home"), ] ``` Before we analyse the code, go to your website (in the other tab), and refresh. You'll see we got we wanted! ![image]( So how did this happen? Let's look at the code. ```python from .views import homePageView ``` This imports our `homePageView` function from the `` file. The period `.` at the start tells Django to open it from the current directory (`main`). This is needed because the code will be run from somewhere else, so Django could get confused and try to import it from a different folder. In `urlpatterns` we added ```python url('',homePageView,name="home"), ``` (Note that `''` is 2 single-quotes, not 1 double quote) This tells Django to treat it as a url. There are 3 arguments given: * The first (`''`) is the page name, which I described earlier. If it was something like `about/aboutme` then the page would be located at (replacing `` with the domain name, obviously). However, it is just `''` so the view will be located at just * The second is our view that we created in `` and imported earlier. * The third is the *name* we give our page. It is not essential, but will come in useful later when we want to keep track of all the pages. ------------------------------------------------------------------------------------- ### Congratulations! You've made your first web page with Django! It may seem a bit convoluted right now, but this format is very helpful when we make bigger web applications and have many files. #### That concludes Part 1 In [Part 2](, we will be looking at the more powerful `class-based views`, as well as multiple pages in out project. Please upvote if you found this tutorial helpful, it supports me and lets me know that you want more! If you have any questions, post in the comments and I (or someone else) will answer them.
posted by ArchieMaclean (523) 3 months ago
Making a Phaser Game with HTML5 and JavaScript
# Making a Phaser Game with HTML5 and JavaScript Hi guys! Everybody likes to make games, right? And everybody has their own way of doing it. In this tutorial I wanted to share a very simple, yet effective way to make games in your browser! It should be easy enough for most people with javascript knowledge to follow along and, if you want to investigate further, there are endless possibilities out there! ![image]( ### Phaser As Phaser describes itself it is a fast, free and fun open source framework for Canvas and WebGL powered browser games. And it really is! It is super simple to use and is quite easy to set up. No super extensive javascript knowledge is necessary and the process of making games is fun and rewarding. It also comes with tons of extra features that you may need in some more complicated games so while it caters to starters as well, it also does not lack depth if you want to look further. Anything from image editing to complex game mechanic mathematics is possible. ##### Sites to use The official Phaser website is [here]( Additionally, because we are going to use Phaser 3, the latest release, the examples on the site will most probably not work for v3. If you want some examples of v3 features the link is [here]( You should not need the examples during this tutorial but if you want to learn further that is where you start. Google works as well but be careful about which version is being discussed. Version 3 is relatively new and v2 has loads more documentation and examples and tutorials on it. However, I would recommend learning v3 because it is generally better in many ways and the knowledge will last you longer and it will be more current. #### Prerequisites (what you need before doing this tutorial) The pre-requisites are: * A basic understanding of HTML, CSS and Javascript. * Knowledge in Javascript about the `this` keyword. * Some time and patience. * 3 rolls of duct tape. * Lots of cardboard * Creativity ### Let's Get Started! The project that I will be using for this tutorial is [here]( and the website for it if you just wanna play the game is [here]( If you ever get stumped on a step that I take in this tutorial just check the repl and see how the code looks in it. If all else fails a bit of copy-paste will solve your issues. Make a new HTML/CSS/JS repl and follow along... So, first of all we need to include the Phaser script into our website. The only piece of HTML in this tutorial will be the following:`<script src="//[email protected]/dist/phaser.min.js"></script>`Just paste this into your project's HTML file right above your script tag that links to `script.js`. The order is important and if you get it wrong nothing will work. If your project is not working you should definitely have a look at the order of your scripts. The Phaser script should be first. With that out of the way, let's get into making our game! The first bit of code is a standard template that is in most simple Phaser games (more advanced ones may use a slightly different structure but the idea is the same). The code looks like this: ```javascript let config = { type: Phaser.AUTO, width: 800, height: 500, physics: { default: 'arcade', arcade: { debug: false } }, scene: { preload: preload, create: create, update: update } }; const game = new Phaser.Game(config); function preload(){ } function create(){ } function update(){ } ``` While this may look alien to you, don't stress. To follow along this tutorial you don't need to understand what everything does exactly. The main things you should pay attention to are: * The three functions at the bottom `preload`, `create` and `update`. These we will fill in with the game's code. * The `width` and `height` properties. You can set these to anything you like, I did not make it `window.innerWidth` and `window.innerHeight` because scaling can quickly become messy. It is easier to make it a fixed width for everybody. So now if you run your repl you should see a black square in your browser window. Success! If you do not, make sure you have the Phaser script in the right place and that you have the code in your `script.js` exactly like above. You should also get a message in the console, something like: ```%c %c %c %c %c Phaser v3.14.0 (WebGL | Web Audio) %c background: #ff0000 background: #ffff00 background: #00ff00 background: #00ffff color: #ffffff; background: #000000 background: #fff``` This may look awful in the console but if you open it in a new tab and check the console it should be a colorful banner. ### Loading Assets The `preload` function that we are going to use for this section is where you load your assets. If you want some images or audio (Phaser does that as well) in your game you first have to load it here. This way you are loading all the required assets immediately and you can use them throughout the game. I have made some assets for this tutorial so that you do not need to find or make some yourself. Go [here]( and click download like so to get the files: ![image]( If you get the files in a `.zip` folder just unzip them and drop them into your repl. Once you have them in your repl we have to load them into our game. The following code in the `preload` function will do the trick: ```javascript this.load.atlas("player", "spritesheet.png", "sprites.json"); this.load.image("platform", "platform.png"); this.load.image("spike", "spike.png"); this.load.image("coin", "coin.png"); ``` The first parameter in all of the functions is the "key" for the image. This key you would use when you need to add the image into the game. You can put it as whatever you want but make sure it is descriptive of the image in some way. I suggest you keep them the same as mine so that later code in my tutorial works for you. The second parameter is the path to the image. Because I put the assets in the same folder as the html and js files the path is just the name of the image. If you put your assets in another folder the file path string would look like `"folder_name/file_name.png"`. You may also have noticed that the first command is a bit different. It loads an __atlas__ and not an image. An atlas is a collection of images put together to make a larger image accompanied by a file that states where all the smaller images are. If you open the file `sprites.json` in the assets I gave you you should see that it contains a bunch of named objects that have x, y, width and height properties among others. Each object is an image inside the larger image. In this tutorial we will use the atlas for the player animations. All of the frames for the player (in our case only three) are in the `spritesheet.png` file. The third parameter for the atlas is the path to the `.json` file which we looked at already. If you now run the current code the screen should remain black and no errors should be in the console. If you see a web audio warning that is fine, it does not mean anything important. It's just chrome messing with you. ### Adding Objects to Our Game The `create` function is where the building of our game happens. It is run right after `preload` and is run only once. If you want to add an object to the game, this is where you do it. If you want to repeatedly create some object. Make a function (read below) that creates the object and run that as may times as you like. So we now have loaded some images but we need to have something happen on the screen. Let's add a function in the `create` function that will spawn our player in. Add this code to the `create`function: ```javascript this.spawnPlayer = ()=>{ this.player = this.physics.add.sprite(400, 250, "player", "sprite_0"); } this.spawnPlayer(); ``` I put this in a seperate function so that we can spawn the player multiple times. We are saving the player to __`this`__ which is the Phaser game object so that we can access it from anywhere. The function itself creates a sprite (image/object) that is in the Phaser physics system. The parameters are: 1. X position 2. Y position 3. Image key 4. (optional) If the image is an atlas, which frame in the atlas. There may be a few more parameters but those are not important for this tutorial. The way we find out which frame is which in the atlas is by looking at the `sprites.json` file. Find an object and look at its x and y properties. For example `sprite_2` has the following object: ```javascript "sprite_2":{"frame":{"x":0,"y":0,"w":48,"h":64}... ``` We can see that the x and y coordinates of the frame are `0, 0`. This means that it will be in the top left corner. If you look at the top left corner of the `spritesheet.png` image you will see which frame is `sprite_2`. Try changing the last parameter in the add function to be `sprite_2`. You will see that it has changed. ##### Adding a Background If the only background color we could have would be black Phaser would look really bad. Luckily enough, Phaser has an easy way to add a background to our game. Just add this code to the top of your `create` function above the `spawnPlayer` function: ```javascript this.cameras.main.setBackgroundColor('#ffffff'); ``` This sets the background color for our main camera to white. If you have not used hex color codes before don't worry about it, just know that `#ffffff` is white. The only problem with that is that now we can't see where our canvas window starts and ends. We can fix this with a little CSS: ```css canvas{ border: 1px solid black; } ``` Now if you run your code it should look something like this: ![image]( You can see we have our little character in the middle of the screen. The background is now white. You may have noticed that the character is not offset to a side even though we put in the coordinates for the center of the screen. This is because Phaser draws images from their center. This makes it easier to center images. Another simple thing we can add to the game is a camera that follows the player. This is quite easy to do in Phaser: ```javascript this.spawnPlayer = ()=>{ this.player = this.physics.add.sprite(400, 250, "player", "sprite_0"); this.cameras.main.startFollow(this.player); }; this.spawnPlayer(); ``` The function should be quite self-explanatory and if you run it you should see no change for now. As long as you do not get any errors you are fine. ### Adding Platforms Before we start I wanted to show you the most basic way to add an image to the game. The method used above has a very specific use case (only for sprites). Here is a more general use way of doing it: ```javascript // This goes beneath the spawnPlayer function call this.platform = this.add.image(404, 302, "platform"); ``` This is good for some simple use cases like for example a logo image in your title screen. However it has its shortcomings. Imagine you want to create a map of these platforms. You would have to add `platform1` `platform2` and so on... It would be a nightmare. Let's not get started on collisions. So by now you can see why we are not going to use this to add our platforms. Instead we will have a group. Defining a new group is easy. Remove the above code and add this instead. ```javascript this.platforms = this.physics.add.staticGroup(); ``` Currently we are just defining a new static (non-moving) group and assigning it to the variable `this.platforms`. If you run this now the platform image will disappear. That is because we need to add some platforms to the group. This can be done simply like this: ```javascript //Below the spawnPlayer function this.platforms = this.physics.add.staticGroup(); this.platforms.create(404, 302, "platform"); ``` There we go! Now we have our platform back! But what is the benefit? In a moment when we deal with collisions you will see why. For now we will leave the platforms and get back to them later. ### Keyboard Inputs As you have probably gathered by now, Phaser has made its own version of everything you may need when developing games. Keyboard inputs are no exception. Phaser even supports many ways to do keyboard inputs. We are going to do the shortest and simplest. We are going to have a bunch of variables, one for each key. And we will check each frame if any of the keys are pressed and set velocities accordingly. The code for the keyboard variables in the `create` function looks like this: ```javascript this.key_W = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.W); this.key_A = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.A); this.key_D = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.D); ``` You do not need to understand this, just get the idea of what is happening. When a player presses a key the variable associated with that key will have `isDown` set to `true`. This makes adding keybinds really easy. Now for the rest of this section we are using the `update` function. `update` is your game loop. This function is run very fast repeatedly all throughout your game. This is where you would handle things like movement and other stuff you would want to check every frame. If you would be coding your own physics this would be where you do it. In the `update` function now let's check if the W key is pressed: ```javascript if(this.key_W.isDown){ this.player.setVelocityY(-50); }else{ this.player.setVelocityY(0); } ``` Instead of incrementing or decrementing the Y property of the player we set its velocity. We do this because it sets a velocity within Phaser which has some benefits. First of all Phaser object velocities take into account the frame rate. If every frame you increase the position X of a player, the higher the frame rate the faster the player moves. However, Phaser counteracts this. We do not need to know how, just that no matter the frame rate the player will always move at the same speed. The value we put into `setVelocityY` is the amount of pixels we want it to move in one second. If you run this now you will see that is you press the W key your character will move up. Success! Now let's add keybinds for A and D. This is only a few more lines of code: ```javascript if(this.key_A.isDown){ this.player.setVelocityX(-50); }else if(this.key_D.isDown){ this.player.setVelocityX(50); }else{ this.player.setVelocityX(0); } ``` We have this in an if/else if statement because we don't want to head left and right at the same time. We can only go in one direction or the other. And that's it! We now have linked up our keyboard keys to our Phaser game! Now it's time to deal with physics. ### Game Physics Phaser also has its own physics engine. In fact it has three but we will only use the most basic one for this tutorial. Just simple square and square collisions. Before we can do collisions, how about we add some gravity. We only need it on the player so it would look like this: ```javascript this.spawnPlayer = ()=>{ this.player = this.physics.add.sprite(400, 250, "player", "sprite_0"); this.player.body.setGravityY(800); this.cameras.main.startFollow(this.player); }; ``` Now if you run your game you will see that the player drops. But he is dropping very slowly. Why so? This is because each frame we are setting his velocity to 0 if the W key is not pressed. Previously that was needed so that he would not just fly away but now we need to remove that bit: ```javascript //In the update function if(this.key_W.isDown){ this.player.setVelocityY(-50); }/*else{ this.player.setVelocityY(0); } NO LONGER NEEDED*/ ``` Now if you run it the player falls a bit faster. You can still fly with W but we will change that in a second. #### Collisions Now that we have gotten gravity mostly out of the way let's make the player collide with the platform that we have. We can do this with one simple line of code. Add this to your `spawnPlayer` function: ```javascript this.physics.add.collider(this.player, this.platforms); ``` That's it. Just one line of code does everything. But if you run this now it will not work. The player will fall right through. And this is actually for a really stupid reason. We are running this code before we add the platforms. All you have to do is move the `spawnPlayer` function __call__ (not the function itself) below where we add the platforms. And Viola! We have the player not falling through the platform. There are some small problems that we should address before moving on. First of all, When we press W we can fly endlessly. That defeats the point of the game. To prevent this all we need to do is to only let us jump when we are on the ground. This is easy to do: ```javascript if(this.key_W.isDown && this.player.body.touching.down)... ``` When the key W is down and the player's body is touching a platform with its bottom it will jump. If you run this now you will see that the player now makes many little jumps if you press W. To make the jumps larger we have to increase the `setVelocitY`: ```javascript if(this.key_W.isDown && this.player.body.touching.down){ this.player.setVelocityY(-550); } ``` And also while we are at it we can make the left/right movement a bit faster: ```javascript if(this.key_A.isDown){ this.player.setVelocityX(-150); }else if(this.key_D.isDown){ this.player.setVelocityX(150); }else{ this.player.setVelocityX(0); } ``` So there we have it! A running and jumping player! Now let's give him a map to run around in. #### Map Building Phaser supports multiple ways to build a map (of course). However, I have decided that it would be better to cook up our own map builder that would work off of a string. Spaces would indicate that at that position there is no platform, 1 would mean that there is, 2 that this is a spawn point for the player and a dot(.) would mean that this is the end of a row. The map I designed looks something like this: ```javascript //At the top of your js file const map = '11111111111111111111111111.'+ '1 1.'+ '1 1.'+ '1 2 1 1 1 1 1.'+ '1 1 1 1 1 1.'+ '1 1.'+ '1 1.'+ '1 1 1 1 1 1.'+ '1 1 1 1 1 1.'+ '1 1.'+ '1 1.'+ '1 1 1 1 1 1.'+ '1 1 1 1 1 1.'+ '1 1.'+ '1 1.'+ '11111111111111111111111111'; ``` You can see that it is a box that is riddled with platforms. How do we turn this into a map? The parser for this that I made is only a few lines of code: ```javascript //Goes instead of the previous platform adding code this.platforms = this.physics.add.staticGroup(); let mapArr = map.split('.'); let drawX = 0; let drawY = 0; mapArr.forEach(row=>{ drawX = 0; for(let i = 0; i<row.length; i++){ if(row.charAt(i)==='1'){ this.platforms.create(drawX, drawY, "platform"); }else if(row.charAt(i)==='2'){ if(row.charAt(i+1)==='1'){ this.spawnPlayer(drawX-4, drawY-12); }else if(row.charAt(i-1)==='1'){ this.spawnPlayer(drawX+4, drawY-12); }else{ this.spawnPlayer(drawX, drawY-12); } } drawX+=40; } drawY+=40; }); ``` First we split the string that we have into an array of rows using the . that says that a row ends at that point. Then we loop through each row and at each row we loop through each character in the row. If the character is a 1, we add a platform at that place. If the character is 2 we spawn the player. I have a bit more code there that checks if there is a platform to the left or right and that nudges the character to a side just so that the player does not spawn in a platform. Also, you may have noticed that we are calling `spawnPlayer` here with some parameters. These are just x and y coordinates of where to spawn. To make that work we just have to edit the `spawnPlayer` function like so: ```javascript this.spawnPlayer = (x, y)=>{ this.player = this.physics.add.sprite(x, y, "player", "sprite_0"); this.player.body.setGravityY(800); this.cameras.main.startFollow(this.player); }; ``` Now if you run this you should get a map inside of which the player can run around. You can mess around with the map string if you want and design your own map. I would love to see what you come up with in the comments! ### Player Animations A while ago, I mentioned that we would use the atlas for player animations. Now is the time! We have three frames in our atlas and we have only used one. It's time to use the other two. Phaser has its own animation manager (by now you get the idea - Phaser === everything) that makes it super simple to do animations. First we have to set up our animations: ```javascript // At the bottom of the create function this.anims.create({ key:"walk", frames:[{key:"player", frame:"sprite_2"}, {key:"player", frame:"sprite_1"}], frameRate:10, repeat:-1 }); this.anims.create({ key:"stand", frames:[{key:"player", frame:"sprite_0"}], frameRate:1 }); ``` This creates an animation for our player that we can play when we want. The array `frames` is what Phaser will loop though and play. `frameRate` is quite self explanatory - the amount of frames that are played each second. `repeat` with the value -1 will make the animation loop again and again. Not specifying `repeat` will just make it run once. The key is the string that we can use to reference to the animation later. Just the same way as with images. Now let's run the animations when we walk right or left: ```javascript //In the update function if(this.key_A.isDown){ this.player.setVelocityX(-200);"walk", true); }else if(this.key_D.isDown){ this.player.setVelocityX(200);"walk", true); }else{"stand", true); this.player.setVelocityX(0); } ``` The `true` parameter is just whether if there is already an animation running, should Phaser continue it? If you set this to false you will see that it will just freeze on a frame. That is because every frame it is checking if a key is pressed and then playing the animation. It will start again every frame making it look like it is frozen. Now if you run this you will see that we have a running animation with the legs moving and the hat bobbing up and down. There is only one more problem with the sprite. The player does not flip when he runs to the left. This is an easy fix: ```javascript //In the update function if(this.key_A.isDown){ this.player.setVelocityX(-200);"walk", true); this.player.flipX = true; }else if(this.key_D.isDown){ this.player.setVelocityX(200);"walk", true); this.player.flipX = false; }else{"stand", true); this.player.setVelocityX(0); } ``` There we go! Now we have a map, player animations, keybinds, physics and most of all - a weird blob of a character who has a hat that flaps in the breeze! ### The Final Step - Spikes and Coins Now let's add some spikes that the player has to dodge and some coins that the player can collect. First, let's add a score counter in the top of the screen that displays our score: ```javascript this.spawnPlayer = (x, y)=>{ this.player = this.physics.add.sprite(x, y, "player", "sprite_0"); this.player.body.setGravityY(800); this.physics.add.collider(this.player, this.platforms); this.cameras.main.startFollow(this.player); //====================================== this.player.score = 0; this.scoreText = this.add.text(0, 0, "Score: "+this.player.score, { fill:"#000000", fontSize:"20px", fontFamily:"Arial Black" }).setScrollFactor(0).setDepth(200); }; ``` `setScrollFactor(0)` will make sure that when our camera moves, the text does not. This way it will always be in the same position in the top-left of the screen. Text is drawn from its top-left (don't ask me why it is one way for one thing and another for another) so drawing it at `0, 0` will put in the top-left corner. `setDepth(200)` will make sure the text always appears on top. We also make a variable for the score of the player that can be increased when we collect a coin. #### Coins Time to make an incentive to run and jump around. Coins will be a `c` in our map string. So, the map would now look like this: ```javascript const map = '11111111111111111111111111.'+ '1 c 1.'+ '1 c c c 1.'+ '1 2 1 1 c 1 c 1 1.'+ '1 1 1 1 1 1.'+ '1 1.'+ '1 c c 1.'+ '1 c 1 1 c 1 c 1 1.'+ '1 1 1 1 1 1.'+ '1 1.'+ '1 c c c 1.'+ '1 1 c 1 c 1 1 1.'+ '1 1 1 1 1 1.'+ '1 1.'+ '1 c c c c 1.'+ '11111111111111111111111111'; ``` Now to make this work we have to add an option of what to do if the current character is a `c` in our map parser. I added something like this: ```javascript this.platforms = this.physics.add.staticGroup(); //================================== this.coins =; //================================= let mapArr = map.split('.'); let drawX = 0; let drawY = 0; mapArr.forEach(row=>{ drawX = 0; for(let i = 0; i<row.length; i++){ if(row.charAt(i)==='1'){ this.platforms.create(drawX, drawY, "platform"); }else if(row.charAt(i)==='2'){ if(row.charAt(i+1)==='1'){ this.spawnPlayer(drawX-4, drawY-12); }else if(row.charAt(i-1)==='1'){ this.spawnPlayer(drawX+4, drawY-12); }else{ this.spawnPlayer(drawX, drawY-12); } //================================= }else if(row.charAt(i)==='c'){ this.coins.create(drawX, drawY+10, "coin"); } //================================= drawX+=40; } drawY+=40; }); ``` If you run this you will see that a bunch of little coins appear. But we can't collect them! This is fairly easy to add: ```javascript // Add this after the map parsing code this.physics.add.overlap(this.player, this.coins, this.collectCoin, null, this); ``` This function will check if there is an overlap between two objects. The two objects are the first two parameters. If there is an overlap, it will run the function that is passed in with the third parameter. `null` is just there for reasons and `this` is just passing on the `this` value to the function. We now need to make a function `collectCoin` that will run if there is an overlap: ```javascript this.collectCoin = (player, coin)=>{ player.score+=10; this.scoreText.setText("Score: "+ this.player.score); coin.destroy(); }; ``` If you run this you will see that you can now collect coins and increase your score. Success! There is only one more step before we are done. #### Spikes Time to add some difficulty to the game. We are going to have spikes that if you step on they will clear your score and respawn you. Let's first add them to our map as an `s`: ```javascript const map = '11111111111111111111111111.'+ '1 c 1.'+ '1 c c s c 1.'+ '1 2 1 s 1 c 1 c 1 1.'+ '1 1 1 1 1 1.'+ '1 1.'+ '1 c c s s 1.'+ '1 c 1 s 1 c 1 c 1 1.'+ '1 1 1 1 1 1.'+ '1 1.'+ '1 c s c c 1.'+ '1 s 1 c 1 c 1 s 1 1.'+ '1 1 1 1 1 1.'+ '1 1.'+ '1 c c c c 1.'+ '11111111111111111111111111'; ``` And now we can render them into our game: ```javascript this.platforms = this.physics.add.staticGroup(); this.coins =; //================================== this.spikes =; //================================== let mapArr = map.split('.'); let drawX = 0; let drawY = 0; mapArr.forEach(row=>{ drawX = 0; for(let i = 0; i<row.length; i++){ if(row.charAt(i)==='1'){ this.platforms.create(drawX, drawY, "platform"); }else if(row.charAt(i)==='2'){ if(row.charAt(i+1)==='1'){ this.spawnPlayer(drawX-4, drawY-12); }else if(row.charAt(i-1)==='1'){ this.spawnPlayer(drawX+4, drawY-12); }else{ this.spawnPlayer(drawX, drawY-12); } }else if(row.charAt(i)==='c'){ this.coins.create(drawX, drawY+10, "coin"); //================================== }else if(row.charAt(i)==='s'){ this.spikes.create(drawX, drawY+10, "spike"); } //================================== drawX+=40; } drawY+=40; }); ``` Let's do what we did last time - add an overlap detector between the player and the spikes. The code is pretty much the same: ```javascript //Next to the other overlap checker for the coins this.physics.add.overlap(this.player, this.spikes, this.die, null, this); ``` And now we have to make a function `die` that will be run when the player hits the spike. All we will do is stop the game and display text saying **YOU DIED**: ```javascript this.die = ()=>{ this.physics.pause(); let deathText = this.add.text(0, 0, "YOU DIED", { color:"#d53636", fontFamily:"Arial Black", fontSize:"50px" }).setScrollFactor(0); Phaser.Display.Align.In.Center(deathText,, 250, 800, 500)); } ``` `this.physics.pause` is what stops the game. The text adding should be pretty self explanatory. The bit that may be confusing is the line after that. This is the code I used to center the text. It accepts two arguments - the object to center and the zone in which to center it in. `` in turn accepts four arguments - the x, y, width and height of the zone. The x and y are in the center of the screen and the width is the width of the screen and the same for the height. When you run this code and jump on a spike you will see that it shows some big red text saying __YOU DIED__. And there we have it! Our completed game! Make sure to celebrate by wrapping __lots__ of duct tape around some cardboard. That was what the duct tape and cardboard were for. Nothing, really :). ## Final Word Thank you for sticking to the end of this monster of a tutorial. I hope you are proud of what you have made. If you liked this tutorial, please show support by voting for it. If you have any questions, suggestions or if you found a typo don't hesitate to post it in the comments! Also, if you put a spin on the game or make a cool map that be sure to share it! I would love to see what you guys can make out of this :). If you are too lazy to scroll up, the link to the repl that I made is [here]( Also, if you would like me to make some follow up tutorials outside of the competition about some more advanced features like scenes and (multiplayer?) then be sure to leave a comment. If enough people want it I will be sure to make some more tutorials. ## __EDIT__ I made an additional demo that delves into some more complicated concepts but it looks a lot better (I stole some sprites off the internet). It is just some uncommented code that you can play around with and try and see if you can make anything out of it. If you want to check it out you can find it [here]( Just wanna play it? Go [here]( Also, thank you guys for all the support in the comments! So heartwarming to see that many people like it. [email protected]_
posted by kaldisberzins (255) 9 months ago
🎮 Making 3D Babylon Scenes more Dynamic with Actions
# 🎮 Making 3D Babylon Scenes more Dynamic with Actions In the [last tutorial](, I showed you guys how to make a basic Babylon scene, with lights, cameras, player controls, gravity, collision and other stuff. This time, I'm going to show you how to make scenes more dynamic! If you want to continue where I left off, make sure you fork my repl from the last tutorial! ![image]( *Image depics the logo of BabylonJS* ### Prerequisites - Intermediate JavaScript knowledge ## Actions To create things that are more dynamic in BabylonJS, you can use things called "Actions". To put it simply, Actions let you execute some function when an event occurs. For example, you can log some output to the console if you look at a Sphere. Before creating an Action, you must create an `ActionManager`. This lets you attach multiple actions to the same object. In this case, we are adding an `ActionManager` to the `scene` ```js scene.actionManager = new BABYLON.ActionManager(scene); ``` Now since we have our `ActionManager` all set up, we can create some Actions. To start off simply, we're going to create an "action" that tells the user when they have pressed space. ```js let myAction = new BABYLON.ExecuteCodeAction( BABYLON.ActionManager.OnKeyUpTrigger, function(event) { if(event.sourceEvent.key === " ") { console.log("You have pressed space"); } } ) gameScene.actionManager.registerAction(myAction); ``` - We're using the [`BABYLON.ExecuteCodeAction()`]( constructor to create the "Action". - The first argument of the constructor is a "trigger". A trigger will *cause* the action to execute. In this case, the trigger is "pressing a button on the keyboard" - The second argument to the constructor is the function we want to execute. In this case, we create a function that logs some output to the console, but only if the user pressed space. Cool! So when you press space, it logs to the console. If you want to see it in action, check out [this repl]( [repl]( ![image]( But logging some text to the console is pretty boring. Wouldn't it be cooler if it spawned in some spheres? Here I simply call the `createSphere` function instead of logging output to the console. ```js let action = new BABYLON.ExecuteCodeAction( BABYLON.ActionManager.OnKeyUpTrigger, function(event) { if(event.sourceEvent.key === " ") { createSphere(scene); } } ) scene.actionManager.registerAction(action); }; ``` Inside of the `createSphere` function, I create a Sphere Mesh. Like in the prevoius tutorial, I create a physics imposter and set collisions to `true`, so it collides with the ground and other spheres. ```js function createSphere(scene) { // Create Sphere Mesh let mySphere = BABYLON.MeshBuilder.CreateSphere("sphere", { diameter: 1 }, scene); // Give the sphere mesh a height so it spawns above the ground mySphere.position.y = 2; // Create a Pysics Imposter around the Sphere, and enable collisions so it interacts with other parts of the scene let mySpherePhysicsImposter = new BABYLON.PhysicsImpostor( mySphere, BABYLON.PhysicsImpostor.BoxImpostor, { mass: 0.01, friction: 0.1, restitution: .85 }, scene ); mySphere.collisionsEnabled = true; mySphere.checkCollisions = true; } ``` As you can see in the gif below, it works! 😄 ![gif]( If the spheres are not acting the way you want them to, you might want to change the `mass`, `friction`, or `restitution` of the spheres. You may also want to make gravity stronger. See it working in [this repl](! ## Changing a single Mesh Besides creating new meshes, you can also modify the properties of existing meshes! For example, I could use Actions to change the color of a Mesh whenever I look at it. Let's do exactly that. First, let's create a Cylinder Mesh. ```js let cone = createCone(scene); ``` The `createCone` function looks something like this ```js function createCone(scene) { // Create the cylinder let cone = new BABYLON.MeshBuilder.CreateCylinder("cone", { height: 5, diameterBottom: 3, diameterTop: 0 }); cone.position.x = -3; cone.position.z = -3; cone.position.y = 1; // Create a physics imposter and make sure collisiosn are enabled (so the spheres bounce off of it) new BABYLON.PhysicsImpostor( cone, BABYLON.PhysicsImpostor.BoxImpostor, { mass: 1000, friction: 3, restitution: .7 }, scene ); cone.collisionsEnabled = true; cone.checkCollisions = true; let coneMaterial = new BABYLON.StandardMaterial(scene); coneMaterial.diffuseColor = new BABYLON.Color3(105 / 256, 256 / 256, 124 / 256); // green cone.material = coneMaterial; return cone; } ``` The function looks pretty similar to what we went over in the [first tutorial]( The difference is at the bottom - we're changing the color of the cone. We do this by creating a *new* [(Standard) material]( To actually change the color, we set the [diffuseColor]( property of the material to a color. Then, we assign that material to our `cone`. OK, so we created our cone. Let's make it change color when we hover over it. First, create another action manager. This time, we create an `Actionmanager` for the `cone` rather than the `scene`. ```js cone.actionManager = new BABYLON.ActionManager(scene); let coneAction = new BABYLON.ExecuteCodeAction( BABYLON.ActionManager.OnPointerOverTrigger, function(event) { changeConeColor(cone); } ); cone.actionManager.registerAction(coneAction); ``` The `changeConeColor` function will trigger when the mouse has hovered over the cone. If you want to see all of Babylon's triggers, you can check their [documentation](! Inside `changeConeColor`, I just created random *red*, *green*, and *blue* numbers and created a color using Babylon's `BABYLON.Color3` constructor. I then set the `cone`'s material to that color (`diffuseColor`). ```js function changeConeColor(cone) { let r = Math.floor(Math.random() * 256) + 1; let g = Math.floor(Math.random() * 256) + 1; let b = Math.floor(Math.random() * 256) + 1; cone.material.diffuseColor = new BABYLON.Color3(r / 256, g / 256, b / 256); } ``` And there you have it! There is a lot more movement in our scene now! If you wish, you can check this repl]( to take a look! ![gif]( I hope you found this tutorial useful, please let me know!
posted by eankeen (529) 23 days ago
# What is a bookmarklet? A bookmarklet is similar to an extension, but is used by clicking a bookmark. According to wikipedia: > A bookmarklet is a bookmark stored in a web browser that contains JavaScript commands that add new features to the browser. Bookmarklets are unobtrusive JavaScripts stored as the URL of a bookmark in a web browser or as a hyperlink on a web page. Bookmarklets are usually JavaScript programs. Regardless of whether bookmarklet utilities are stored as bookmarks or hyperlinks, they add one-click functions to a browser or web page. When clicked, a bookmarklet performs one of a wide variety of operations, such as running a search query or extracting data from a table. For example, clicking on a bookmarklet after selecting text on a webpage could run an Internet search on the selected text and display a search engine results page. # Create a bookmarklet Creating a bookmarklet is easy. (If you do know how to create a bookmark. If not read [Creating A Bookmark]( ) Let's create a simple example: First, create a bookmark. As for the title of the bookmark, name it “Hello World”. Instead of keeping the url of the page as the bookmark type `javascript:alert(‘Hello World!’)`. There! Click save or whatever it is in your search engine. And click the bookmark. You should have an alert message saying “Hello World!” appear! To run js in a bookmark, you need to have the `javascript:` prefix before it. You can only type one line so make sure to use your semicolons! In addition, you **can not use double quotes**. The search engine saves the bookmark in code that looks something like this: ```html <a href="javascript:alert(‘Hello World!’)">Hello World</a> ``` If you use double quotes it looks like: ```html <a href="javascript:alert(“Hello World!”)”>Hello World</a> ``` And causes an error. If you have multiple lines, create an anonymous function: `javascript:(function(){ var x=prompt(‘Hi say something:’); alert(‘You said: ’ + x); })()` Notice there are NO double quotes. Let's go over some examples: Google Search: `javascript:(function(){''+prompt('Google Search:', '').split(' ').join('+'), '', 'width=800,height=500,left=10,top=10,scrollbar=yes');})();` The above example opens up a new window with a search query of your input! Feel free to copy any of these or the ones listed below. Calculator: `javascript:(function(){var evl,expr=prompt('Formula...','');with(Math)try{evl=parseFloat(eval(expr));if(isNaN(evl)){throw Error('Not a number!');}prompt('Result of '+expr+':',evl)}catch(evl){alert(evl);}})();` @JSer ‘s Rolling Sky: (Thanks for creating such an awesome game!) `'', '', 'top=15,left=15,scrollbar=yes,width=500,height=600')` # Community Creations @Zavexeon **Faces Generator** > uhm... it works.... and is also useless... ```js javascript: const faces = ['OwO ', 'UwU', 'TwT', '>w<', '^w^']; let face = faces[Math.floor(Math.random()*faces.length)]; document.write('<body style=\'background-color: black;\'></body><title>' + face + '</title><p style=\'text-align: center; font-size: 500px; font-family: Arial; color: white;\'>' + face + '</p>'); ``` ** Thank you for reading! Please upvote and comment your own bookmarklets, to be added to the community creations section! I hope I get a content creator tag for this 😀 **
posted by PYer (2045) 3 months ago
LLC - Java
# Language learning club - Java ### Introduction Thanks to the []( team (especially @amasad and @katyadee), we now have a language learning club about which you can learn more [here](<>). We recently had a voice session for [GoLang]( and it was pretty dull and I didn't want that to happen again. So I decided to contribute to the people learning Java myself. There is going to be a session over voice chat on the discord server at 06:00 PM CST on Mondays. You can join the discord server by [clicking here]( ------ ### For Beginners Now that all the info has been shared, here are some resources you can use to get started with Java: - For book lovers: - - [Java: A Beginner's Guide]( - [Effective Java]( For YouTube video lovers: - - [Java tutorial for beginners video series]( - [Another Java tutorial for beginners (9 hour video)]( ------ ### GUI Development with Java For people who have learned the basics of Java, here are a few YouTube videos that you can watch to learn GUI development with Java. For people who like to read: - - [Java Swing Tutorial]( - [Swing Tutorialspoint]( For people who like videos: - - [Complete Java Swing tutorial]( - [Java Swing tutorial video series]( ------ ### Android App development For people who even know about Swing. Java is the most used language for mobile apps development in [Android Studio]( [Click here to learn about Android App development]( Here you'll find that there is a new alternative to Java - `Kotlin`. And it also seems like a sweet choice. You can compare the differences between Java and Kotlin [here]( ------ ### Some code examples ***Note:*** *In all the examples the file was named as `` which is the default in []( Also, the following examples use the simplest ways possible, these programs could've been made much smaller (except for the first one).* **Hello World** ```java /* This program is basically the boilerplate for the language*/ class Main { public static void main(String[] args) { System.out.println("Hello world!"); } } ``` ------ **Hello <name>** ```java // Importing the scanner class for taking input import java.util.Scanner; class Main { public static void main(String[] args) { // Declaring the variables String name; Scanner in = new Scanner(; // Getting the name System.out.println("What's your name?"); name = in.nextLine(); // Printing the name System.out.println("\nHello, " + name); } } ``` ------ **Factorial** ```java // Importing the Scanner class for taking input import java.util.Scanner; class Main { public static void main(String[] args) { // Declaring the variables int n, factorial = 1; Scanner in = new Scanner(; // Getting a number from the user. System.out.print("Please enter a number: "); n = in.nextInt(); // Calculating the factorial using a simple for loop for(int i = 1; i <= n; i++) { factorial = factorial * i; } // Showing the calculated factorial System.out.println("\nThe factorial of " + n + " is " + factorial); } } ``` ------ That's all for now. Visit the above links and learn more for yourself! :P
posted by TheDrone7 (516) 3 months ago
Learn ReactJS on Replit! 📙
# Learn ReactJS on Replit!📙 ![react-logo]( Some of you guys may have heard of ReactJS According to the [official website]( > [React is a] a JavaScript library for building user interfaces. But what exactly does that mean? This tutorial is meant for people that know a bit of JavaScript and want to learn the fundamentals of React. But first, lemmie tell you a problem that we've all probably asked at one point > How do I put one HTML file in another HTML file? When we create HTML files by hand, we often come across the problem of reusability. For example, we may want to reuse a `heading` component across a bunch of HTML files. Or, we have a navigation bar, and we want to avoid copying and pasting each navigation item over and over again. React helps us solve this problem. ## Fundamentals Before I show you how to do this, I'd like to share one of the fundamental concepts of React. Components. You can think of a component as a capsule that contains some HTML, CSS, and JavaScript. Let me show you some examples ![1561236905533]( As you can see, each colored rectangle is a component. Rectangles that have the same color are the same component, but with a few differences. For example, all the components with the blue rectangle look the same because they all have a title, a 'last edited' time, and a picture. The differences are the actual numbers, and the actual text of the titles. The formatting is near-identical. I found another website, and outlined a few components. The header component is in red, and the navigation components are in yellow. ![image]( From these example, you may have noticed that components are made to be reusable. That's part of the point. 🙂 So rather than having the following in your HTML: ```html <nav> <ul> <li> <div class="wrapper"> <a href="/">Home</a> </div> </li> <li> <div class="wrapper"> <a href="/about">About</a> </div> </li> <li> <div class="wrapper"> <a href="/contact">Contact</a> </div> </li> </ul> </nav> ``` You may want to have something like this: ```html <nav> <ul> <NavigationItem></NavigationItem> <NavigationItem></NavigationItem> <NavigationItem></NavigationItem> </ul> </nav> ``` (Note that this is not valid HTML markup, but it's useful to think this way when using React components) Each `<NavigationItem>` is a reusable component and may contain the following. ```html <li> <div> <a href="placeholder1">placeholder 2</a> </div> </li> ``` Although this code won't actually run, it's useful to have this mindset of components. If you are reusing a set of element on the page, it's likely you can create a component out of it. ## Components in React You create components in React with something called [JSX]( In a nutshell, it's a way of writing HTML in JavaScript. Here is a classic example of JSX ```jsx const element = <h1>Hello, world!</h1>; ``` With some special tools, you will be able to create HTML elements using this kind of syntax with React. Here is another example - writing JSX over multiple lines. ```jsx let MyComponent = ( <div className="App"> <h1>Very neat</h1> <MyOtherComponent /> </div> ); ``` As you have noticed, one main difference between writing HTML and JSX, is the use of [HTML classes]( Because JSX is more close to JavaScript (rather than HTML), you cannot use the word `class`. It's a reserved word (see [JS Classes]( If we ever want to have an HTML class, we just have to write `className` instead of `class`. ## Creating a React Repl 🚀 Now that we know a bit about `React`, and `JS`, let's create a `React` repl! ![image]( A bunch of files are already created for us. I'd recommend looking at `public/index.html`. This is the actual `html` file that's send to your browser. You might be a little confused because there aren't any `<script></script>` tags to any JavaScript files or `<link>` tags to any CSS files. But after "Inspect Elementing" our website, you can clearly see that someone put them there (see the bottom of the orange rectangle or underneath the red rectangle). ![1561237937286]( Who's putting our script tags there? The details are a bit too complicated for this tutorial, but just know that certain build tools automatically inject JavaScript and CSS files in our HTML. You don't need to know about these tools right now. Just know they exist when you create a React repl, and that they work ✨magically ✨behind the scenes. Before we leave our `index.html` element, just take a mental note of the single HTML in our `<body>` tag ```html <div id="root"></div> ``` So now let's check out our `src/index.js` (I deleted a few lines, since some of them were not needed). ![image]( `index.js` is the start for our app. Here, we're importing React, our global CSS, and our main `App` component. - Our global CSS is the `index.css` file. It contains CSS for the entire page. Don't put too much CSS in here since it can potentially override CSS in your React components - Our `App` component is where all our other components will start. For example, you might have a `<Heading />`, `<BodyComponent />`, and `<FooterComponent />` in your `App` component Under all the imports,, we really have one line of code on our page ```js ReactDOM.render(<App />, document.getElementById('root')); ``` It's pretty self explanatory, but this makes React render our App component. It renders our App component and puts it all inside of that `<div id="root"></div>` element that I showed you earlier. So React is rendering our `App` component! What is inside of of it? ![image]( Here, we create a class called `App`. This class is a React component. Inside this class, we are creating a render function. This function returns JSX, which will eventually get rendered on the screen. If you're a bit confused, try looking at the render function this way: ```jsx class App extends Component { render() { let myJSX = ( <div className="App"> <header className="App-header"> ... </header> </div> ); return myJSX; } } ``` Here, we explicitly create a variable called `myJSX`, then return it. ## Creating our Own Components Now you know a bit about `React` and `JSX`, let's create our own components. Components are usually put in a folder titled `components`. ![image]( I'm going to start off by making a Heading component. I only have text in here, just to keep it simple. We want to put the `Heading` component inside our `App` component. To do this, we just have to import it inside our `App` component! ```js import Heading from './components/Heading' ``` Now, anywhere in your JSX, you can add the `<Heading />` element. I'm going to add it to the top. ![image]( It's working! However, the formatting is a bit off since there is a scrollbar. I solved this by removing everything inside of `<header></header>` and replacing it with my own `<Body />` component. I also replaced the `App.css` file with my own `css`: ```css * { margin: 0; padding: 0; } html, body { height: 100%; width: 100%; } .App { height: 100%; } ``` If you want to see the repl up to this point, you can find it [here]( It looks like this: ![image]( Remember how I was talking about reusing components? This is where we would do it - just copy whatever element you want to be repeated! ![1561245087705]( Go ahead and try to play around - create some components and add them to your `App`, `Heading`, or `Body` component! ## Props There is one more basic concept that you should know about: props. Props (which stands for properties) let us transfer data from our parent component to a child component. This might sound confusing at first, but hopefully it'll clear up when I give an example. For this example, I'm going to be using the repl located [here]( ### Example I want to transfer data from my `Heading` to each `NavigationItem`. So, the parent component is `Heading` and child component is `NavigationItem`. Inside of the parent component, I need to have my child component imported and being used. ![image]( I already have imported the `NavigationItem` component. I'm also using it (3 times). The next step is to add the prop. Props need to have a name and a value. I'm going to name them `myPropName` and `myPropValue` ![image]( Great! We're now sending the prop from our `Heading` component to the `NavigationItem` component! We are almost finished - now we just have to render it! The props you pass down are properties of the `this.props` object. Simply access your prop by its name (in the child component), and you're good to go! Don't forget to add the `{}`curly brackets! ![image]( You can also use props when you're dealing with HTML attribute values. Just add brackets and access the prop! ```jsx <img src={ this.props.myImageLink } /> ``` I hope this introduction to React was helpful! I remember when I was getting into JavaScript frameworks it was difficult since tutorials would gloss over the "obvious" parts. If this helped you or some parts were confusing, let me know and I'll make it better!
posted by eankeen (529) 28 days ago
Build a WhatsApp bot in 30 minutes 🕐
A few months ago, I'd started making chatbots on [Telegram]( - I'd seen APIs for WhatsApp but they were unoffical and there was a chance for getting your number blocked 📱 ❌ A while ago, I saw that [Twilio]( had an official WhatsApp API. 30 minutes later, I made a [Wikipedia bot on WhatsApp]( 👇 ![]( This is a tutorial to help you make a something like this, your own chatbots on WhatsApp - these bots are immediately available to 2 billion users, and there are so many things possible 🎓 I can't wait to see what you make! Now, let's get started 🏃‍♂️ ## 🔑 Accounts and Keys First, Sign up for [Twilio]( - it's free and you won't need a credit card 💳 ![]( Once you're done verifying your phone number, select Procuts > Programmable SMS and then continue to name your project. ![]( Feel free to skip steps for adding teammates - you won't need that for now. You must now take note of some authentication keys you'll need for building the WhatsApp bot 👇 ![]( The final step - setup your WhatsApp Sandbox [here]( - choose any number, and join your sandbox following instructions on the page. ![]( Aaaaaand you're done with credential setup! Don't worry, that was the toughest part of this tutorial 😛 ## 🚀 Getting Started So that we don't spend too much time on setup, I've created an environment (with!) you can use within your browser. Head over [here](, and wait for a couple of seconds to fork it. Next, open up `server.js` and put in your Account SID and Auth Token, on lines `7` and `8` ```javascript const accountSid ="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; //Account SID const authToken ="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; // Auth Token ``` You can see, this environment already has dependencies installed, and an `express` server set up. We still need to give Twilio a URL to send incoming messages to, though 🔗 Let's go back to the [WhatsApp Sandbox](, and put in a webhook URL for incoming messages. ![]( This URL must be what you see on the preview panel of your []( project + `/incoming` ![]( We can now finally read messages that are sent to the bot. Add a simple `console.log()` in your webhook handler 👇 ```javascript'/incoming', (req, res) => { console.log(req.body) }); ``` When you send a message to your bot, you should be able to see something like this in your repl console 👨‍💻 ![]( Building an echo bot would look something like this, using `twiml` to write a message 👇 ```javascript'/incoming', (req, res) => { const twiml = new MessagingResponse(); twiml.message(req.body.Body); res.writeHead(200, {'Content-Type': 'text/xml'}); res.end(twiml.toString()); }); ``` But, since we're actually trying to build a useful bot - let's use informative APIs! ## 🌐 Fetching Information DuckDuckGo has an amazing, free instant answer API. It takes in a query and returns back a summary from WikiPedia and more. A few examples 👉 [WikiPedia](, [Macbook Air](, [Twilio]( I spent some time creating a decent parser which usually returns information from this API. Try pasting this code in your []( project, and your [console]( should have stuff about Trump in it 😛 ```javascript var base = ''; var query = 'Donald Trump'; request(base + query, function (error, response, body) { body = JSON.parse(body) if(body["Abstract"] == ""){ body["Abstract"]= body["RelatedTopics"][0]["Text"] } var msg = body["Heading"]+"\n\n"+body["Abstract"]; console.log(msg) }); ``` Pretty straight forward, right? 😄 ## 🛠️ Putting it all together To make our actual bot, all we need to do is get the query from our request - which we can get as `req.body.Body` - and use `twmil` to send across the data we collected in `msg` ```javascript'/incoming', (req, res) => { const twiml = new MessagingResponse(); var base = ''; var query = req.body.Body; request(base + query, function (error, response, body) { body = JSON.parse(body) if(body["Abstract"] == ""){ body["Abstract"]= body["RelatedTopics"][0]["Text"] } var msg = twiml.message(body["Heading"]+"\n\n"+body["Abstract"]); res.writeHead(200, {'Content-Type': 'text/xml'}); res.end(twiml.toString()); }); }); ``` You now have a fully functionaing WhatsApp bot! Send anything you want to know about your bot 🤖 and you should see it respond super fast 💬 ⚡ Adding welcome messages and a little formatting is quite simple, look at the final [repl]( to see how I did it 👨‍💻 ## 🔗 Sharing the bot For others to use this bot, they'll need to join your sandbox first - and send a message just like you did earlier 👉 `join <two-words>` You can create links with this text too - For example this link lets you join my bot 👇 ``` ultramarine-tapir ``` `14155238886` is my bot's number, while `ultramarine-tapir` is the sandbox phrase. ## ⚡ What's next? Now that you know how to build a bot on WhatsApp, try sending notifications to yourself, and building more useful tools! Twilio has loads of [other mediums]( to message through too! All code for my WikiBot is on [Github](! I'm a 15 year old maker 👨‍💻 For more cool things to make and to stay update with my progress, sign up for [my newsletter 📧](
posted by jajoosam (543) 9 months ago
👾🎉 Announcing Python Play (beta) & a pong game tutorial
# [Python Play]( is the easiest way to get started coding games and graphics projects. @amasad and the team asked me to help them make an easy way for new programmers to start making games and graphics projects. As a result, we made [Python Play](, a code library for Python loosely based on [Scratch]( For more information about Python Play, you can [read the documentation here]( This is a tutorial showing how to use Python Play to make a game. To follow along with the tutorial, you can go to **[this repl](** and add code line-by-line. The game we'll be making is a pong game: ![screenshot]( ## How to make a pong game with Python Play To make this game, first we need a box. Copying and pasting the code below will put a box on the screen: ```python import play # this should always be the first line in your program box = play.new_box(color='black', x=0, y=0, width=30, height=120) play.start_program() # this should always be the last line in your program ``` After you've copied that code, click the "Run" button. You should see a tall black box in the middle of the screen. If you change any of the stuff after `new_box`, it will change what the box looks like and where it shows up on the screen. Change `x=0` to `x=100` and the box moves over to the right: ```python box = play.new_box(color='black', x=350, y=0, width=30, height=120) ``` (Click the Run button after every code change you make. Also make sure you still have the `import play` and `play.start_program()` lines of code in your program.) Changing `x` changes the horizontal position and changing `y` changes the vertical position of the box. You can try playing with these numbers to see how they work. Don't forget you can do negative numbers i.e. `x=-100` (note the minus symbol in front). Okay cool, a box is on the screen and we can change where it is. But how do we get it to do stuff? Change your code to look like this: ```python box = play.new_box(color='black', x=350, y=0, width=30, height=120) @play.when_key_pressed('up') async def do(key): box.y += 10 ``` Then try pressing the 'up' arrow on your keyboard. The box moves upward now! The code above is saying "when the up arrow key is pressed, add `10` to the box's `y` position". Adding to the box's `y` position moves the box up on the screen. Can you guess how we could get the box to move down when the down arrow key is pressed? Here's the full code for how you might do that: ```python box = play.new_box(color='black', x=350, y=0, width=30, height=120) @play.when_key_pressed('up') async def do(key): box.y += 10 @play.when_key_pressed('down') async def do(key): box.y -= 10 ``` (Remember that your program should still start with `import play` and end with `play.start_program()`.) So now the box moves up and down on the screen when we press the arrow keys. ### Adding a ball Now we need a ball. Add this line below the `new_box` line: ```python ball = play.new_box(color='dark red', x=0, y=0, width=20, height=20) ``` Now there's a ball but it's not moving. To get it moving, here's the full code to put in your program: ```python ball = play.new_box(color='dark red', x=0, y=0, width=20, height=20) ball.dx = 2 ball.dy = -1 # make the ball move @play.repeat_forever async def do(): ball.x += ball.dx ball.y += ball.dy ``` This makes the ball move by changing its `x` and `y` position (repeating forever) by the horizontal speed `dx` and the vertical speed `dy`. `ball.dx` and `ball.dy` are two variables we're making up to store the horizontal speed and vertical speed of the ball. The starting horizontal speed (`dx`) is 2 (to the right) and the vertical speed is -1 (down). But the ball doesn't bounce off the paddle, it just goes right through. To fix that, we have to detect when the ball is right next to the paddle and reverse its direction. Add this code to your program: ```python # make the ball bounce off the player's paddle @play.repeat_forever async def do(): if (ball.right >= box.left) and ( >= box.bottom) and (ball.bottom <= and (ball.left < box.left): ball.dx = -2 ``` Now the ball bounces off the paddle! The code above checks three conditions which are best shown visually: ![if-statement]( If the ball is anywhere over the red line in the grey areas, then the condition written below it becomes `True`. If all three conditions are `True` at the same time, that means the ball hit the paddle and its speed should be reversed (-4) so it goes the other way. (`<=` means "less than or equal" and `>=` means "greater than or equal"). Here's the whole program at this point: ```python import play box = play.new_box(color='black', x=350, y=0, width=30, height=120) ball = play.new_box(color='dark red', x=0, y=0, width=20, height=20) ball.dx = 2 ball.dy = -1 @play.when_key_pressed('up') async def do(key): box.y += 10 @play.when_key_pressed('down') async def do(key): box.y -= 10 @play.repeat_forever async def do(): ball.x += ball.dx ball.y += ball.dy # make the ball bounce off the player's paddle @play.repeat_forever async def do(): if (ball.right >= box.left) and ( >= box.bottom) and (ball.bottom <= and (ball.left < box.left): ball.dx = -2 play.start_program() ``` ### Adding a computer player There should be another player. Let's create another box! Add this code near where you put the code starting with `box = play.new_box`: ```python other_box = play.new_box(color='black', x=-350, y=0, width=30, height=120) other_box.dy = 3 ``` We're making the box have a vertical speed of 2 when it moves, but we haven't made it move yet. To make the computer player follow the ball, we can add this code to our program: ```python # make the computer player follow the ball @play.repeat_forever async def do(): if ball.x < 0 and abs(ball.y-other_box.y) > other_box.dy: if other_box.y < ball.y: other_box.y += other_box.dy elif other_box.y > ball.y: other_box.y -= other_box.dy ``` Now when the ball is on the left side of the screen, the computer player will move toward the ball! We add to the box's `y` if the box is below the ball, otherwise we subtract from the box's `y` if it's above the ball. But oops, the ball doesn't bounce off the computer player's paddle (`other_box`). Let's make it do that by adding this code: ```python # make the ball bounce off the computer player's paddle @play.repeat_forever async def do(): if (ball.left <= other_box.right) and ( >= other_box.bottom) and (ball.bottom <= and (ball.right > other_box.right): other_box.dy = play.random_number(1, 4) ball.dx = 2 ``` This code works just like the collision code from above but in reverse for the left paddle. Also when the ball hits the paddle we change the paddle's speed to a random number between 1 and 4 so the paddle will move either slower or faster. But oops again, now if we get the ball to bounce off the computer player's paddle, it doesn't bounce off the walls. To make the ball bounce off the walls, we add this code that checks that the ball is lower than the top of the screen and higher than the bottom of the screen: ```python # make ball bounce off bottom and top walls @play.repeat_forever async def do(): if ball.bottom <= play.screen.bottom: ball.dy = 1 elif >= ball.dy = -1 ``` If the ball hits either the top or the bottom of the screen, the code above will reverse its speed so it bounces. And that's it! A simple pong game in about 50 lines of code! ## The final code Here's all the code in the tutorial in one place: ```python import play box = play.new_box(color='black', x=350, y=0, width=30, height=120) other_box = play.new_box(color='black', x=-350, y=0, width=30, height=120) other_box.dy = 3 ball = play.new_box(color='dark red', x=0, y=0, width=20, height=20) ball.dx = 2 ball.dy = -1 @play.when_key_pressed('up') async def do(key): box.y += 10 @play.when_key_pressed('down') async def do(key): box.y -= 10 # make the ball move @play.repeat_forever async def do(): ball.x += ball.dx ball.y += ball.dy # make the ball bounce off the player's paddle @play.repeat_forever async def do(): if (ball.right >= box.left) and ( >= box.bottom) and (ball.bottom <= and (ball.left < box.left): ball.dx = -2 # make the computer player follow the ball @play.repeat_forever async def do(): if ball.x < 0 and abs(ball.y-other_box.y) > other_box.dy: if other_box.y < ball.y: other_box.y += other_box.dy elif other_box.y > ball.y: other_box.y -= other_box.dy # make the ball bounce off the computer player's paddle @play.repeat_forever async def do(): if (ball.left <= other_box.right) and ( >= other_box.bottom) and (ball.bottom <= and (ball.right > other_box.right): other_box.dy = play.random_number(1, 4) ball.dx = 2 # make ball bounce off bottom and top walls @play.repeat_forever async def do(): if ball.bottom <= play.screen.bottom: ball.dy = 1 elif >= ball.dy = -1 play.start_program() ``` And here's a [link to a repl with the code above]( ## More Challenges This game is pretty simple. Can you think of other things to add to make it more fun? Here are some suggestions for things to try: - Can you make the paddles change colors when the ball hits them? - How would you keep track of and show scores in the game? (Hint: look up the `play.new_text()` function.) - Did you find any glitches in the game? How would you try to fix those glitches? - How would you make the ball change speed differently depending on where it hits on the paddle? - Could you add multiple balls to the game? What else would you add to make the game more fun? # Python Play Thanks for reading this tutorial! If you make anything with Python Play, please post it in the comments! Python Play is currently in beta, which means some things may not work quite right. If you find a problem (usually called a "bug"), please send us a link to the repl where you found that bug. To find out more about all the things you can do with Python Play, [read the documentation here](! Look for more Python Play features coming soon! Try it out and let us know what you think!
posted by glench (34) 4 months ago
Building AI: Neural Networks for beginners 👾
Teaching Machine to recognize Hand-written Numbers! I am excited to share some of my experience studying machine learning with you, guys! I'm not an expert but I'll try to explain it the way I see it myself. I'm going to try to give you some intuition about how Neural Networks work, omitting most of the math to make it more understandable but, for the most curious of you, I'll leave the links to complete explanations/courses in the end. ![Predicted class_ 4]( In 29 mins, you'll be able to configure an algorithm that's going to recognize the written digits in python :) ## **🧠 What is a Neural Network?** Imagine Neural Network as an old wise wizard who knows everything and can predict your future by just looking at you. ![magicbox]( It turns out that he manages to do so in a very non-magical way: 1. Before you visited him, he trained, carefully studied everything about many thousands of people who came to see him before you. 2. He now collects some data about what you look like (your apparent age, the website you found him at, etc). 3. He then compares it to the historical data he has about people that came to see him before. 4. Finally, he gives his best guess on what kind of person you are based on the similarities. ![nn]( In very general terms, it is the way many machine learning algorithms work. They are often used to predict things based on the history of similar situations: Amazon suggesting the product you might like to buy, or Gmail suggesting to finish the sentence for you, or a self-driving car learning to drive. ## **📙 Part 1: Import libraries** Let's start! I have put together a class that is doing all the math behind our algorithm and I'd gladly explain how it works in another tutorial or you could go through my comments and try to figure it out yourself if you know some machine learning. **For now, create a file called `` and paste this code:** ```python import numpy as np from scipy.optimize import minimize class Neural_Network(object): def configureNN(self, inputSize, hiddenSize, outputSize, W1 = np.array([0]), W2 = np.array([0]), maxiter = 20, lambd = 0.1): #parameters self.inputSize = inputSize self.outputSize = outputSize self.hiddenSize = hiddenSize #initialize weights / random by default if(not W1.any()): self.W1 = np.random.randn( self.hiddenSize, self.inputSize + 1) # weight matrix from input to hidden layer else: self.W1 = W1 if (not W2.any()): self.W2 = np.random.randn( self.outputSize, self.hiddenSize + 1) # weight matrix from hidden to output layerself.W2 = W2 else: self.W2 = W2 # maximum number of iterations for optimization algorithm self.maxiter = maxiter # regularization penalty self.lambd = lambd def addBias(self, X): #adds a column of ones to the beginning of an array if (X.ndim == 1): return np.insert(X, 0, 1) return np.concatenate((np.ones((len(X), 1)), X), axis=1) def delBias(self, X): #deletes a column from the beginning of an array if (X.ndim == 1): return np.delete(X, 0) return np.delete(X, 0, 1) def unroll(self, X1, X2): #unrolls two matrices into one vector return np.concatenate((X1.reshape(X1.size), X2.reshape(X2.size))) def sigmoid(self, s): # activation function return 1 / (1 + np.exp(-s)) def sigmoidPrime(self, s): #derivative of sigmoid return s * (1 - s) def forward(self, X): #forward propagation through our network X = self.addBias(X) self.z = X, self.W1.T) # dot product of X (input) and first set of 3x2 weights self.z2 = self.sigmoid(self.z) # activation function self.z2 = self.addBias(self.z2) self.z3 = self.z2, self.W2.T) # dot product of hidden layer (z2) and second set of 3x1 weights o = self.sigmoid(self.z3) # final activation function return o def backward(self, X, y, o): # backward propgate through the network self.o_delta = o - y # error in output self.z2_error = self.W2 ) # z2 error: how much our hidden layer weights contributed to output error self.z2_delta = np.multiply(self.z2_error, self.sigmoidPrime( self.z2)) # applying derivative of sigmoid to z2 error self.z2_delta = self.delBias(self.z2_delta) self.W1_delta += np.array([self.z2_delta]).T, np.array([self.addBias(X)])) # adjusting first set (input --> hidden) weights self.W2_delta += np.array([self.o_delta]).T, np.array([self.z2])) # adjusting second set (hidden --> output) weights def cost(self, nn_params, X, y): #computing how well the function does. Less = better self.W1_delta = 0 self.W2_delta = 0 m = len(X) o = self.forward(X) J = -1/m * sum(sum(y * np.log(o) + (1 - y) * np.log(1 - o))); #cost function reg = (sum(sum(np.power(self.delBias(self.W1), 2))) + sum( sum(np.power(self.delBias(self.W2), 2)))) * (self.lambd/(2*m)); #regularization: more precise J = J + reg; for i in range(m): o = self.forward(X[i]) self.backward(X[i], y[i], o) self.W1_delta = (1/m) * self.W1_delta + (self.lambd/m) * np.concatenate( (np.zeros((len(self.W1),1)), self.delBias(self.W1)), axis=1) self.W2_delta = (1/m) * self.W2_delta + (self.lambd/m) * np.concatenate( (np.zeros((len(self.W2),1)), self.delBias(self.W2)), axis=1) grad = self.unroll(self.W1_delta, self.W2_delta) return J, grad def train(self, X, y): # using optimization algorithm to find best fit W1, W2 nn_params = self.unroll(self.W1, self.W2) results = minimize(self.cost, x0=nn_params, args=(X, y), options={'disp': True, 'maxiter':self.maxiter}, method="L-BFGS-B", jac=True) self.W1 = np.reshape(results["x"][:self.hiddenSize * (self.inputSize + 1)], (self.hiddenSize, self.inputSize + 1)) self.W2 = np.reshape(results["x"][self.hiddenSize * (self.inputSize + 1):], (self.outputSize, self.hiddenSize + 1)) def saveWeights(self): #sio.savemat('myWeights.mat', mdict={'W1': self.W1, 'W2' : self.W2}) np.savetxt('data/', self.W1, delimiter=',') np.savetxt('data/', self.W2, delimiter=',') def predict(self, X): o = self.forward(X) i = np.argmax(o) o = o * 0 o[i] = 1 return o def predictClass(self, X): #printing out the number of the class, starting from 1 print("Predicted class out of", self.outputSize,"classes based on trained weights: ") print("Input: \n" + str(X)) print("Class number: " + str(np.argmax( np.round(self.forward(X)) ) + 1)) def accuracy(self, X, y): #printing out the accuracy p = 0 m = len(X) for i in range(m): if (np.all(self.predict(X[i]) == y[i])): p += 1 print('Training Set Accuracy: {:.2f}%'.format(p * 100 / m)) ``` ## **📊 Part 2: Understanding Data** Cool! Now, much like the wizard who had to study all the other people who visited him before you, we need some data to study too. Before using any optimization algorithms, all the data scientists first try to *understand* the data they want to analyze. **Download files `` (stores info about what people looked like - question) and ``(stores info about what kind of people they were - answer) from [here]( and put them into folder `data` in your repl.** * X: We are given 5,000 examples of 20x20 pixel pictures of handwritten digits from 0 to 9 (classes 1-10). Each picture's numerical representation is a single vector, which together with all the other examples forms an array `X`. * Y: We also have an array `y`. Each column represents a corresponding example (one picture) from `X`. `y` has 10 rows for classes 1-10 and the value of only the correct class' row is one, the rest is zeros. It looks similar to this: ``` [0, 0, 0, 0, 0, 0, 0, 0, 0, 1] # represents digit 0 (class 10) [1, 0, 0, 0, 0, 0, 0, 0, 0, 0] # represents digit 1 (class 1) ...... [1, 0, 0, 0, 0, 0, 0, 0, 1, 0] # represents digit 9 (class 9) ``` Now, let's plot it! ![TrainingData]( In the end, I'd want a function `displayData(displaySize, data, selected, title)`, where * `displaySize` - the numer of images shown in any one column or row of the figure, * `data` - our X array, * `selected` - an index (if displaying only one image) or vector of indices (if displaying multiple images) from X, * `title` - the title of the figure **Create a `plots` folder to save your plots to. Also, if you use repl, create some empty file in the folder so that it doesn't disappear.** **Create a `` file and write the following code in there. Make sure to read the comments:** ```python import matplotlib.pyplot as plt # Displaying the data def displayData( displaySize, data, selected, title ): # setting up our plot fig=plt.figure(figsize=(8, 8)) fig.suptitle(title, fontsize=32) # configuring the number of images to display columns = displaySize rows = displaySize for i in range(columns*rows): # if we want to display multiple images, # then 'selected' is a vector. Check if it is here: if hasattr(selected, "__len__"): img = data[selected[i]] else: img = data[selected] img = img.reshape(20,20).transpose() fig.add_subplot(rows, columns, i+1) plt.imshow(img) # We could also use, but repl # can't display it. So let's insted save it # into a file plt.savefig('plots/' + title) return None ``` Great, we are halfway there! ## **💪 Part 3: Training Neural Network** Now, after we understand what our data looks like, it's time to train on it. Let's make that wizard study! It turns out that the results of the training process of the Neural Networks have to be stored in some values. These values are called *parameters* or *weights* of the Neural Network. If you were to start this project from scratch, your initial weights would be just some random numbers, however, it would take your computer forever to train to do such a complex task as recognizing digits. For this reason, I will provide you with the initial weights that are somewhat closer to the end result. **Download files `` and `` from [here]( and put them into `data` folder.** We are now ready to write code to use our Neural Network library! ![training]( **Create a `` file and write the following code in there. Make sure to read the comments:** ```python # This code trains the Neural Network. In the end, you end up # with best-fit parameters (weights W1 and W2) for the problem in folder 'data' # and can use them to predict in import numpy as np import display from NN import Neural_Network NN = Neural_Network() # Loading data X = np.loadtxt("data/", comments="#", delimiter=",", unpack=False) y = np.loadtxt("data/", comments="#", delimiter=",", unpack=False) W1 = np.loadtxt("data/", comments="#", delimiter=",", unpack=False) W2 = np.loadtxt("data/", comments="#", delimiter=",", unpack=False) # Display inputs sel = np.random.permutation(len(X)); sel = sel[0:100]; display.displayData(5, X, sel, 'TrainingData'); # Configuring settings of Neural Network: # # inputSize, hiddenSize, outputSize = number of elements # in input, hidden, and output layers # (optional) W1, W2 = random by default # (optional) maxiter = number of iterations you allow the # optimization algorithm. # By default, set to 20 # (optional) lambd = regularization penalty. By # default, set to 0.1 # NN.configureNN(400, 25, 10, W1 = W1, W2 = W2) # Training Neural Network on our data # This step takes 12 mins in or 20 sec on your # computer NN.train(X, y) # Saving Weights in the file NN.saveWeights() # Checking the accuracy of Neural Network sel = np.random.permutation(5000)[1:1000] NN.accuracy(X[sel], y[sel]) ``` **Now, you have to run this code either from:** * **** - but you would need to move code from `` into ``. Don't delete `` just yet. It would also take approximately 12 minutes to compute. You can watch [this]( Crash Course video while waiting :) * **Your own computer** - just run ``, which takes 20 sec on my laptop to compute. If you need help installing python, watch [this]( tutorial. ![trained]( ## **🔮 Part 4: Predicting!** By now, you are supposed to have your new weights (``,``) saved in `data` folder and the accuracy of your Neural Network should be over 90%. Let's now write a code to use the trained weights in order to predict the digits of any new image! ![giphy]( **Create a `` file and write the following code in there. Make sure to read the comments:** ```python import numpy as np import display from NN import Neural_Network NN = Neural_Network() # Loading data X = np.loadtxt("data/", comments="#", delimiter=",", unpack=False) y = np.loadtxt("data/", comments="#", delimiter=",", unpack=False) trW1 = np.loadtxt("data/", comments="#", delimiter=",", unpack=False) trW2 = np.loadtxt("data/", comments="#", delimiter=",", unpack=False) # Configuring settings of Neural Network: NN.configureNN(400, 25, 10, W1 = trW1, W2 = trW2) # Predicting a class number of given input testNo = 3402; # any number between 0 and 4999 to test NN.predictClass(X[testNo]) # Display output display.displayData(1, X, testNo, 'Predicted class: ' + str(np.argmax(np.round(NN.forward(X[testNo]))) + 1) ) ``` **Change the value of `testNo` to any number between 0 and 4999. In order to get a digit (class) prediction on the corresponding example from array X, run the code from:** * **** - but you would need to move code from `` into ``. Don't delete `` just yet. * **Your own computer** - just run ``. Yay, you are officially a data scientist! You have successfully: 1. Analyzed the data 2. Implemented the training of your Neural Network 3. Developed a code to predict new testing examples ![congrats]( ## **🚀 Acknowledgments** Hat tip to @shamdasani whose code I used as a template for Neural Network architecture and Andrew Ng from Stanford whose data I used. Plenty of things I told you are not completely correct because I rather tried to get you excited about the topic I am passionate about, not dump some math on you! If you guys seem to enjoy it, please follow through with studying machine learning because it is just an amazing experience. I encourage you to take [this free online course]( on it to learn the true way it works. Also, it's my first post here and I'd appreciate any feedback on it to get better. Keep me updated on your progress, ask any questions, and stay excited! ✨✨✨
posted by ArtemLaptiev1 (76) 9 months ago
A Good API for the Online Music Hackaton!
Yeah so I have been searching for an API to find lyrics and stuff that to make an app the the Hackaton... and Yes! I have found a good api! MusixMatch is surprisingly pretty Popular for music app developer! The Free plans are good to get you started with making the music app for the online hackaton! So hope this post helped you! Waddle on!
posted by optimistguy (21) 12 days ago
A Crash Course in LOLCODE 🐱
# A Crash Course in LOLCODE ___ OHAI! This is a crash course in the beautiful programming language known as LOLCODE! LOLCODE is a great language, and while it is similar to many other programming languages, trying to learn it may confuse some people because of the syntax. For this tutorial, any time I say `[variable1]`, `[variable2]`, or `[variable]`, as long as I'm not talking about initializing a variable, you can put a value instead. ### Creating a new program To begin a program, you need to have the line `HAI 1.2`. This will declare that it's a LOLCODE program that's written in LOLCODE 1.2. The last line in the program must be `KTHXBYE`. ### Comments There are two different ways of doing commenting - `BTW` and `OBTW`. The differences are shown below: ```lolcode BTW This is a one-line comment. OBTW This is a multi-line comment TLDR ``` The indentation is not necessary, but it makes it easier to read. ### Variables Variables are dynamically typed in LOLCODE, so you don't have to give them a type when declared. To declare a variable, use `I HAS A [variable]`. However, if you do want to give it a type, you can use `I HAS A [variable] ITZ A [type]`. There are 4 usable types of variables: - TROOF (a boolean - `WIN` or `FAIL`, corresponding to true or false.) - NUMBR (an integer - whole numbers) - NUMBAR (a float - decimal places) - YARN (a string - text, defined by "") Variable names are case-sensitive, so INT is different from Int. You can use capital and lowercase letters, underscores, and numbers - as long as neither underscores nor numbers begin the variable name. To assign one variable to another, use `[variable 1] R [variable 2]`. ### Concatenation It's very simple to concatenate YARNS in LOLCODE - you use `SMOOSH [variables to concatenate, seperated by AN] MKAY`. It will cast any input given to it to a YARN before concatenating. See below for an example. ```lolcode I HAS A VAR1 ITZ "Hi" I HAS A VAR2 ITZ 1234 I HAS A VAR3 ITZ WIN I HAS A VAR4 ITZ SMOOSH VAR1 AN VAR2 AN VAR3 MKAY VISIBLE VAR4 BTW The output will be Hi1234WIN ``` ### Casting There are a couple different ways of casting a variable from 1 type to another. The first is `MAEK [variable] A [type]`. This will attempt to cast from whatever type the variable is to the desired type. However, this will not work if it's illogical - for instance, trying to cast letters into a NUMBR or NUMBAR. To cast a variable to a different type and save the output in a different variable, use `[variable 1] R MAEK [variable 2] A [type]`. ### Expressions There are 3 different types of expressions in LOLCODE - **Math**, **Boolean**, and **Comparison**. The basic form for all expressions is either `[expression] [variable]` or `[expression] [variable1] AN [variable2]`. #### Math In LOLCODE, you have all the typical expression types - addition, subtraction, multiplication, division, and modulus (remainder), as well as some less-common ones - min (returns the value of the smaller of 2 variables) and max (returns the value of the larger of 2 variables). If either variable is a YARN and has a decimal, it is cast to a NUMBAR for the calculation. If it doesn't have a decimal, it's cast to a NUMBR. If both variables used are NUMBRs, then integer math is performed. If one or both are NUMBARS, floating floating point math is invoked. See below for a list of math expressions: ```lolcode SUM OF [variable 1] AN [variable 2] BTW This is addition DIFF OF [variable 1] AN [variable 2] BTW This is subtraction PRODUKT OF [variable 1] AN [variable 2] BTW This is multiplication QUOSHUNT OF [variable 1] AN [variable 2] BTW This is division MOD OF [variable 1] AN [variable 2] BTW This is modulus (remainder) BIGGR OF [variable 1] AN [variable 2] BTW This returns the bigger variable's value SMALLR OF [variable 1] AN [variable 2] BTW This returns the smaller variable's value ``` #### Boolean The boolean expressions work pretty much as you would expect, comparing WINs and FAILs. You can use and, or, xor, and not. Any value passed to this is cast to a TROOF. See below for the complete list: ```lolcode BOTH OF [variable 1] AN [variable 2] BTW This is an and statement EITHER OF [variable 1] AN [variable 2] BTW This is an or statement WON OF [variable 1] AN [variable 2] BTW This is an XOR statement NOT [variable] BTW This is a not statement ALL OF [variable 1] AN ... MKAY BTW This is an infinite and statement, keep adding variable names and ANs to check more ANY OF [variable 1] AN ... MKAY BTW This is an infinite or statement, see above ``` ### Comparisons This is very similar to boolean expressions - it takes in 2 variables and checks if they're either the same or different. However, it doesn't have to be 2 TROOFS, but they do have to be the same type. "9" and 9 will NOT be recognized as the same. See below for examples ```lolcode BOTH SAEM [variable 1] AN [variable 2] BTW returns WIN if variable 1 == variable 2 DIFFRINT [variable 1] AN [variable 2] BTW returns WIN if variable 1 != variable 2 BOTH SAEM [variable 1] AN BIGGR OF [variable 1] AN [variable 2] BTW variable 1 >= variable 2 BOTH SAEM [variable 1] AN SMALLR OF [variable 1] AN [variable 2] BTW variable 1 <= variable 2 DIFFRINT [variable 1] AN BIGGR OF [variable 1] AN [variable 2] BTW variable 1 < variable 2 DIFFRINT [variable 1] AN SMALLR OF [variable 1] AN [variable 2] BTW variable 1 > variable 2 ``` ### Printing To output text, you have to use the `VISIBLE [output]` command. This can also be used with variables by using `VISIBLE [variable]`. See below for examples: ```lolcode VISIBLE "Invisible" VISIBLE INT ``` ### Input To get input from the user, you can use `GIMMEH [variable]`. For this, you MUST specify a variable because that is where the output is stored. GIMMEH stores input as a YARN, so if you want to get a NUMBR or NUMBAR you have to cast it as such. ### Conditionals Creating conditionals is fairly straightforward in LOLCODE. There are 2 basic formats - one utilizing TROOFs, and one utilizing other types of variables. To create a conditional using TROOFs, use the following: ```lolcode [expression], O RLY? YA RLY BTW This code will execute if the result of [expression] is WIN NO WAI BTW This code will execute if the result of [expression] is FAIL OIC ``` To create a conditional using other variable types is a little more involved. Basically, `OMG [value]` is the same as checking if the expression is equal to [value], and `OMGWTF` is an else. To end a statement, you must put GTFO. ```lolcode [expression], WTF? OMG 5 BTW This code will execute if the result of [expression] is 5 GTFO OMG 91 OMG 21 BTW This code will execute if the result of [expression] is 91 or 21 GTFO OMGWTF BTW This code will execute if the result of [expression] is not 5, 91, or 21 OIC ``` ### Loops Loops are a somewhat confusing beast at first, but actually aren't that hard. First, you need `IM IN YR [label for the loop - I would recommend just calling it LOOP]`. Then, if you want to increase the iterator variable have `UPPIN YR [variable]`, and if you want to decrease the iterator variable have `NERFIN YR [variable]`. Finally, if you want to go until a certain value, use `TIL [expression]`, and if you want to go while a certain expression is true, use `WILE [expression]`. To end the loop, use `IM OUTTA YR [label]`. See below for an example: ```lolcode I HAS A ITERATOR ITZ 0 IM IN YR LOOP UPPIN YR ITERATOR TIL BOTH SAEM ITERATOR AN 9 VISIBLE ITERATOR IM OUTTA YR LOOP BTW This will output 0 through 8, and then stop before printing 9. ``` ### Conclusion Aaaand that's pretty much everything I could possibly find on the internet about LOLCODE... There is documentation for functions and BUKKITs (arrays), but I couldn't get them to work and so I decided against detailing them. If you still want MOAR LOLCODE documentation, go [here](, [here](, or [here]( If you want a fairly simple random python with turtle spiral generator, go check out my tutorial for that [here]( If you want a super long tutorial about how to make your own game using only python with turtle graphics, go [here]( If you liked this tutorial, feel free to leave an upvote. Thanks! :)
posted by minermaniac447 (170) 9 months ago
A Quick Guide to Talk Markdown
Guys! In this quick tutorial, I'll be showing you how to make your posts pretty using Markdown styling! # Headers First we'll learn about headers. A header starts with a hash symbol `#` followed by a space: ```md # A header ``` Output: # A header Headers can be a variety of sizes. A smaller header starts with more hash symbols. The number of hash symbols can be 1 to 6: ```md #### A header with 4 hash symbols ``` Output: #### A header with 4 hash symbols Alternatively, you can also "underline" a text with `=` or `-` to produce headers ```md First header (Same as # First header) -------------- Second header (Same as ## Second header) =========== ``` ___ # Text Styles You can make *italic*, **bold** or ~~strikethrough~~ text. Put the text between a pair of `*` or `_` to make it *italic*. ```md *italic text* _also italic_ ``` Output: *italic text* _also italic_ Put two `*` or `_` on both sides of text to make it **bold**. ```md **bold text** __also bold__ ``` Output: **bold text** __also bold__ You can also do a ~~strikethrough~~ by putting two tildes (`~`) on each side: ```md ~~strikethrough~~ ``` Output: ~~strikethrough~~ It's ok to mix up those stylings: ```md **_~~bold, italic and strikethrough~~_** ``` Output: **_~~bold, italic and strikethrough~~_** ___ # Lists There's two kind of lists in Markdown: **unordered** (bulleted) and **ordered** (numbered). Since talk Markdown doesn't support ordered lists (sadly), we'll only deal with unordered lists. An unordered list item starts with either a `*`, `+` or `-` followed by a space: ```md * this + that - and stuff ``` Output: * this + that - and stuff Use indentations of 2 spaces to make sublists ```md * list item * sublist item * yet another sublist item ``` Output: * list item * sublist item * yet another sublist item ___ # Links Just paste the URL and it'll work: ```md ``` Output: If you want **custom link text**, try this: `[link text](URL)`: ```md []( ``` Output: []( ___ # Images The Markdown syntax for **images** is pretty simple: `![alt text](URL)`: ```md ![ logo]( ``` Output: ![ logo]( **Wait... what if my image is stored in my computer? It doesn't have a URL!** Well, provided an easy way to upload images. All you need is to click the **select files** button below to upload it. After that, you'll see the Markdown code for your image in the text box. ___ # Code And finally, code!! **Inline code** and **code blocks** are widely used in talk since talk is a platform for coders to share. Wrap a pair of **backticks** (`` ` ``) around text to make a span of code (inline code): ```md `$ node index.js` ``` Output: `$ node index.js` To indicate a block of code, put three backticks (` ``` `) at both the start and end of your code: ````md ``` This is a code block. Everything here is monospaced. ``` ```` Output: ``` This is a code block. Everything here is monospaced. ```` Additionally, supports code block syntax highlighting, which is pretty useful for emphasizing readability. Just put the language name (or its short form) after the three backticks: ````md ```js while (true) console.log("MARKDOWN IS AWESOME!!!"); ``` ```` Output: ```js while (true) console.log("MARKDOWN IS AWESOME!!!"); ``` ___ # Blockquotes To do blockquotes put a `>` before each line of the block: ```md > Timchen is the greatest and > we should praise him ``` Output: > Timchen is the greatest and > we should praise him Don't forgot to leave a blank line after each blockquote! ___ # Horzontal rules A horzontal rule (a line that separates content) can be made of either three asterisks (`*`) or underscores (`_`): ```md There's a horizontal rule below *** There's a horizontal rule above ``` Output: There's a horizontal rule below *** There's a horizontal rule above That's all what I can teach in this very tutorial. Start using Markdown to style your posts, and find more about it!
posted by JSer (1088) 9 months ago
Make your first Pygame 🎮
## Make games the easy way, and forget about the setup 😌 ![]( [Demo + Code]( ⏯️ 👨‍💻 I've heard coding in python is quite delightful! And I agreed once I made my first python app that didn't just run on the terminal - a game made with [Pygame]( You'd usually have to spend a while getting set up, installing Pygame, dependencies and then have to spend time compiling an executable before sharing your game. But with [replit's new GFX system]( - there's absolutely no need for that ✌️ This is a tutorial to get started with Pygame, and make a simple game within 30 minutes! ## 🛠️ Getting our environment running Head over to []( and once you're logged in, hit `new repl → Pygame` to create the repl where we're going to be making our game. ![]( That's it 😉 ## 🎲 Understanding the game Before we start coding, let's understand what we're making 🛠️ Our game concept is pretty straightforward - there's a paddle - a simple rectangle that moves left or right in the screen, attempting to catch balls falling from the top of the screen. A higher score is more number of balls caught ⚾ ## 👨‍💻 Initializing pygame You can go right ahead and paste this code in your repl! ```python # adding libraries we're going to use import pygame from random import randint pygame.init() # initializing variables to account for the number of balls caught, and total dropped score = 0 total = 0 myfont = pygame.font.SysFont('monospace', 50) # creating a font to write the score in # Making dictionaries with settings for everything. display = { "width": 800, "height": 600 } paddle = { "width": 200, "height": 20, "x": 300, "y": 580, "velocity": 10 } ball = { "radius": 15, "y": 30, "x": randint(0, display["width"]), "velocity": 20 } # creating a window, and launching our game win = pygame.display.set_mode((display["width"], display["height"])) # 800 width, 600 height ``` I've added comments to explain what each line does 😄 Make sure to paste in the dictionaries too, they'll be super useful soon! ## 👾 The paddle Our paddle is going to be just a little rectangle that moves when we hit the arrow keys. Before we can start making it, we need to create the main loop. Pygame will run the code inside this loop continuously, to update the screen based on inputs. Paste all this in! ```python while True: pygame.time.delay(100) win.fill((255, 255, 255)) for event in pygame.event.get(): if event.type == pygame.QUIT: break keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: paddle["x"] -= paddle["velocity"] if keys[pygame.K_RIGHT]: paddle["x"] += paddle["velocity"] pygame.draw.rect(win, (255, 0, 0), (paddle["x"], paddle["y"], paddle["width"], paddle["height"])) pygame.display.update() ``` ​ ```python pygame.quit() ``` Don't worry, I'm not just going to leave you like that xD Let's break this up into smaller blocks to explain what everything does! Let's talk about everything inside the while loop, which will run forever - since `True` will always remain `True` 😮 ```python pygame.time.delay(100) win.fill((255, 255, 255)) ``` We're adding the delay so that the loop doesn't run too often, and there's some gap between each cycle - keeping our repl from crashing. `100` is delay in milliseconds, causing the loop to run 10 times a second. `win.fill()` takes a color in `RGB` as it's argument - and `255, 255, 255` represents white, filling our window with white before we draw anything onto it 🖌️ ```python for event in pygame.event.get(): if event.type == pygame.QUIT: break ``` This piece of code goes over all events that pygame gives us, and breaks the loop if Pygame has been quit. When the loop breaks, we go to the line which says `pygame.quit()`- you know what that does 😛 ```python keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: paddle["x"] -= paddle["velocity"] if keys[pygame.K_RIGHT]: paddle["x"] += paddle["velocity"] ``` To get this - lets first clear out our understanding about the coordinate grid - it doesn't start at the center in pygame! In fact, the top left corner is `0, 0` and `x` increases as you go right, while `y` increases as you move down. This block of code gets all currently pressed keys, and checks whether the left or right keys are pressed. If they are, it changes the `x` coordinates of the paddle - reducing if ⬅️ is pressed, and increasing if ➡️ is pressed by the velocity we set in the `paddle` dictionary. Try changing the `velocity` to see what happens 🤔 ```python pygame.draw.rect(win, (255, 0, 0), (paddle["x"], paddle["y"], paddle["width"], paddle["height"])) pygame.display.update() ``` This is where we actually draw our paddle to the screen - in the window called `win`, red in color (`255, 0, 0` RGB) - at `paddle[x]` on the x axis, and `paddle[y]` on the y axis. We've also set the width and height in the `paddle` dictionary, feel free to mess around with it! Finally, `pygame.display.update()` updates the entire screen with what we've drawn in this cycle of the loop! Try running the code, and hitting the left and right arrow keys! You should see a little rectangle moving around 👇 ![]( ## ⚽ Generating falling circles Let's bring up the `ball` dictionary up again 👇 ```python ball = { "radius": 15, "y": 30, "x": randint(0, display["width"]), "velocity": 20 } ``` What does the `"x"` line do? We're selecting a random x co-ordinate between `0` and `display["width"]` (currently 800) - using the `randint` function we imported right at the start of our code. Add this inside your while loop, right before you draw the paddle to the screen: ```python ball["y"] += ball["velocity"], (0, 0, 255), (ball["x"], ball["y"]), ball["radius"]) ``` We're increasing the y co-ordinate of the ball by its `velocity` and drawing the ball again in every cycle of the loop. ## 🏆 When do you actually score a point, though? The final part of our game would be checking if the ball hits the paddle when it's at the bottom of the screen. Collision detection is going to be essential to most of the games you're going to make in the future, so let's go over it here! ```python if ball["y"] + ball["radius"] >= paddle["y"]: if ball["x"] > paddle["x"] and ball["x"] < paddle["x"] + paddle["width"]: score += 1 total += 1 ball["y"] = 0 ball["x"] = randint(0, display["width"]) ``` First up, we're learning if the ball has hit the level of the paddle - by checking if the ball's radius + it's position on the y axis is equal to the position of the paddle. ```python if ball["x"] > paddle["x"] and ball["x"] < paddle["x"] + paddle["width"] ``` With this long condition, we're testing if - The ball's position on the X axis is greater than the paddle's position on the X axis AND - The ball's position on the X axis is lesser than the sum of the paddle's position on the X axis and its width If this condition is true, it means that the ball has landed on the paddle, and we increase the score 🙌 Maybe this image helps a bit 🤞 ![]( After this, regardless of whether a point has beens scored or not, we add one to the total number of balls landed - and reset the ball's position, setting the ball's y co-ordinate to 0, and generate a random position for the X axis. Lastly, we're going to write the score on the screen 🏅 ```python textsurface = myfont.render("score: {0}/{1}".format(score, total), False, (0, 0, 0)) win.blit(textsurface, (10, 10)) ``` We create a new [surface]( where we write the text using python's [format]( function, replacing `{0}` with the socre, and `{1}` with the total. We're writing this in black (`0, 0, 0` RGB). `win.blit(textsurface, (10, 10))` merges the text with the main window, at co-ordinates `10, 10`. And that's the game - the full thing 🤯 ## 🔮 Things to try - Changing the contents of the dictionary and seeing what happens ❓ - Make multiple balls fall at the same time 🔴 🔵 ⚫ - Make the paddle move up and down too 🚀 - Adding poison balls - the game stops when your paddle hits one 😵 Be sure to put down any questions or improvements down in the comments 💬 And here's all the code for you to go over again - I highly recommend going through this to help you understand the flow of the program, and the sequencing of everything if you were even a little confused by this guide 😅
posted by jajoosam (543) 4 months ago
JavaScript's Intersection Observers
# JavaScript's Intersection Observers JavaScript's [intersection observers]( are pretty cool. They let you test if some DOM element is intersecting another DOM element. ## Concept There are two words you might want to know when dealing with Intersection Observers. The *root* element and the *target* element. I think it's easiest to show you the difference: First example: ![image]( Second example: ![image]( As you may have concluded, you usually want the target element to be a descendent of the root element. And the root element can be another DOM element, or the browser's viewport. You can think of the root element as "watching" to see if any child elements are intersecting it. For the second example, your code might look like the following ```html <body> <div id="root-element"> <div id="target-element"></div> </div> </body> ``` The root element *must* be an ancestor of the target element. So, you **cannot** have something that looks like the following ```html <!-- you cannot use intersection observers with this html --> <body> <div id="root-element"></div> <div id="target-element"></div> </body> ``` ## Creating the Intersection Observer Here is an example (I'll break it down step by step right underneath). ```js let player = document.getElementById("player"); let options = { root: document.getElementById("main"), threshold: 0 // when 50% of the target element is inside of the root element, that is when the callback fires }; let callback = function(entries, observer) { console.log(`The target element is intersecting with the root element. The threshhold ratio is ${options.threshold}.`) }; let observer = new IntersectionObserver(callback, options); // The root element is observing one element (player) observer.observe(player); ``` To create new Intersection Observer (`observer`), you must specify two things - `callback`, the function to invoke when your elements intersect - `options`, some options to change the behavior of the Intersection Observer After you create the Intersection Observer, you can then observe any other elements you want. In the example above, I am only observing the `player` element. (`observer.observe(player)`) ### Options When creating your Intersection Observer `options`, you can specify what the root object is and the threshold. (see [MDN]( for more properties you can add) ```js let options = { root: null threshold: .5 // when 50% of the target element is inside of the root element, that is when the callback fires }; ``` - If the `root` property is `null`, then your root element is the viewport (like in the first visual example I showed). - When creating the `threshold`, as yourself this question: "How much do I want the *target* element to be inside the *root* element for the callback function to execute?" ## Thresholds The following shows a threshold of `0`. 0% of the target element is inside the root element. So in this case, 0% of the target element must be in the root element for the callback function to execute. ![InkedScreenshot_46_LI]( The following shows a threshold of `.5`. 50% of the target element is inside the root element. In this case, 50% of the target element must be in the root element for the callback function to execute. ![InkedScreenshot_44_LI]( The following shows a threshold of `1`. 100% of the target element is inside the root element. And in this case, 100% of the target element must be in the root element for the callback function to execute. ![InkedScreenshot_45_LI]( ### Callback The callback function executes every time an intersection occurs. From here you have access to two variables: `entries` and `observer`. ```js let callback = function(entries, observer) { console.log(`The target element is intersecting with the root element. The threshhold ratio is ${options.threshold}.`) }; ``` - `entries` gives you an array of the DOM elements you are observing. *However*, note that each array element is an `IntersectionObserverEntry`. From this object, you can extract where the DOM element is, or how much the DOM elements are intersecting. Learn more about `IntersectionObserverEntry`s on the [MDN Docs]( If you want to check out some example of using IntersectionObservers, I have a repl [here]( that uses the viewport as the root element and [another one]( that uses a DOM element as the root element. The latter is interactive, so you can move the squares around with the 'wasd' keys. I hope this tutorial was useful! Let me know what you think and post a comment!
posted by eankeen (529) 19 days ago
How to use a custom domain
In case you've worked with before, you may have noticed that you are given a decently long subdomain for your project, like the following: `` You may have wanted to change that into a shorter, more memorable domain name, like this: `` Let's see how. ## Getting your domain This section will cover registering a domain name with Freenom. If you already have a domain, [skip this part]( ### A word on Freenom #### You don't own it Freenom hands a selection of domain names out like free candy. If you've heard of, it's these guys. In this tutorial I'll walk you through them, but I'd also like to point out that by registering a domain name with Freenom, you are still not entitled to it. It's perfectly valid and legal for them to all of a sudden deactivate your domain and use it to make money with ads, without notification. This is just a fair warning, some people have had domains from Freenom for a long time without any issues, but anything can happen. In short, nothing could be actually free. You are borrowing Freenom's domains for your purposes, and don't own them like you would from another registrar. #### HTTPS ~~If you use Freenom, you won't be able to use HTTPS. You need to use "http://" before your domain instead. You will still be able to use your domain name if you need to use HTTPS, so make note of that.~~ **As pointed out, HTTPS does work with a Freenom domain! You just need to wait a little bit of time for it to get set up.** As for "mission critical" applications, like, say, Uptime Robot or something like that, you will probably want to use your domain. ### Registering the domain You will want to make or log into a Freenom account first. Then, you will be brought to the [Client Area]( Once you're signed in, you will find "Register a New Domain" under the Services menu. ![image]( This will bring you to Freenom's domain search. Type in the name you want. In this example, I searched for "mylittleblog". It will give you a list of what domains they have available. ![image]( Choose the one you want, then scroll down to the bottom and choose "Checkout". Don't touch the section in the middle, we'll cover that later. Choose the period you'll be using the domain, which is from 3 months to 12 months. (If memory serves, when you're going close to the due date, you are offered the opportunity to renew.) ![image]( Check the box to agree to the Terms and Conditions (reading them is a good idea too) and complete the order. Then, go back to your client area. ## Attaching to ### setup Go to your repl and click on the pencil icon next to the address in the preview pane. ![image]( Type in your domain name and if the domain is registered correctly, it will prompt you to add a `CNAME` record to your domain: ![image]( Copy where the record should point to, then go to your client area at your registrar (in my case, Freenom). ### Registrar setup From [My Domains](, go to the management page for the domain you chose. From Management Tools, choose Nameservers. Make sure it is checked to use default nameservers. ![image]( Then, find the area where you can add records; for Freenom, it is "Manage Freenom DNS". In the Name textbox, enter your domain name, nothing more, nothing less. Change the type to `CNAME`. Then, set the target to what asked you. Then, choose Save Changes. ![image]( ### Finish Now go back to your repl. now should have noticed that your domain is set up correctly and now lets you click on the Link button. ![image]( You're done! Your domain should now be attached to your repl.
posted by dotcomboom (54) 8 months ago
Build your very own URL shortener 🔗🚀
## Build a tiny URL shortener, using a remote database ![]( [Demo]( ⏯️ [Code]( 👨‍💻 Setting up a URL shortener is a lot of work - either you have to pay, or spend hours setting up your own server. This is a guide to making your own URL shortener with []( - using `express`, and a remote database - all on `node.js` ## 🛠️ Getting our environment running First up, fork the []( repl, so that you have a running project. Next, create a new file - `.env` ![]( A `.env` file can store secrets for you, that no one else will be able to see. This is where we want to store our token for accessing the remote database. ## 📁 Making our database We're going to be using []( for storing all our URLs. Head over to []( - and copy the token you see - this is the secret we want to store in our `.env` file. Open up your `.env` file, and set `KEY` to your token, like this 👇 ```bash KEY=yourTokenGoesHere ``` Remember to keep **no whitespace**, or your token might not be recognized right! When you open `index.js` you'll see that I've already initialized the database, and a small web server for you. Now let's get to making our API so we can shorten them URLs 🚀 ## 👨‍💻 The API There are two parts to our URL shortener: 1. Storing the short link, corresponding to the long URL - in our database. 2. Redirecting visitors from the short link to the long link Both of these are super simple to implement, thanks to the `express` server we're using - we'll just be collecting `get` requests for both of the tasks. For adding links to our database, we have a special endpoint - requests to it have two parts: the long URL, and the short path. ```javascript app.get('/shorten', (req, res) => { db.write(req.query.key, {"url": req.query.url}); res.status(200); }); ``` Adding this to our code lets us correspond the short path (`key`) to the long `url`, and then we finally send a successful response. For the second task, we'll just be collecting the short path (`key`) from a request, finding the corresponding URL in our database, and then redirecting our visitor ⬇️ ```javascript app.get('/:key', (req, res) => { + "/url").then( (url) => { res.redirect(url); }); }); ``` That's prety much it - we have a fully functional URL shortener 🤯 - check it out for yourself, open a new URL which looks like this 🔗 ``` ``` Now, going to [``]( will be nice to see 👇 ![]( Of course, you'll be replacing `tyni.jajoosam` in those URLs with your own repl! ## ✨ The Frontend Our URL shortener does work, but it's tedious, having to type out a huge URL before shortening it - we can make the whole process much simpler with a simple frontend. I've already created this - and gone for a neat and minimal look using [wing.css]( ![]( You just have to add code to send visitors to the hompage in the `static` folder 🏠 ```javascript app.get('/', (req, res) => { res.sendFile("static/index.html", {root: __dirname});; }); ``` If you browse through the `static` folder, you'll find a simple `HTML` file with a form, `CSS` to style our page, and most importantly, `JS` to send requests to our URL shortening API. The `HTML` is quite straightforward, we're asking for the long URL, and *optionally* a short path. Open up `script.js` and you'll see the `shorten()` function. Here's what the JS file does (*I've also annotated the code with comments*) 👇 🔍 Getting the path(`key`) and the long `url` from the form. 📝 Possibly generating a random 5 character hash as our path (in case there's no path entered) 🔗 Sending a get request to our API, with our `key` and `url` as parameters 🖥️ Displaying the shortened URL on our page ## 🌐 Getting our custom domain Sure, our links are shorter - but we still don't have them on our own domain, and the `` links can be pretty long 👀 Luckily for us, the folks at []( recently allowed custom domains to be used! That means this project could be something you actually use all the time 😄 Check out `dotcomboom`'s guide on [using custom domains](, it should only take a few minutes. It also teaches you about getting free domains 💸 Be sure to put down any questions or improvements down in the comments 💬 - and here's all the code for you to go over again 🤖
posted by jajoosam (543) 7 months ago
Making a discord bot with disco-py (not!)
# Creating a discord bot with disco-py This is **not** a tutorial! This is a tutorial for a discord bot library that I prefer, and made by one of discord's own developers! [disco-py]( ## Getting Started First, let's create a [python3 repl]( We're going to create a requirements.txt file, can put the following text inside it. ``` disco-py flask ``` will look to this file for external dependencies, disco-py for bot obviously, and flask, if you want to use uptimerobot. Then we're also going to create a folder for the plugins called `plugins`. Plugins are exactly like's cogs, it's just a set of commands grouped together, that can be loaded / unloaded. By now you should have created a bot application [here](, and you can now copy the bot's token. Now create a `.env` file, and write ``` token=<token here> ``` `.env` files are special on, as other people can't see them. will load these files on startup and create environment variables. Alright, now time to write some code! ## Creating a plugin! Let's create a file in the plugin folder called `` (`plugins/`) and create the class that will hold all the commands / listeners. ```python from import Plugin class HelloPlug(Plugin): ... ``` We'll get into loading the plugins later (For those of you that've used, you'll notice there's no function like `setup` to add the plugin. That's because disco-py doesn't need one.) Let's create a command that says hello to us. ```python from import Plugin class HelloPlug(Plugin): @Plugin.command("hello", "<name:str...>") def hello(self, event, name: str): event.msg.reply(f"Hello {name}!") ``` Ok, let's break down all this code. First we use `@Plugin.command` to tell disco that this function is a command. The first argument we pass into that in the name of the command that people will use to invoke the command. The second argument specifies what information the command requires. The syntax is pretty simple, however it requires an explanation. * The `<` `>` characters specify that this argument is required. If I had used `[``]`, it would have been optional. * `name:str` tells disco-py to pass the value provide into the function's `name` argument. the `str` tells disco-py to cast the value to a string, if it's not already. * The `...` tells disco-py to match the whole input. Without this, if someone did `!hello Johny Jenkins`, name would only be `Johny`. * `command("add", "<num1:int> <num2:int>")` will match `!add 5 4` * `command("kick", "<user:str> <reason:str...>")` will match `!kick Johny Called me ugly` * **Pro Tip:** You cannot use `...` if it's not the last argument. As you can see, an `event` variable is provided, this will contain information on the event, and exposes things such as * event.msg * * * event.guild In this case, we want to send a message back in the same channel, so we can do `event.msg.reply` for that. If you've used, you'll notice we're not using async / await. That's because disco-py uses the (arguably better) gevent lib. This means you can use packages such as requests, almost any database driver, and still be asynchronous! ## Running the bot Disco-py has a very different way of running bots, for better or worse. We're going to create a `config.json` file. Here we're going to put information like the prefix and plugin locations. The config.json actually stores a lot more information, but for right now that's all we'll need. ```json { "bot": { "plugins": [ "plugins.hello" ], "commands_prefix": "!" } } ``` You can copy paste this, it's pretty self-explanatory. Don't use `/` or `\\` paths to provide the location of the bot, instead use `.` like you're importing it. Now, disco bots must be run by the command line, but doing something like: ```bash python3 -m disco.cli --token <token here> ``` **Pro Tip**: Make sure you run this command in the same directory as the config file However that's quite inconvenient on Instead, we're going that some command in the file, like so: ```python from os import environ, system token = environ['token'] system("python3 -m disco.cli --token {token}".format(token=token)) ``` And at this point, we have everything we need! You can start the repl and everything should be ready to go! This is just a small part of disco-py. Sadly, the docs right now are quite lacking. That's why I'm going to continue to work on this tutorial, and expose all of disco's hidden treasures! You can view the complete bot here: ## Using it with uptimerobot (Optional) If you'd like to run your bot on, it's actually even easier with disco-py than disco-py has flask integration built right in, making it super easy to combine a website and discord bot. Let's return to the `` file, and add the following route to the Plugin class: ```python @Plugin.route("/") def index(self): return "Hello World" ``` If you've used flask before, this should look very familiar. All this code does is return the text `Hello World` when someone visits the website. Now we just have to edit the config, and add 2 pits of information flask requires. ```json { "bot": { "plugins": [ "plugins.hello" ], "commands_prefix": "!", "http_enabled": true } } ``` All we added was `"http_enabled": true` to tell disco-py that we're using flask. And just like that if you visit the repl's website it should say `Hello World`! See the link to the example bot above to see it in action. Thanks for reading! Hopefully you'll give disco-py a try. At first glace it's not much, but I promise you, it's much more complicated then that! Any feedback or questions are greatly appreciated!
posted by 21natzil (684) 2 months ago
🔵 Blogging on Replit with Hexo
# 🔵 Blogging on Replit with Hexo ![hexo logo]( If you've ever wanted to create a blog, you might have heard of static site generators like [Jekyll](, [Hugo](, and [Hexo]( In a nutshell, they transform any blog posts you've written in [markdown]( to a complete website. I'll show you how to get started with Hexo on replit. It's super simple. If you just want to fork a working example, see the repl below and follow the "*After forking*" steps. But if you want to follow along and create it yourself, follow the "*preliminary steps*" 😉. *You may have to fork the project if replit doesn't update files properly*. ### Prerequisites - Beginner experience with `npm` / `nodeJS` - Beginner experience with [markdown]( syntax ## Preliminary Steps ### Installing Hexo First, create a NodeJS repl and install the `hexo` package. ![image]( After adding Hexo, make sure you click `run` so the `npm` dependencies download. ## Initializing a Hexo Project Open the terminal with Ctrl + Shft + P (or F1) (make sure the file editor window is selected while doing this). Then, make sure you have the Hexo package by typing ```bash ./node_modules/.bin/hexo ``` You should see something like this 👇 ![image]( On replit, we cannot install global `npm` dependencies. Because of this, we have to type `./node_modules/.bin/hexo` instead of `hexo` whenever we want to do some Hexo command. Once you know you have Hexo properly installed, initialize a Hexo project. I called it `public`, but it really doesn't matter what you call it. ```bash ./node_modules/.bin/hexo init public ``` Now, wait until the generated folders show up in the file tree. If the files never generate, you may want to consider forking my repl (which is down below), which has all the necessary files. ![image]( Now, move all of the folders inside of `public` to the parent directory. Lastly, delete the `public` folder. ### Editing the Hexo Configuration Before, you start, you gotta change a few things in the configuration file. ![image]( In your `_config.yml` edit the`url` and parameter. Be sure to change the `url` to the url that shows up in the website preview area (denoted by red arrow). ### Starting the Hexo Server Starting the Hexo server enables you to preview your website as you're editing it. To start it, just type the following in the shell ```bash ./node_modules/.bin/hexo server ``` It should look something like this 👇 ![image]( But you may notice one large problem with this method. If someone visits you're repl, they'll have to type `./node_modules/.bin/hexo server` just to see your blog. We can fix this by making our `index.js` file automatically invoke the command`./node_modules/.bin/hexo server` in the shell. That way, when the user clicks "start", they'll see your blog 😄 To do this, put the following in your `index.js` ```js // Starts Hexo Development Server let spawn = require('child_process').spawn; let run = (cmd, args) => { child = spawn(cmd, args); child.stdout.on('data', data => process.stdout.write(data.toString())); child.on('close', code => console.log(`Child process exited with code ${code}.`)); }; run('./node_modules/.bin/hexo', ['server']); ``` Basically, this code creates a function called `run` with the arguments `cmd` and `args`. In this `run` function, a child process is spawned. Think of this child process as some process that's running a command (ex. `./node_modules/.bin/hexo server`). Whenever the process has received some `data` it logs it to the console. When the process `close`s, it logs that event to the console also. Now, after clicking on "run", your development server will start 😄. Be sure to refresh the site every time you want to make changes! Now read "*Using Hexo*" for more information. ## After Forking After you've forked my repl, you've basically almost done. Now, just change the `url` parameter in the `_config.yml` file so it matches yours. ![noimage]( Now you can start writing a blog! Hit "run" to start your blog and refresh the page every time you want your changes to show! Now read [Using Hexo](## Using Hexo) for more information. ## Using Hexo There are a few commands you'll want to know when editing or updating your blog. ### Starting the development server ```bash ./node_modules/.bin/hexo server ``` This starts the development server. If you followed this tutorial, you shouldn't have to type it in via the command line interface. Also, whenever you refresh the page, the website will automatically update. This is because replit automatically saves your files after you finish typing. ### Creating a new page ``` ./node_modules/.bin/hexo new <layout> <title> ``` For example, you can create a new post with the following ```bash ./node_modules/.bin/hexo new post "My Hexo Post" ``` However, sometimes, the posts you create within the shell won't pop up in the replit file viewer. As a workaround (for example), I 1. Create a post using the shell with `./node_modules/.bin/hexo new post "Sample Post"`. Then, I output the contents of the file with `cat ~/source/_posts/` 2. Create the actual markdown file inside of `source/_posts/` 3. Copy the output of what you got in step 1, and paste it in the text editor You can see the steps laid out below 👇 ![image]( If you want to learn more, check out the official Hexo [docs]( ### See the repl here 👇 I hope this tutorial helped you out 🙂
posted by eankeen (529) 3 months ago
Game Tutorial: Canyon Runner
Hey everyone, I made a canyon runner game ( and wrote up a tutorial for it here: Hope you like it!
posted by ericqweinstein (194) 11 months ago
3D graphics, a beginners mind.
# Preface In this tutorial I would like to show how 3d graphics is done today, why it's important, and how it will change the way you see 3d graphics applications. To better understand, we'll end up creating a 3d engine with Python. # Requirements I expect you to be familiar with Python, if you understand what `class` means you're probably qualified in this department. I also expect you to understand what the terms fov (field of view), vertex, mesh..etc. mean. # But 3d graphics is hard! No, it's not. This is an awesome area of programming you'll be able to show to your friends, there *will* be math(s) involved, so strap in, but it'll all be explained. If there are aspects you do not understand, simply copy my solution. # Fundamentals To start, let's go through the basic building blocks. Imagine we have a simple object, a cube. ![blender_2018-10-24_10-42-00]( There's more going on under the hood, this cube is made up of two things, *vertexes* and *triangles*. Vertexes are essentially points in 3d space. Look around your room, and imagine a speck of dust, a single point in 3d space. Triangles are, well just triangles, normal 2d flat triangles. However their three points are connected to specific vertexes. Let's look at the vertexes. ![blender_2018-10-24_10-43-32]( On the above image of a cube, you can see there are eight points, these are the points which make up the cube. In memory, these points each have a 3d coordinate: X, Y, Z axis. however when we go to *render* the cube, we map each 3d coordinate to 2d screen space. And the way we do that is surprisingly simple. Next, let's look at the triangles. ![blender_2018-10-24_10-43-33]( As you can see, a triangle is now connected to three of the points. Do this 12(*) times and you'll get a cube. *: A cube is made up of 6 faces, however to make a face with a triangle, you must use two triangles, so it ends up being 12 triangles. # Enough "fundamentals", more coding! Alright, now that we understand the basic structure for rendering 3d shapes. Let's get more technical. We'll be doing this in `Python (with Turtle)`. First, we import Turtle, I will assume you already know how to use Turtle and are familiar with it's functionality. In short, it's just a graphics library aimed at kids learning how to code with graphics, and making flowers and all sorts of things... Except we'll be going much further than flowers. ```python import turtle ``` Next we need to store our object data. We need to store all our vertexes and triangles. ```python VERTEXES = [(-1, -1, -1), ( 1, -1, -1), ( 1, 1, -1), (-1, 1, -1), (-1, -1, 1), ( 1, -1, 1), ( 1, 1, 1), (-1, 1, 1)] TRIANGLES = [(0, 1, 2)] ``` For now, we only have one triangle connected to the first three points. # Our basic main loop We want to simulate a normal graphics library with turtle. Our program will follow this structure: ```python # Create turtle, pointer = turtle.Turtle() # Turn off move time, makes drawing instant, turtle.tracer(0, 0) pointer.up() while True: # Clear screen, pointer.clear() # Draw, # ... # Update, turtle.update() ``` # Rendering Alright, now we need to somehow map these 3d vertex coordinates to 2d screen coordinates. To do this, let's use the *Perspective Formula*. Before we dive into the details of what exactly this formula does, let's start with an observation. Place an object in front of you, for instance a cup. As you move away, the cup shrinks; now this is all very obvious, but it is an essential property of 3d space we must consider. When we're creating a 3d engine, what we're doing is simulating this observation. When we move away from our objects, that is - the Z axis, we're essentially *converging* the X and Y axis toward zero. Look at this front-view of a cube, you can see the back vertexes are closer to the center (zero). ![blender_2018-10-24_19-01-34]( # So what is this "formula"? ```python f = field_of_view / z screen_x = x * f screen_y = y * f ``` Where x, y, z are vertex coordinates. We can simplify this to: ```python f = fov / z sx, sy = x * f, y * f ``` Easy right? So let's add `FOV` at the top of the file: ```python FOV = 100 ``` # Drawing the points Let's iterate through each vertex: ```python # Draw, for vertex in VERTEXES: # Get the X, Y, Z coords out of the vertex iterator, x, y, z = vertex # Perspective formula, f = FOV / z sx, sy = x * f, y * f # Move to and draw point, pointer.goto(sx, sy) ``` What we get is: ![chrome_2018-10-24_19-45-21]( But where are our four other points from before? The ones behind? The issue is we're inside the cube, we need to move the camera out. # The camera Alright, I won't go into the camera in this tutorial, you can look at my repl at the bottom to see how to properly implement a 3d engine, but we're taking baby steps here. When we think of moving the camera, we think of the camera object moving, simple right? Well that's not easy to implement in a rasterized renderer. However what's easier is to move the *world* around it. Think about it, either you can move the camera, or move the world; it's the same effect. As it turns out, it's a lot easier to offset the vertex positions than somehow change the perspective formula to equate the position; it would be a whole lot more complex. So quickly solve this, let's move the camera out: ```python # Perspective formula, z += 5 f = FOV / z sx, sy = x * f, y * f ``` ![chrome_2018-10-24_19-52-05]( And adjust the `FOV` to say, `400`. ![chrome_2018-10-24_19-53-04]( Nice! # Drawing triangles To draw triangles, consider this code. By this point you should be able to understand it: ```python # Draw, for triangle in TRIANGLES: points = [] for vertex in triangle: # Get the X, Y, Z coords out of the vertex iterator, x, y, z = VERTEXES[vertex] print(x, y, z) # Perspective formula, z += 5 f = FOV / z sx, sy = x * f, y * f # Add point, points.append((sx, sy)) # Draw trangle, pointer.goto(points[0][0], points[0][1]) pointer.down() pointer.goto(points[1][0], points[1][1]) pointer.goto(points[2][0], points[2][1]) pointer.goto(points[0][0], points[0][1]) pointer.up() ``` # Rotation To rotate our object, we'll be using the *Rotation Matrix*. It sounds scary, right? If you're familiar with linear algebra, you should already know this, but the rotation matrix is commonly defined as: ``` [x'] = [cos(0), -sin(0)] [y'] = [sin(0), cos(0)] ``` *using `0` as theta* I won't go into detail of the matrix. If you're unfamiliar, feel free to either research or copy & paste. To implement this, we'll first need the `math` library: ```python from math import sin, cos ``` Let's make a function to rotate: ```python def rotate(x, y, r): s, c = sin(r), cos(r) return x * c - y * s, x * s + y * c ``` Then let's place this before we do our perspective formula calculations: ```python # Rotate, x, z = rotate(x, z, 1) ``` As you can see the triangle is now rotated: ![chrome_2018-10-24_20-21-51]( Let's make the rest of the triangles: ```python TRIANGLES = [ (0, 1, 2), (2, 3, 0), (0, 4, 5), (5, 1, 0), (0, 4, 3), (4, 7, 3), (5, 4, 7), (7, 6, 5), (7, 6, 3), (6, 2, 3), (5, 1, 2), (2, 6, 5) ] ``` ![chrome_2018-10-24_20-23-06]( Awesome! Let's initialize a counter at the start of the file: ```python counter = 0 ``` and increment this at the end of every loop: ```python # Update, turtle.update() counter += 0.025 ``` And replace our rotation function: ```python x, z = rotate(x, z, counter) ``` It's rotating, awesome! To rotate on the X, Y and Z axis: ```python x, z = rotate(x, z, counter) y, z = rotate(y, z, counter) x, y = rotate(x, y, counter) ``` We're done! # Complete code Before you read, I recommend you do read through the above, I know it's easier to just skip down to the bottom for the solutions. However, if you're here after reading through the above, feel free to post `Full read` in the comments as a token of my respect, and feel free to copy this code =) ```python from math import sin, cos import turtle VERTEXES = [(-1, -1, -1), ( 1, -1, -1), ( 1, 1, -1), (-1, 1, -1), (-1, -1, 1), ( 1, -1, 1), ( 1, 1, 1), (-1, 1, 1)] TRIANGLES = [ (0, 1, 2), (2, 3, 0), (0, 4, 5), (5, 1, 0), (0, 4, 3), (4, 7, 3), (5, 4, 7), (7, 6, 5), (7, 6, 3), (6, 2, 3), (5, 1, 2), (2, 6, 5) ] FOV = 400 # Create turtle, pointer = turtle.Turtle() # Turn off move time, makes drawing instant, turtle.tracer(0, 0) pointer.up() def rotate(x, y, r): s, c = sin(r), cos(r) return x * c - y * s, x * s + y * c counter = 0 while True: # Clear screen, pointer.clear() # Draw, for triangle in TRIANGLES: points = [] for vertex in triangle: # Get the X, Y, Z coords out of the vertex iterator, x, y, z = VERTEXES[vertex] # Rotate, x, z = rotate(x, z, counter) y, z = rotate(y, z, counter) x, y = rotate(x, y, counter) # Perspective formula, z += 5 f = FOV / z sx, sy = x * f, y * f # Add point, points.append((sx, sy)) # Draw trangle, pointer.goto(points[0][0], points[0][1]) pointer.down() pointer.goto(points[1][0], points[1][1]) pointer.goto(points[2][0], points[2][1]) pointer.goto(points[0][0], points[0][1]) pointer.up() # Update, turtle.update() counter += 0.025 ``` # Conclusion If you want to see an expanded and better written version: If there's demand I will perhaps dive into shading, lighting, culling, clipping and even texturing. If you've got any questions, fire away in the comments. Good luck!
posted by CoolqB (102) 9 months ago
Learning Web Development w/ Python Part 3
# Learning Web Development with Python and Django ## Part 3 _Thank you to @timmy_i_chen and @masfrost for sorting out the issue!_ ## Welcome! In [Part 1]( and [Part 2]( we learned how to use views and templates to create some basic pages on our web app. In the rest of the series, we will be creating our own **Web Forum app**, that allows users to post questions and other users to answer them. In this tutorial we will first cover how to split our large app into smaller apps, and then we will set up an external database for storing information. ## A New Basic Template In the previous parts, I have given you a basic Django template to start work with. However, this template is fairly limiting because it does not allow access to the **command line**. From now on, we will be using another template, which you can find [here]( This also fixes some other bugs that mean that normal Django repls cannot use external databases. Fork the repl, rename it to something like `Web Forum`, and let's begin! ### Running the repl Before, when using Django, we just had to click the `run` button in order to run. Now, we are presented with a prompt. To run the server, just press enter without typing anything, and you should get our familiar startup screen: ![image]( ----------------------------------------------------------------------------- Now we're ready to start. ## Apps So far, when creating our (very basic) websites, all of our files have been in the one folder - `main`. However, when you are running a large or complicated website, this can get very confusing and hard to work with. To fix this, Django has a built-in `startapp` function, that maks separating your code into separate **apps** very easy. For example, an online shop may have an app for: * Users - deals with logging on, password reset, e.t.c. * Shopping Cart - deals with adding/removing products from the cart. * Products - deals with displaying/updating products. The only problem is that `startapp` doesn't work with ### DIY startapp Fortunately, all the `startapp` command does is create some folders and write a minimal amount of code, so we can do the same fairly quickly. We are creating a web forum, so let's create an app called 'Posts'. * Create a folder (at the top level, i.e. outside the `main` folder) called `Posts` * Within `Posts`, create empty files for each of the following: * `` (2 underscores on either side of the `init`) * `` * `` * `` * `` * `` * Next, create a folder called `migrations` * Within `migrations`, add a file called `` (2 underscores on either side of the `init`) The sidebar on your project should now look like this: ![image]( (Or similar with the light theme) Now we need to add just a little bit of code. To `` add the following code: ```python from django.apps import AppConfig class PostsAppConfig(AppConfig): name = 'Posts' ``` You don't really need to know how this code works - basically all it does is create a configuration class to allow the app to be used by Django. ### Updating After you have created the app, you need to update the `` file in order for Django to be able to find the app. To do this, go to `` and change the `INSTALLED_APPS` list. ```python INSTALLED_APPS = [ # stuff 'Posts.apps.PostsAppConfig', 'main', ] ``` This links to the code that we put in `` above. ------------------------------------------------------------------------------- ## Pages within Apps Now we have made our app! Let's make a home page within the app. #### Template First, we create folder called templates, then add a file called `base.html` into that folder. This will be our base template. Add the following `html` to `base.html`: ```html <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock title %}</title> </head> <body> <nav> This will be the navbar. </nav> <div id="content"> {% block content %} {% endblock content %} </div> </body> </html> ``` You should be familiar with most of this - the only bits I haven't covered before are: * `nav` - this is a `html` navigation bar element. * `div` - this is a `html` element that surrounds a distinct area in the `html`. These will be needed because we will be using `CSS` later to apply styles to different sections of the page. Next, create a file called `home.html`, and the following `html`: ```html {% extends 'base.html' %} {% block title %}Home{% endblock title %} {% block content %} <h1>Home</h1> <p>Welcome to the home page!</p> {% endblock content %} ``` You should be comfortable with this - if you don't understand the `{% %}` tags, then look back at [Part 2]( #### View Now we need to create our view. In `Posts/`, add the following code: ```python from django.views.generic import TemplateView class HomePageView(TemplateView): template_name='home.html' ``` This is just a basic class-based view that will display the template that we created above. #### URL Finally, we need to map a URL to our view. This is slightly more complicated because our page is within the `Posts` app, but `` is in `main`. How do we solve this? The answer is that we create another `` file **within** `Posts`, then redirect the `main` `` to this file. Sounds complicated? It is actually quite simple - let's do it. Within `Posts`, create a file called ``, and add the following code: ```python from django.urls import path from .views import HomePageView urlpatterns = [ path('', HomePageView.as_view(), name='home'), ] ``` This is fairly simple to understand: the URL `''` (i.e. no URL) gives the home page - so if the domain was, then the home page would be located at Next, in `main/`, change the file to this: ```python from django.urls import path, include # include has been added from django.contrib import admin urlpatterns = [ path('admin/',, path('',include('Posts.urls')), # this has also been added ] ``` What does this do? We are importing the `include` function - this is used for redirecting to another file. So the new line we added just tells Django to check the `Posts.urls` file (that we created above). What about the first `''`? This can be confusing, but for example, if we changed the line to ```python path('hello/',include('Posts.urls')), ``` Then **all the URLs** in our `Posts/` file would be located at . We will use this later - all of our `user` URLs will be located at If you run the program now (by running the repl and pressing `enter` without typing anything in), you will see that our home page is where it should be! ![image]( ### `url` vs `path` You may have noticed that the last time we used Django URLs, we have a list of `url`s - like this: ```python urlpatterns = [ url('',blah), url('about',blah), ] ``` whereas now we are using `path` instead. `path` is the new version of `url`. `path` is better because it doesn't use regex which can be confusing for beginners, and it also makes writing some URLs easier and makes them more readable - especially for database-driven pages. ------------------------------------------------------------------------ ## Databases Databases are a way of storing data in a way that can be accessed easily, encrypted easily and changed easily. Django usually uses `sqlite3` databases by default - in fact, if you look in your file list at the side, you will see Django has automatically created a file called `db.sqlite3`. However, doesn't support databases - if you refresh your page, all your data is lost. For this reason, we are going to use an external database. ### Setting up our Database Now we are going to set up our external database. We will be using `postgresql`, because it is widely used and we can use it for free. We will be using [ElephantSQL]( to host our database. First, create an account [here]( Once you have done that, you should be faced with the following page: ![image]( Click on `Create a new Instance` and follow through all the instructions. You can just use a **Tiny Turtle** instance because it is free. You will be asked to select a region - just pick somewhere near you. Once you've done that, you will be redirected back to the `instances` page. Click on the instance that you just created and you should get a page like this: ![image]( (I've just greyed out the password so you aren't tempted to use my database and corrupt everything.) Now that the database host is ready, we can set up the database on Django! Go to `` and you will see a list called `DATABASES`. Change the list to look like this: ```python DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'Default Database', 'USER': 'User', 'PASSWORD': 'Password', 'HOST': 'Server', 'PORT': '' } } ``` Swap the text for the correct data that was given for the instance. For the server, you don't need the bit in brackets - so for my database, I can just set the server to ``. If you run this now, you get a long error: ![image]( This is because Django was expecting there to be some default tables in the database. To fix this, instead of pressing enter at the command line, type the following: ```bash > python migrate ``` This applies the changes to the database that Django wants there to be. And that's the database set up! If you run the server now (by just pressing `enter`), then it runs correctly and our home page is displayed! ## Conclusion Now that we have set up our database, we're ready to create some database-driven web pages! In [Part 4]( we will learn how to use databases with Django. Please upvote if you found this tutorial helpful, it supports me and lets me know that you want more! If you have any questions, post in the comments and I (or someone else) will answer them.
posted by ArchieMaclean (523) 3 months ago
How to draw Pixel Art on Python with Turtle!
# How to Draw Pixel Art on Python with Turtle! In this Tutorial you shall learn how to create your own pixel art on Python with Turtle, I hope you enjoy. The first step to creating our art is to import turtle and set a background. My personal tip is to use black as it works best with pixel art. Here is model code: ``` import turtle t=turtle.Turtle() wn=turtle.Screen() wn.bgcolor("Black") #Remember Speech Marks. ``` Then, for step 2, we will set the speed of your turtle to be a high value, using this command: ` t.speed(0) ` Then, now the technical aspects are over with, let us get into the real juicy code! First, we must define square. My optimum size after a lot of testing was a 20 by 20 square. You define a function using this piece of code: ``` def square(): for x in range(4): t.forward(20) t.right(90) #Remember Indentation. ``` Then, After that step, we can start making pixel art! To add colours to our squares, we use the begin_fill command. Let me show an example about how this works. ``` def Tetris_Piece_1(): for x in range(4): t.begin_fill() square() t.color("Blue") t.end_fill() t.color("Black") t.forward(20) ``` We created this function. Now we may uses it whenever we like with this command: ` Tetris_Piece_1(). ` This code will make a Horizontal line of 4 pixels, like the Tetris piece! Look at the example below to see Pac-Man also. You've come to the end of the Tutorial. However, if you would like to extend this, here are some ideas. Find a way to define Red_Square or Blue_Square. Make a video-game character. Create a model of a Tetris screen. It has lots of uses, so try it today. Remember to click on Python with Turtle and not python 2.7, Python or Django. I recommend you watch the example in larger screen by pressing Open in Special Credit to JSer for teaching me how to use markdown on this post! Up the pensize to 4 if you want it really blocky using this command! ` t.pensize(4) `
posted by John_WardWard (143) 9 months ago
Chromebooks Tutorial -> as an App.
# Chrome OS + Hello guys. So i have found out how to use as a chrome app. (Some of you may already know, others maybe not.) > You can do this with pretty much any website: ![image]( As you see i did with my own web and (My web is the fox one) ## Tutorial 1.Get to the website ( ![image]( 2. Press the chrome 3 dots. ![image]( 3. Press More tools and then click over "Create a shortcut" ![image]( 4. Check the checkbox that says 'Open as a window' ![image]( 5. Click ok and have fun coding! ![image]( Also, i made this post with the app :) ![Uploading image.png...]()
posted by IzanLarumbe (27) 2 months ago
6 Essential Python Libraries for Python Programming
Python is a high-level, general-purpose programming language that has become one of the leading names in the programming community. It ranges in the ability from developing simplistic applications to carrying out complex, mathematical calculations with an equal level of ease. Being one of the leading programming languages means that there is no scarcity of [great frameworks]( and libraries available to toy with. A programming language library is simply a set of modules and functions that eases some specific operations using the programming language. So, here are 6 essential Python libraries for Python programming that every Python developer or aspirant must know about: # 1. **Keras** _Type_ – Neural Networks Library _Initial Release_ – March 2015 Written in Python, Keras is an open-source neural-network library. Designed especially for enabling fast experimentation with deep neural networks, Keras prioritizes for being user-friendly, extensible, and modular. In addition to providing an easier mechanism for expressing neural networks, Keras also offers some of the best features for compiling models, processing datasets, and visualizing graphs. On the backend, Keras makes use of either Theano or TensorFlow. Due to the fact that Keras creates a computation graph by using backend infrastructure and then uses it to perform operations, it is slower than other machine learning libraries. Nonetheless, all models in Keras are portable. _<span style="text-decoration:underline;">Highlights</span>_: * Easy to debug and explore as it is completely written in Python * Features several implementations of the commonly used neural network building blocks such as activation functions, layers, objectives, and optimizers * Incredible expressiveness and flexibility makes it ideal for innovative research * Offers several pre-processed datasets and pre-trained models like Inception, MNIST, ResNet, SqueezeNet, and VGG * Provides support for almost all neural networks models, including convolutional, embedding, fully connected, pooling, and recurrent. Moreover, these models can be combined to develop even more complex models * Runs smoothly on both CPU as well as GPU _<span style="text-decoration:underline;">Applications</span>_: * Already used by Netflix, Square, Uber, and Yelp * For deep learning research. Adopted by researchers at CERN and NASA * Popular among startups developing products based on deep learning # 2. **NumPy** _Type_ – Technical Computing Library _Initial Release_ – 1995 (As Numeric) 2006 (As NumPy) NumPy was created by Travis Oliphant in 2005 by incorporating features of the rival Numarray library into the Numeric library and applying extensive modifications. The free and open-source library has several contributors from all over the globe. One of the most popular machine learning libraries in Python, TensorFlow and several other libraries make use of the NumPy Python library internally in order to perform multiple operations on tensors. _<span style="text-decoration:underline;">Highlights</span>_: * Active community support * Completely free and open source * Complex matrix operations, such as [matrix multiplication]( * Interactive and super easy to use * Eases complex mathematical implementations * Easy to code with digestible concepts _<span style="text-decoration:underline;">Applications</span>_: * For carrying out complex mathematical computations * For expressing images, sound waves, and other forms of binary raw streams as an array of real numbers in N-dimensional * For machine learning projects # 3. **Pillow** _Type_ – Image Processing and Manipulation Library _Initial Release_ – 1995 (As Python Imaging Library or PIL) 2011 (As Pillow) Pillow is a Python library that is almost as old as the programming language for which it was developed. In reality, Pillow is a fork for the PIL (Python Imaging Library). The free to use Python library is a must-have for opening, manipulating, and saving a diverse range of image files. Pillow has been adopted as the replacement for the original PIL in several Linux distributions, most notably Debian and Ubuntu. Nonetheless, it is available for MacOS and Windows too. _<span style="text-decoration:underline;">Highlights</span>_: * Adds text to images * Image enhancing and filtering, including blurring, brightness adjustment, contouring, and sharpening * Masking and transparency handling * Per-pixel manipulations * Provides support for a galore of image file formats, including BMP, GIF, JPEG, PNG, PPM, and TIFF. Provides support for creating new file decoders in order to expand the library of file formats accessible _<span style="text-decoration:underline;">Applications</span>_: * For image manipulation and processing # 4. **PYGLET** _Type_ – Game Development Library _Initial Release_ – April 2015 A multi-platform windowing and multimedia library for Python, PYGLET is a popular name when it comes to game development using Python. In addition to games, the library is developed for crafting visually rich applications. In addition to supporting windowing, PYGLET provides support for loading images and videos, playing sounds and music, OpenGL graphics, and user interface event handling. _<span style="text-decoration:underline;">Highlights</span>_: * Leverage multiple windows and multi-monitor desktops * Load images, sound, and video in almost all formats * No external dependencies and installation requirements * Provided under the BSD open-source license, therefore free to be used for personal as well as commercial uses * Provides support for both Python 2 and Python 3 _<span style="text-decoration:underline;">Applications</span>_: * For developing visually rich applications * For game development # 5. **Requests** _Type_ – HTTP Library _Initial Release_ – February 2011 A Python HTTP library, Requests is aimed at making HTTP requests simpler and more human-friendly. Developed by Kenneth Reitz and a few other contributors, Requests allows sending HTTP/1.1 requests without requiring human intervention. From Nike and Spotify to Amazon and Microsoft, dozens of big organizations make use of Requests internally to better deal with the HTTP. Written completely in Python, Requests is available as a free open-source library under the Apache2 License. _<span style="text-decoration:underline;">Highlights</span>_: * Automatic content decoding * Basic/digest authentication * Browser-style SSL verification * Chunked requests and connection timeouts * Provides support for .netrc and HTTP(S) proxy * Sessions with cookie persistence * Unicode response bodies _<span style="text-decoration:underline;">Applications</span>_: * Allows sending HTTP/1.1 requests using Python and add content such as headers, form data, and multipart files * For automatically adding query strings to URLs * For automatically form-encode the POST data # 6. **TensorFlow** _Type_ – Machine Learning Library _Initial Release_ – November 2015 TensorFlow is a free and open-source Python library meant to accomplish a range of dataflow and differentiable programming tasks. Although a symbolic math library, TensorFlow is one of the most widely used Python machine learning libraries. Developed by Google Brain for internal use, the library is used for both commercial and research purposes by the tech mogul. [Tensors]( are N-dimensional matrices that represent data. The TensorFlow library allows writing new algorithms involving a grand number of tensor operations. Because neural networks can be expressed as computational graphs, they can be easily implemented using the TensorFlow library as a series of operations on tensors. _<span style="text-decoration:underline;">Highlights</span>_: * Allows visualizing each and every part of the graph * Completely free and open source * Easily trainable on CPU and GPU for distributed computing * Humongous community support * Offers flexibility in its operability. Parts that are required the most can be made standalone * Supports training multiple neural networks and multiple GPUs to make efficient models on large-scale systems * Uses techniques to the likes of XLA for hastening linear algebra operations _<span style="text-decoration:underline;">Applications</span>_: * For machine learning projects * For neural networks projects * In automated image-captioning software like DeepDream * Machine learning in Google products, such as Google Photos and Google Voice Search That finishes the list of the 6 essential Python libraries for Python programming. Which libraries should/shouldn't have made it to the list? Let us know in your comments. Check out some of the [best Python tutorials]( now!
posted by VijaySingh1 (21) 4 months ago