Make a Game. Win a Bitcoin.

00
Days
00
Hours
00
Mins
00
Secs

Jam Ended on Apr 19. Results coming soon!

Learn to Code via Tutorials on Repl.it

Posts
1
Login System
I have created a login and register system in python 3, and I'm trying to do an if statement testing to see if the users login input matches the registered users in a separate file but it wont work! Any tips or help will be greatly appreciated! Code: https://repl.it/@OathOfCode/Login-system
0
posted by OathOfCode (0) 3 hours ago
1
In Introduction to Java
# Java Tutorial for Beginners This is a very fast tour of some basic `Java`. You should type everything in to a [Java repl](https://repl.it/languages/java), and try changing values to see what happens. You should know how to program in other languages - I'm assuming knowledge of a language like Python or JavaScript. ## Basics Java is OOP (Object-Oriented Programming) so everything must be in a class. The Java compiler will automatically run any code in the `main` method. ```java class Main { public static void main(String[] args) { // This is a comment // This will be run } } ``` In Java, blocks are defined with curly braces `{}` - indentation is not necessary, but improves readability. All lines in Java must end with either `;`, or `}` (where appropriate). You can print stuff to the screen using `System.out.println`. ```java class Main { public static void main(String[] args) { System.out.println("Hello, world!"); // => 'Hello, World!' } } ``` Mathematical operators are as follows: ```java class Main { public static void main(String[] args) { System.out.println(2+3); // addition System.out.println(2-3); //subtraction System.out.println(2*3); // multiplication System.out.println(2/3); // division - rounds down System.out.println(3%2); // modulus - remainder of division } } ``` ## Variables and Datatypes When declaring a variable in Java, use the suntax `variable_type variable_name;`. This declares an empty variable ```java class Main { public static void main(String[] args) { int num; num = 3; System.out.println(num); // Or, on one line int another_num = 3; System.out.println(another_num); } } ``` There are a few datatypes - here are the most common: ```java class Main { public static void main(String[] args) { // integers up to 2,147,483,647 int i = 3; // integers up to 9,223,372,036,854,775,807 long l = 314159265; // 64-bit floating-point number double d = 3.1415d; // 32-bit floating-point number (for saving memory) float f = 3.14f; // text String s = "Hello, World!"; // single character char c = 'a'; // true/false boolean b = false; } } ``` Arrays are when you assign multiple values to one variable name, e.g. `x = {1,2,3}`. The syntax is `type[] name = new type[length];` ```java class Main { public static void main(String[] args) { // integer array of length 10 int[] i = new int[10]; // access elements with 0-based index, i.e. first element is 0, second is 1 e.t.c. i[0] = 1; i[6] = 32; // another way of defining arrays int[] i2 = {1,2,3}; // use .length to find the length of the array System.out.println(i.length); System.out.println(i2.length); } } ``` The `String` datatype is basically an array of `char`s. ```java class Main { public static void main(String[] args) { char[] c = {'H','e','l','l','o'}; String s = new String(c); System.out.println(s); // .length() is used to find the length of a String System.out.println(s.length()); } } ``` For an array with variable length, you can use an `ArrayList` ```java import java.util.ArrayList; class Main { public static void main(String[] args) { ArrayList al = new ArrayList(); al.add('a'); al.add(3); al.add("Hi there!"); // pushes to 0 index al.add(0,"First"); System.out.println(al); System.out.println(al.size()); // => 4 // remove removes by index, not value al.remove(0); System.out.println(al.size()); // => 3 // also, you can set it to only 1 datatype ArrayList<String> sal = new ArrayList<String>(); sal.add("Hi"); sal.add(34); // fails because it is not String } } ``` `HashMaps` give each item a `key` and a `value` (also called Hashes, dicts or maps in other langs). ```java import java.util.HashMap; class Main { public static void main(String[] args) { // key is String, value is Integer // datatypes are different than normal // use Boolean, Character, Double for boolean,char,double HashMap<String, Integer> hm = new HashMap<String, Integer>(); hm.put("John",23); hm.put("Anne",17); System.out.println(hm); // use get to find a specific value System.out.println(hm.get("Anne")); hm.remove("Anne"); System.out.println(hm); } } ``` ## Control Flow Comparison operators are used to compare things. ```java class Main { public static void main(String[] args) { System.out.println(1==1); // equal to System.out.println(2>1); // greater than System.out.println(2<1); // less than System.out.println(1>=1); // greater than or equal to System.out.println(2<=1); // less than or equal to System.out.println(2!=1); // not equal to } } ``` Logical operators are ways of choosing based on `true`s and `false`s. ```java class Main { public static void main(String[] args) { // AND - true if both are true System.out.println(true && true); // OR - true if either are true System.out.println(true || false); // NOT - swaps true with false and vice versa System.out.println(!true); // XOR - true if either are true but not both System.out.println(true^false); System.out.println(true^true); } } ``` `If` statements do things depending on whether certain conditions are evaluated as `true` or `false`. ```java class Main { public static void main(String[] args) { // outputs "10 is greater than 5!" if (10>5) { System.out.println("10 is greater than 5!"); } else { System.out.println("10 is not greater than 5"); } int a = 10; // outputs "a is greater than 8" if (a<2) { System.out.println("a is less than 2"); } else if (a<8) { System.out.println("a is less than 8"); } else { System.out.println("a is greater than 8"); } } } ``` `for` loops are used to loop a fixed number of times. ```java class Main { public static void main(String[] args) { // loops 10 times, incrementing i by 1 each time // (i++) for (int i=0;i<10;i++) { System.out.println(i); } char[] c_array = {'a','b','c','d'}; // loos for each item in the array for (char c:c_array) { System.out.println(c); } } } ``` `while` loops continue looping until a certain criteria is met. ```java class Main { public static void main(String[] args) { int x = 3; // continues until x=6 // because then 6*4 == 24 while ((x*4)!=24) { System.out.println(x); x++; } } } ``` ## Classes and Methods Methods are another name for functions inside classes. ```java class Main { public static void main(String[] args) { sayHello(); String farewell = sayGoodbye(); System.out.println(farewell); System.out.println("3 is greater than 5: "+isGreaterThanFive(3)); System.out.println("10 is greater than 5: "+isGreaterThanFive(10)); } // public and static will be covered in a minute // void means the method doesn't return anything public static void sayHello() { System.out.println("Hello!"); } // String means that the method returns a String public static String sayGoodbye() { return "Goodbye!"; } // boolean so returns true/false public static boolean isGreaterThanFive(int n) { return (n>5); } } ``` A `class` is like a blueprint, with which you can make `objects` (`instances`). ```java class Main { public static void main(String[] args) { // create a new 'instance' of the dog class, called George Dog George = new Dog("George"); George.bark(); George.live(); George.eat(); // fails because eat() is private } } class Dog { // this is an attribute that all // of our Dog objects will have String name; // this is called the constructor // it is called when the dog is created public Dog(String name) { // this. means that name applies the this dog // it means that it's name can be used elsewhere // in the class this.name = name; System.out.println("A dog called "+this.name+" was just created!"); } // public means that it can be accessed by other classes public void bark() { System.out.println(this.name+" just said 'Woof!'"); } public void live() { this.eat(); } // private so cannot be accessed by other classes private void eat() { System.out.println(this.name+" is eating!"); } } ``` `static` methods can be referenced from a static setting. ```java class Main { public static void main(String[] args) { // create a new instance of the Shop class Shop Amazon = new Shop(); Amazon.buy(); // static, so we can just do this Shop.buy(); Amazon.showDetails(); // fails because it is not an instance // and the method is not static Shop.showDetails(); } } class Shop { // static so don't need to instantiate in order to // use the method public static void buy() { System.out.println("Buying!"); } public void showDetails() { System.out.println("You have to create a instance for this to work"); } } ``` ## Input The `Scanner` class is used to scan text. ```java import java.util.Scanner; import java.io.File; class Main { public static void main(String[] args) { // creates a new Scanner looking at the string "Hello World" Scanner input_reader = new Scanner("Hello World"); // outputs each word one at a time while (input_reader.hasNext()) { String input = input_reader.next(); System.out.println(input); } } } ``` You can use the `Scanner` class to read input from the keyboard. ```java import java.util.Scanner; class Main { public static void main(String[] args) { Scanner input_reader = new Scanner(System.in); System.out.println("Enter some text: "); String input = input_reader.nextLine(); System.out.println("You said: "+input); } } ``` ## Error Handling You can handle errors with `try..catch` ```java import java.lang.ArithmeticException; class Main { public static void main(String[] args) { try { System.out.println(1/0); } catch (ArithmeticException e) { System.out.println("Got error: "+e); } } } ``` ## Conclusion That was a quick look over some basic Java. You may want to re-read this to make sure you understand it all. Please upvote if you liked this tutorial, it helps support me :) **Suggested further topics**: * File reading/writing (may not work on repl.it) * Inner Classes * Inheritance * Interfaces * Packages
0
posted by ArchieMaclean (350) 11 hours ago
1
123
vyyfu
0
posted by PranavVashisht (0) 1 day ago
1
Learning Web Development w/ Python Part 4
# Learning Web Development with Python and Django ## Part 4 _[Part 1](https://repl.it/talk/learn/Learning-Web-Development-with-Python-Part-1/12880)_ ## Welcome! In [Part 3], we learnt about **apps**, and set up our external database on ElephantSQL. In this tutorial, we will learn how to use databases with Django to create our **Web Forum** app. ------------------------------------------------------------ In the last tutorial, we started our web app. You can use the same repl for this tutorial. ### Setting up Django Admin The first thing we need to do is to set up a Django admin account. This is an account that we can use to access the database on our website. Start the repl, and instead of just hitting `enter`, type: ```bash > python manage.py createsuperuser ``` You will be asked to enter a username and password - make sure that they are ones that you can remember! You do not have to enter your email if you don't want to. **Note:** when you enter your password, no text will appear. This is for privacy reasons - typing works normally, it is just not displayed. ![image](https://storage.googleapis.com/replit/images/1555585110853_94078fe923faee37dd7c918be516f5fd.pn) Now that you have created your admin account, you can run the server and open it in a new tab. To access your admin page, you need to add `/admin` to the end of your URL - so your URL should be https://repl-name--username.repl.co/admin Enter your login details that you just created, and you should be presented with the Django admin page: ![image](https://storage.googleapis.com/replit/images/1555585296705_422c1cc1efdfb4e034e637fddbc79570.pn) Now we are ready to start creating our database. ### What _is_ a database? Before we create our database, let's try to understand what a database actually is. You can visualise a database like a ~~Excel spreadsheet~~ Google sheet. ![image](https://storage.googleapis.com/replit/images/1555585582127_eb26f29b655ceb16d88bfb896de9b521.pn) A database is similar, but many features are re-named: * Sheet (e.g. People, Repls) becomes Entity (or table) * Column (e.g. First Name, Has A Pet?) becomes Attribute * Row (e.g. row 4) becomes Record In reality, the data is not stored like this, but this is a good way of thinking of it. Another key difference with a database is that each attribute in a database (column) has to be the same **data type**. Examples of data types are: text, datetime, number or boolean. Notice that these are not quite the same as data types in programming - e.g. a "string" is "text" in a database. In nearly all databases, a **primary key** is used. This is a _unique identifier_, i.e. an attribute that has a different value for every single record in the database. It is most often a number. Django adds a primary key by default, so we don't need to worry about including one when designing our entity. ### Creating our first Entity Let's create an entity to store information about each Post that is made to the web forum. Before creating your entity, it is good to make a plan about what attributes the entity should have. For this entity, some good attributes could be: * **title** - Title of post. Limited to 50 characters. * **text** - Content of the post. Not limited. * **author** - Creator of the post. Limited to 30 characters. * **date** - Date that post was created. Django creates and modifies entities using `models`. To see this in action, navigate to `Posts/models.py` and add the following code: ```python from django.db import models class Post(models.Model): title = models.CharField(max_length=50) text = models.TextField() author = models.CharField(max_length=30) date = models.DateTimeField(auto_now_add=True) ``` What does this code do? * On `Line 1`, we import `models`. This is a very handy module in Django that allows us to interface with databases very easily. * On `Line 3` we define our `Post` class. This is our database entity. It **inherits** from `models.Model`, which means that all the code from `models.Model`, which interfaces with the database, applies to our entity. * On `Lines 4-7` we declare the attributes that our entity is going to have * `title` is a `CharField`, or character field - this just means that it has letters in it. We have set the maximum size to be 50 characters. * `text` is a `TextField`. This is similar to a `CharField`, but has no limit to the amount of text it can hold. * `author` is another `CharField`, this time with a maximum length of 30 characters. * `date` is a `DateTimeField` - not surprisingly, for storing date and time. The `auto_now_add=True` is a useful Django function which means that the date and time will be set automatically to whenever the `Post` was created. Now we have created our model, we need to apply it to the database. This is called **migrating**. Run the repl, but instead of just hitting `enter` to start the server, type the following line: ```bash > python manage.py makemigrations ``` This tells Django to look for changes to the database model. Now you need to apply those changes, by typing: ```bash > python manage.py migrate ``` This creates our entity in the database! The last thing we need to do, in order to see the database on our `admin` page, is change the file `Posts/admin.py`. Add the following: ```python from django.contrib import admin from .models import Post admin.site.register(Post) ``` This code imports the `admin` module from Django, and tells Django to add our entity (`Post`) to the admin page. If you go to your admin page now, you can see that our entity has been added! ![image](https://storage.googleapis.com/replit/images/1555587465586_f243a85e6e528d8c35b722ca8294a9df.pn) Click on `Add` next to `Post` and create a record for the database. ![image](https://storage.googleapis.com/replit/images/1555587608777_f9e210ad066f99f6f11bcdf337c252cf.pn) If you save the record, then you can see that the record has been added to the database (`The post "Post object (1)" was added successfully.`). -------------------------------------------------------------- ### Database Web Pages It's all very well being able to change the database when you're the administrator, but how do we get the database to interact with a web page? The answer is that we use some of Django's pre-defined views. Our current home page is not very interesting - let's change it so that it lists all of the posts in the database. #### View Go to `Posts/views.py` and delete all the code from it. Now we can start coding our view. ```python from django.views.generic import ListView from .models import Post class HomePageView(ListView): model = Post template_name='home.html' ``` * `Line 1` of our code imports `ListView`, which is a Django view specifically for listing records in an entity. * On `Line 2` we import our `Post` entity from `models.py`. This is the entity that our page will be based off of. * On `Line 4`, we create our view, `HomePageView`. Our view inherits from `ListView`, which means that we can use our view to list all of the records. * On `Line 5` we define which entity we are using - the `Post` model. This is just the entity that we created in `models.py` and imported on `Line 2` * On `Line 6`, we state which template we will be using - `home.html` #### Template We will also need to update our template in order to display all of our records. Go to `templates/home.html` and delete all the `html` from it. Now we can start writing our template. ```html {% extends 'base.html' %} {% block title %}Home{% endblock title %} {% block content %} {% for post in object_list %} <div class="post"> <h3>{{ post.title }}</h3> <p>{{ post.author }}</p> </div> <p>----------------------</p> {% endfor %} {% endblock content %} ``` The first 4 lines are standard `html` along with Django's **template language**, which we have covered before. On `Line 5`, we have our first new piece of code. ```html {% for post in object_list %} ``` This is a new part of Django's template language. When we use `ListView`, it passes in to the `html` document a list of all the records in the entity. This list can be referenced with `object_list`. So here, we are saying "for each post in object_list, do the following". On `Line 6`, we use a `div` element, with a `post` class. This is not necessary, but will be useful when styling the page with `CSS` later. On `Lines 7-8` we put the title of the post, and the author, on to the screen. On `Line 9`, we close the `div`, then on `Line 10` we add a divider to separate the items on the page. On `Line 11` we end the `for` loop, so only the `html` between `Lines 5-11` are repeated for each record #### URL We already created the URL for the home page, so we can skip this step. ------------------------------------------------------------------------------ If you run the server now, and navigate to your home page (https://repl-name--yourname.repl.co), then you should see something like this: ![image](https://storage.googleapis.com/replit/images/1555601489363_13d603e29a98b13fc4f7dfa576faf4f2.pn) It worked! Go to the admin page, and add another post. Now if you go back to the homepage, you should see something like this: ![image](https://storage.googleapis.com/replit/images/1555602222012_cea0e29bd01f92df1ee840bb57773eee.pn) Congratulations! You've made your first database-driven web page! ### Individual Pages Now we are going to make individual pages for each post - so each post has its own page that people can visit. To do this, we will use another Django class, `DetailView`. #### View Add the following to `Posts/views.py`: ```python from django.views.generic import ListView, DetailView # new from .models import Post # stuff class PostPageView(DetailView): model = Post template_name = 'post_page.html' ``` We create a view that inherits from `DetailView`, and set the model to our `Post` entity and the template to `post_page.html` (that we haven't created yet). #### Template Create a new file at `templates/post_page.html`, and add the following `html`: ```html {% extends 'base.html' %} {% block title %}{{ post.title }}{% endblock title %} {% block content %} <p>Posted by: {{ post.author }}</p> <p>On: {{ post.date }}</p> <h1>{{ post.title }}</h1> <p>{{ post.text }}</p> {% endblock content %} ``` This sets up a basic html template for the post. It can be confusing as to why `post` is used - the reason is that it is the lowercase name of our entity. You may see it also written as `object`, e.g. ```html <h1>{{ object.title }}</h1> ``` The rest of the `html` is fairly straightforward - we are just putting in all the data that we defined in our entity model in `Posts/models.py`. #### URL To configure the URL, we are going to use the primary key of the database (remember, the primary key is a unique number given to every record of the database). Django automatically adds a primary key to each entity, and its keys are always incremented - the first record added to the database has a primary key of 1, the second has a primary key of 2, and so on. Go to `Posts/urls.py`, and add the following code: ```python from django.urls import path from .views import HomePageView, PostPageView # new urlpatterns = [ path('post/<int:pk>/',PostPageView.as_view(), name='post'), # new path('', HomePageView.as_view(), name='home'), ] ``` This should all be familiar - the only new thing here is on `Line 5`. The `<int:pk>` tells Django to use the primary key of the number after `/post/` in the URL. `int` just tells Django that the key will be an integer. If you run the server now, and go to https://repl-name--yourname.repl.co/post/1, you should get a page displaying the information about the first post you created! ![image](https://storage.googleapis.com/replit/images/1555603916768_aaabaae418cf01008e04db56aea11459.pn) ---------------------------------------------- ### Linking to the Post However, typing in the URL all the time is not very user-friendly, so let's go back to the home page and add a link to each post. We just need to edit the template for this, so navigate to `templates/home.html` and change the `html` to: ```html {% extends 'base.html' %} {% block title %}Home{% endblock title %} {% block content %} {% for post in object_list %} <div class="post"> <h3><a href="{% url 'post' post.pk %}">{{ post.title }}</a></h3> <p>{{ post.author }}</p> </div> <p>----------------------</p> {% endfor %} {% endblock content %} ``` We've met the `url` function before - it takes a `name` and returns the URL. Here, the `name` takes an argument - the primary key of the post - so we just put that afterwards, and Django takes care of everything. If you go to your home page now, you can click on the titles to view the post! ------------------------------------------------ ### Creating and Editing Posts Now, what about creating and editing posts? Django makes this too very quick and easy. First, let's create a page where you can make a new post. #### View Go to `Posts/views.py`, and add the following code: ```python # stuff from django.views.generic.edit import CreateView # stuff class PostCreateView(CreateView): model = Post template_name = 'new_post.html' fields = ['title','author','text'] ``` First, we import `CreateView`, which is yet another pre-built class that Django supplies us with. This one is made especially for creating records for entities. Then we declare our `PostCreateView`, inheriting from `CreateView`. We set the entity model to `Post` and the template to `new_post.html` (which we haven't created yet). Then we set our fields. This is the data that we want the user to create. For this, the date will be created automatically, so we just need 'title', 'author' and of course 'text'. #### Template Create a new file at `templates/new_post.html`, and add the following `html`: ```html {% extends 'base.html' %} {% block title %}Create a new post{% endblock title %} {% block content %} <h2>Post a Question to the Forum!</h2> <form action="" method="POST">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> {% endblock content %} ``` Here, the most interesting bit is from `Lines 8-11`. * On `Line 8` we create a `html` **form** element. This is an element that lets users input information. The `action` attribute is where to send the data when it is submitted - if we set it to `""`, Django will take care of it. * The `method` is how the data is submitted. There are two main methods, `POST` and `GET`. `GET` puts the information in the URL - it is often used for searching. For example, a google search gives you a URL such as https://www.google.com/search?q=django%20tutorial&safe=active&ssui=on. This is a `GET` because the data is in the URL. `POST` doesn't put the data in the URL, so it is more secure. * Then we have `{% csrf_token %}`. This is a Django function to stop people using [Cross-Site Request Forgery](https://en.wikipedia.org/wiki/Cross-site_request_forgery) to attack users on your website. **Always have this on your forms!** * On `Line 9` we tell Django to put the form in as `<p>` elements. * On `Line 10`, we have a `"submit"` button. When the user clicks this, the data will be sent to Django * On `Line 11`, we end the form. #### URL Go to `urls.py` and add the following: ```python from .views import HomePageView, PostPageView, PostCreateView urlpatterns = [ path('create',PostCreateView.as_view(), name='create_post'), path('post/<int:pk>/',PostPageView.as_view(), name='post'), path('', HomePageView.as_view(), name='home'), ] ``` This is all standard. The last thing we need to do is specify what URL the form needs to go to once the form has been filled in. To do this, go to `Posts/models.py` and add the following: ```python from django.db import models from django.urls import reverse # new class Post(models.Model): # stuff def get_absolute_url(self): return reverse('post',args=[str(self.id)]) ``` First, we import the `reverse` function - this is similar to the `url` function that we use with the template language. When the form is submitted, Django automatically checks the `get_absolute_url` method, so we just need to define it in order for the redirect to happen. Here we are redirecting to the `post` page, giving the `id` (`pk`) of the record as an argument. This means that when the form is completed, it will redirect to the page with the post on it. Now we can go to our https://repl-name--yourname.repl.co/create, fill in the form, and create a new post! ### Editing Next, we will make a view that allows website visitors to edit existing posts to the forum. To do this, we will use the `UpdateView` that Django gives us. The process for creating new pages should be pretty familiar by now. #### View Add the following to `Posts/views.py`: ```python from django.views.generic.edit import CreateView, UpdateView class PostUpdateView(UpdateView): model = Post template_name = 'edit_post.html' fields = ['title','text'] ``` This is pretty similar to the `CreateView` - the only difference is that we don't let the user change the author. #### Template Create a file at `templates/edit_post.html` and add the following `html`: ```html {% extends 'base.html' %} {% block title %}Edit Post{% endblock title %} {% block content %} <h1>Post title</h1> <form action="" method="POST">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Update"> </form> {% endblock content %} ``` This is almost identical to the `CreateView`. #### URL Finally, add the following to `Posts/urls.py`: ```python from .views import HomePageView, PostPageView, PostCreateView, PostUpdateView urlpatterns = [ path('post/<int:pk>/edit/',PostUpdateView.as_view(), name='update_post'), # stuff ] ``` This will create an `edit` page at https://repl-name--yourname.repl.co/post/<pk>/edit To test this out, try just entering 1 instead of `<pk>` and you should be able to edit your first post! ### Deleting Records Finally, we will add a page that allows users to delete posts, using Django's `DeleteView`. #### View Add this to `Posts/views.py`: ```python from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy class PostDeleteView(DeleteView): model = Post template_name = 'delete_post.html' success_url = reverse_lazy('home') ``` This is fairly standard. The `success_url` tells Django what page to redirect to after the post has been deleted. We are using `reverse_lazy` instead of `reverse` here - what is the difference? `reverse` runs straight away, which means it can run before the rest of the program is ready - before 'home' has been initialised. To fix this, `reverse_lazy` is used, which waits until everything has loaded before getting the URL. #### Template Create a file at `templates/delete_post.html` and add the following `html`: ```html {% extends 'base.html' %} {% block title %}Delete Post{% endblock title %} {% block content %} <h1>Delete Post</h1> <form action="" method="POST">{% csrf_token %} <p>Are you sure you want to delete <strong>{{ post.title }}</strong></p> <input type="submit" value="Confirm"> </form> {% endblock content %} ``` This will just create a page with a `Confirm` button and a confirmation message. `<strong>` creates **bold** text. #### URL Finally, add this to `Posts/urls.py`: ```python from .views import HomePageView, PostPageView, PostCreateView, PostUpdateView, PostDeleteView urlpatterns = [ path('post/<int:pk>/delete/',PostDeleteView.as_view(),name='delete_post'), # stuff ] ``` If you go to https://repl-name--yourname.repl.co/post/<pk>/delete , you should be able to delete your post. ![image](https://storage.googleapis.com/replit/images/1555613745102_722a3c0e847b2412db9af4f9c5a25948.pn) ### Congratulations! That was quite a long tutorial, but we learnt how to use databases with Django! We went through it quite quickly, so you may want to read it more than once to gain a proper understanding of what is happening. You can post any questions below. In the next tutorial, we will look at user authentication, as well as making the site a bit more user-friendly. As always, 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.
0
posted by ArchieMaclean (350) 1 day ago
2
Traductor Morse
It translate the Morse language to normal and normal to Morse
1
posted by erloce (1) 2 days ago
2
quadratic equation solver
quadratic equation solver. Write the equation and click enter.
1
posted by Zdemon (1) 2 days ago
6
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 repl.it issue!_ ## Welcome! In [Part 1](https://repl.it/talk/learn/Learning-Web-Development-with-Python-Part-1/12880) and [Part 2](https://repl.it/talk/learn/Learning-Web-Development-with-Python-Part-2/12884) 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](https://repl.it/@ArchieMaclean/Django-Template). 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](https://storage.googleapis.com/replit/images/1555498000104_903f1cd023156a462a54072b37c458e5.pn) ----------------------------------------------------------------------------- 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 repl.it. ### 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: * `__init__.py` (2 underscores on either side of the `init`) * `admin.py` * `apps.py` * `models.py` * `tests.py` * `views.py` * Next, create a folder called `migrations` * Within `migrations`, add a file called `__init__.py` (2 underscores on either side of the `init`) The sidebar on your project should now look like this: ![image](https://storage.googleapis.com/replit/images/1555499982569_153f8c618224ad0dd3c3f3fb5958e3e4.pn) (Or similar with the light theme) Now we need to add just a little bit of code. To `apps.py` 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 settings.py After you have created the app, you need to update the `settings.py` file in order for Django to be able to find the app. To do this, go to `settings.py` and change the `INSTALLED_APPS` list. ```python INSTALLED_APPS = [ # stuff 'Posts.apps.PostsAppConfig', 'main', ] ``` This links to the code that we put in `apps.py` 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](https://repl.it/talk/learn/Learning-Web-Development-with-Python-Part-2/12884#extending-templates). #### View Now we need to create our view. In `Posts/views.py`, 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 `urls.py` is in `main`. How do we solve this? The answer is that we create another `urls.py` file **within** `Posts`, then redirect the `main` `urls.py` to this file. Sounds complicated? It is actually quite simple - let's do it. Within `Posts`, create a file called `urls.py`, 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 https://example.domain.com, then the home page would be located at https://example.domain.com/. Next, in `main/urls.py`, change the file to this: ```python from django.urls import path, include # include has been added from django.contrib import admin urlpatterns = [ path('admin/', admin.site.urls), 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/urls.py` file would be located at https://example.domain.com/hello/... . We will use this later - all of our `user` URLs will be located at https://example.domain.com/accounts/... 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](https://storage.googleapis.com/replit/images/1555501691887_aebdae492bf467920b247e67ae20f2cf.pn) ### `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, repl.it 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](https://www.elephantsql.com/) to host our database. First, create an account [here](https://customer.elephantsql.com/signup). Once you have done that, you should be faced with the following page: ![image](https://storage.googleapis.com/replit/images/1555502220876_8e9039bc14be5edf7f4cd7523863a099.pn) 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](https://storage.googleapis.com/replit/images/1555502596418_3854b044d269fb4ea87076774beee774.pn) (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 `settings.py` 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 `manny.db.elephantsql.com`. If you run this now, you get a long error: ![image](https://storage.googleapis.com/replit/images/1555503061679_80bc3dffb5aa84b1a8a5ca0b47d5cc01.pn) 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 manage.py 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.
3
posted by ArchieMaclean (350) 2 days ago
1
How to Make an Epic RNG
How to make an RNG in python
0
posted by programmyBoi (6) 3 days ago
1
HoGBot.js
Discord bot curated for the "House of Gods" Discord server, coded using Javascript/Node.js
0
posted by DPatel0211 (0) 3 days ago
1
use 3d shooter for tutorials
don't be amused,lets help each others for better choice
0
posted by CashLee (0) 4 days ago
1
use 3d shooter for tutorials
don't be amused,lets help each others for better choice
0
posted by CashLee (0) 4 days ago
1
3D
how to use python for editing
0
posted by CashLee (0) 4 days ago
1
finding length of the string by using python
implementation of le() function
0
posted by ganeshkavhar (0) 4 days ago
1
How To Make An Epic Basic Calculator In Python
Learn how to make an epic basic calculator in python here.
0
posted by programmyBoi (6) 4 days ago
2
Label Boxing
Using the code example below, you can start beginning your new program by editing some codes or add some codes of your own, or possibly both!: ============================================================ from tkinter import* root = Tk() root.title("Simple GUI") root.geometry("200x100") app = Frame(root) app.grid() lbl = Label(app, text = "Collin Kunsman") lbl.grid() root.mainloop()
2
posted by CollinKunsman (3) 4 days ago
1
Broken Buttons
Use the corresponding code below to start your Tkinter button program: ============================================================ from tkinter import* root = Tk() root.title("Lazy Buttons") root.geometry("200x85") app = Frame(root) app.grid() bttn = Button(app, text = "I do nothing!") bttn.grid() bttn2 = Button(app) bttn2.grid() bttn2.configure(text = "Me too!") bttn3 = Button(app) bttn3.grid() bttn3["text"] = "same here!" root.mainloop()
0
posted by CollinKunsman (3) 4 days ago
1
exercise 20
exercise 20
0
posted by H00392333 (0) 4 days ago
1
exercise 19
exercise 19
0
posted by H00392333 (0) 4 days ago
1
for loop
exercise 18
0
posted by H00392333 (0) 4 days ago
3
Migrating from discord.py async to rewrite
# Hey everyone! ### Recently, discord.py went through a major update, with quite a lot of changes to how certain things are done. Pretty much any discord bot that hasn't been updated will stop working, so I made this tutorial so you can easily update your code. > This is only a brief description of the changes. For a full guide to migrating, visit [this page](https://discordpy.readthedocs.io/en/rewrite/migrating.html). --- #### Snowflakes IDs are now integers rather than strings. If before you did `myChannel=client.get_channel("437048931827056644")`, now you have to do `myChannel=client.get_channel(437048931827056644)`. This also applies if you are storing IDs for channels, servers or users in `.env` - you will have to do `myServer=int(os.getenv("SERVER"))`. --- #### Sending messages In rewrite, many methods have been moved out of client. The most important example is now instead of `await client.send_message(myChannel,"Hello World!")`, you now need `await myChannel.send("Hello World!")`. To send private messages, you do the same but replace the channel with the user - `myUser.send("Hello World!")`. The other arguments you can pass (`embed=` etc) remain the same. Some other examples of this are: - `await client.delete_message(myMSG)` --> `await myMSG.delete()` - `await client.kick(myMember)` --> `await myMember.kick()` --- #### `Server`s are now `Guild`s Pretty much every single instance of the word `server` in the library is now a `guild` instead. The class is now `discord.Guild`, the server a message came from is `message.guild`, and the list of the bot's servers is now `client.guilds`. If in doubt about whether something should be `server` or `guild`, choose `guild`. --- #### Checking if a channel is a DM `discord.Channel` has been split up into a few different classes. The important ones we need to know about are `discord.abc.GuildChannel` and `discord.abc.PrivateChannel`. To check if a channel is a DM, you now have to use `isinstance(myChannel,discord.abc.PrivateChannel)`. --- #### Other changes - To edit a message, you now do `await myMessage.edit(content="New content!")` instead of `await client.edit_message(myMessage,new_content="New content!")`. Note the change from `new_content` to `content`. - `send_file` has been removed. To send a file, you use the same method, `send`, as for text and embeds: ```py with open("myPicture.png","rb") as myPicture: await myChannel.send(file=discord.File(myPicture)) ``` - `myMessage.timestamp` is now `myMessage.created_at` --- #### Additions - If your command takes a long time to process and output a result, it is now easier to send "typing" whilst your code runs: ```py async with myChannel.typing(): do_stuff_which_takes_a_while() ``` - To get all the users the bot can see, you can now use `client.users` - To get a channel's history, you can use `async for message in myChannel.history():` which will iterate through each `discord.Message`, or you can use `channelHistory=await channel.history().flatten()`, which returns a list of `discord.Message` --- ### Sharding This is one of the biggest changes, and the main reason why I personally migrated to rewrite before the library updated. In async, you had to do `client=discord.Client(shard_count=3,shard_id=1)` (if this was the second shard of a 3-shard bot) and run the same code separately for each shard - I achieved this using threading and running the entire bot as a function, where the `shard_id` was passed as an argument and each instance of the function was run in a separate thread. I then had to use a database that every shard could access and post their own individual server and user counts, in order to get the totals. This often made me want to cry myself to sleep. **However.** In rewrite, you can simply do `client=discord.AutoShardedClient()`. That's it. `client.servers` and `client.users` will now give the entire lists, including the parts that belong to other shards, and you only need to run one instance of the bot. Your bot is sharded with approximately 1000 servers to a shard, although you can control this by doing `client=discord.AutoShardedClient(shard_count=3)` if you want a specific number of shards (bear in mind that the maximum number of servers a single shard can connect to is 2500). --- #### That's all I'm going to cover. This tutorial is not by any means a definitive guide to migrating, you can find one of those [here](https://discordpy.readthedocs.io/en/rewrite/migrating.html), and also make sure to check out the docs [here](https://discordpy.readthedocs.io/en/rewrite/api.html). Post your newly-migrated bots in the comments section! ### I hope you found this post helpful. If you did (or even if you didn't) please leave an upvote! Also, be sure to check out [@TheDrone7](https://repl.it/@TheDrone7)'s tutorials on [how to make a discord bot](https://repl.it/talk/learn/Discordpy-Rewrite-Tutorial-using-commands-extension/10690) and [how to keep a discord bot running](https://repl.it/talk/learn/Hosting-discordpy-bots-with-replit/11008) on Repl.it. (No, I was not paid to plug those.) > @timmy_i_chen consider featuring this in newsletter? 😉
0
posted by minx28 (102) 5 days ago
1
Poderiam me ajudar , o que estou fazendo de errado ?
static void Declarations(string[] args) { int a; int b = 2, c = 3; a = 1; Console.WriteLine(a + b + c); }
0
posted by lecla (0) 5 days ago
1
ddd
ed
0
posted by Marlin_ouwungou (0) 6 days ago
1
Cambridge A-level Object Oriented Tutorial.
This is a basic object oriented tutorial designed for the Cambridge International Examination board. Some of the concepts here are a little unpythonistic, but they are clearly flagged. See the accompanying youtube video. https://www.youtube.com/watch?v=hg2NkuLLqcw
0
posted by jamesabela (14) 7 days ago
7
Learning Web Development w/ Python Part 2
# Learning Web Development with Python and Django ## Part 2 ## Welcome! In [Part 1](https://repl.it/talk/learn/Learning-Web-Development-with-Python-Part-1/12880) we made our first web-page with Django using function-based views. In this tutorial, we will be learning how to use `class-based views` which are more powerful and generally a better choice for web development. We will also look at html templates and creating multiple pages. ## Class-Based Views In the last tutorial, we used function-based views to determine what the client (visitor to the page) would see. However, there are also class-based views, which I will introduce to you now. These make creating views faster, especially when using databases, which we will be doing later. Let's get started! Fork the [basic template](https://repl.it/@ArchieMaclean/Basic-Template) and rename it to `tutorial-part-2`, or something else if you want. ### Templates Before we start creating our view, we need to learn about templates. In Part 1, our html was stored as a string, ```python html = "Hello, World!" ``` This is all right for very small pages, but when you want to make larger or more complicated pages, this gets very limiting. What would be better? If we made a file containing all of our html, and then imported that and displayed it. To do this, we are going to create a folder called `templates`. This will store all of our html templates for our website. Make sure you create your `templates` folder outside of your `main` folder, or Django will not be able to find it, like this: ![image](https://storage.googleapis.com/replit/images/1554639512628_b8e7a503d9c9bad16ec1cc01b69a7e32.pn) #### Creating our first Template Within `templates`, create a file called `home.html`. Then you can write some html inside it: ```html <!DOCTYPE html> <html> <head> <title>Home</title> </head> <body> <h1>Home</h1> <p>Welcome to this website! This site was created using the web framework Django</p> </body> </html> ``` This is just some basic html. This isn't a html tutorial, but here is a quick line-by-line analysis: * `<!DOCTYPE html>` tells the browser what type of file it is (`html`) * The `<html>` and `</html>` tags surround all the html - they show where it starts and ends * The `<head>` tag is used to put data in that isn't displayed on the page. Here I've put in the page title - this is shown in your tab at the top of the screen on your browser. * The `<body>` tags surround all the html that will be shown on the screen * The `<h1>` tag stands for `heading 1` and means that it is the largest heading possible. You can also get `<h2>`, `<h3>` and so on, down to `<h6>`. * The `<p>` tag surrounds a paragraph. -------------------------------------------------------------------------- Now we've created our template, we can write our home page view. ### Creating a Home Page View Now we can create our class-based view! Navigate to `views.py` and add the following code: ```python from django.views.generic import TemplateView class HomePageView(TemplateView): template_name = 'home.html' ``` `Line 1` imports `TemplateView`, which we will need to create our view. `Lines 3-4` define our view class * On `Line 3` we create our view, called `HomePageView`. This view **inherits** from `TemplateView`. This means we can use all the code from `TemplateView` as well as some code that we add that is specific to `HomePageView`. * Here, the only thing that is specific about our home page is that it uses the template `'home.html'`, so on `Line 4` we set `template_name` equal to our template That's it! All the rest is taken care of by the `TemplateView` class, which the Django creators have written - so we don't need to worry about anything else. ### Adding the URL (Page Name) Finally, to give the view a url, we need to add it to the `urlpatterns` in `urls.py`: ```python from .views import HomePageView urlpatterns = [ url(r'^admin/', admin.site.urls), url('',HomePageView.as_view(), name='home') ] ``` This is pretty much all the same as last time (if you need a refresher, see [Part 1](https://repl.it/talk/learn/Learning-Web-Development-with-Python-Part-1/12880)). The only difference is that, for class-based views, we need to add a `.as_view()` on to the end in order for the page to display. ### ...And it Works! If you run the repl now, and open the page in a new tab, we get: ![image](https://storage.googleapis.com/replit/images/1554634538507_9cf09092536f2e87fe37965cc96655e4.pn) It worked! ------------------------------------------------------------------------------------------ ### How did Django know where to find the template? If you've been paying close attention, you may be wondering - how did Django know where to find the template? In the view we just specified it as `'home.html'`, not as `'templates/home.html'`. The answer lies in `settings.py`. If you open the file, you can see a list called `TEMPLATES`: ```python # stuff BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # more stuff TEMPLATES = [ { # stuff 'DIRS': [os.path.join(BASE_DIR, 'templates')], # more stuff }, ] ``` I have cut out the rest of the list to draw your attention to `'DIRS'`. What this code does is sets `'DIRS'` to the `templates` folder that we created. Every time we request a template, Django will look in this folder. This code was put here by repl in case you wanted to create templates. ### Making multiple pages Now we are going to add another page - an `About` page. To do this, we follow much the same process as we did for the home page. ##### Template We create a file called `about.html` in `templates`: ```html <!DOCTYPE html> <html> <head> <title>About</title> </head> <body> <h1>About</h1> <p>This is a tutorial for creating a web app with Django. Currently all we have done is made web pages</p> </body> </html> ``` ##### View Then we create a new view in `views.py`: ```python # HomePageView class AboutPageView(TemplateView): template_name = 'about.html' ``` ##### URL And finally, we add the url in `urls.py`: ```python from .views import (HomePageView, AboutPageView) urlpatterns = [ url(r'^admin/', admin.site.urls), url('about',AboutPageView.as_view(), name='about'), url('',HomePageView.as_view(), name='home'), ] ``` The only thing to note from here is that the URL is now `about`, which means that the page will be located at https://domain.name/about/. The URL for the `about` page **must** be above the URL for the `home page` because Django works through them from first to last, and because of the way it works, it matches `''` to **all** pages. However, if we put the `about` before `home`, it will check `about` first, so if the client enters https://domain.name/about, it will be matched first, and the correct page displayed. ### Extending Templates The last thing we are going to learn in this (rather long) tutorial is a very useful built-in functionality of Django that allows template extension. What do I mean by this? An example is probably the best way to show it. Create a new file in `templates` called `base.html`. This is going to be our **base template**. Add the following html to the file: ```html <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock title %}</title> </head> <body> <a href="{% url 'home' %}">Home</a> <a href="{% url 'about' %}">About</a> {% block content %} {% endblock content %} </body> </html> ``` And update your `home.html` to look like this: ```html {% extends 'base.html' %} {% block title %}Home{% endblock title %} {% block content %} <h1>Home</h1> <p>Welcome to this website! This site was created using the web framework Django</p> {% endblock content %} ``` Now, if you know anything about html, this will look very strange because it has all these `{%`s which are not normally in html. There is quite a lot going on here, so I will walk you through it. In `base.html`: * On `Lines 1-3` we have standard html * On `Line 4` we have our first strange occurrence of the `{%` and `%}`. What is happening here? This is Django's **template language** - designed for doing interesting stuff with your pages. Here we are declaring a `block`. This means that it is going to get replaced by something from another file - as you can see on `Line 1` of `home.html`, we are replacing it with the word `Home`. * On `Lines 7/8` there is also something happening. Here we are using Django's `url` function. Remember when we were defining our views, we set a name for them? ```python urlpatterns = [ url(r'^admin/', admin.site.urls), url('about',AboutPageView.as_view(), name='about'), url('',HomePageView.as_view(), name='home'), ] ``` The `url` function gets the URL of the view with that name - so `{% url 'home' %}` would get the URL of the `home` page. The `<a href="` in html defines a link, so what we are creating here is a link to the home page, and then a link to the about page. * On `Lines 10/11` we are creating a `block` called content, that will also be replaced by another file - in `home.html` we are replacing it with `<h1>Ho...Django</p>`. The `home.html` imports the `base.html` html using `{% extends 'base.html' %}`, and then replaces what bits need to be changed. If we run this, we get: ![image](https://storage.googleapis.com/replit/images/1554638219005_eeaf811555b9a9e07ef89ebe89ae3fe0.pn) It worked! The brilliant thing about these extensions is that they can apply to any pages - just update `about.html` to this: ```html {% extends 'base.html' %} {% block title %}About{% endblock title %} {% block content %} <h1>About</h1> <p>This is a tutorial for creating a web app with Django. Currently all we have done is made web pages</p> {% endblock content %} ``` And our `about` page also has the links at the top! Also, the navigation means that we don't have to type in any more URLs, we can just click the links. ----------------------------------------------------------------- ### Conclusion And that's the end of Part 2! I hope you enjoyed it. In [Part 3](https://repl.it/talk/learn/Learning-Web-Development-with-Python-Part-3/13267) we will learn how to use databases with Django, as well as look at managing larger apps by splitting them up into smaller 'applets'. 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.
5
posted by ArchieMaclean (350) 12 days ago
19
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](https://repl.it/talk/learn/Tutorial-Building-a-Django-web-application/6660). 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. www.google.com or www.repl.it. **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](https://repl.it/@ArchieMaclean/Basic-Template) which has the bare minimum. Open the template, and click the `fork` button at the top to make your own copy. ![image](https://storage.googleapis.com/replit/images/1554625804315_2a5ed0a55c14c016feacd6dc438d3b20.pn) 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](https://storage.googleapis.com/replit/images/1554625969590_1b80aeda3f1db062a5e7916c97db3ae3.pn) 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](https://storage.googleapis.com/replit/images/1554626030130_fdf8263732fa1645061a5e309c29154f.pn) 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 https://ww.repl.it/languages/python) on a browser, there are three parts: * **Protocol** - almost always `http` or `https`. * **Domain name** - looks like `www.repl.it/`. * **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>.repl.co`). 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 `views.py` 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 `urls.py` file, and add the following: ```python from .views import homePageView ``` Then change `urlpatterns` to: ```python urlpatterns = [ url(r'^admin/', admin.site.urls), 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](https://storage.googleapis.com/replit/images/1554627432054_c0f2284207576ce83123b494a7735ee8.pn) So how did this happen? Let's look at the code. ```python from .views import homePageView ``` This imports our `homePageView` function from the `view.py` 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 https://domain.name/about/aboutme (replacing `domain.name` with the domain name, obviously). However, it is just `''` so the view will be located at just https://domain.name/. * The second is our view that we created in `views.py` 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](https://repl.it/talk/learn/Learning-Web-Development-with-Python-Part-2/12884), 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.
2
posted by ArchieMaclean (350) 13 days ago
10
Julia Fractals in JavaScript
***Originally written for [Hack Club](https://hackclub.com), a global network of high-school hackers and coding clubs.*** Fractals. You've seen them. They're beautiful: ![File:Mandelbrot sequence new.gif](https://upload.wikimedia.org/wikipedia/commons/a/a4/Mandelbrot_sequence_new.gif) What kind of crazy black magic lets computers draw these things?? It must be like… really complicated. WRONG. Fractal renderers are _ridiculously_ simple—and to prove it, you're going to write one. [**Click here to get started.**](https://repl.it/@polytrope/julia-fractals-starter) _You should start with this simple HTML document:_ ```html <!DOCTYPE html> <html> <head> <title>Julia Fractals</title> </head> <style> body { background: black; color: white; } canvas { border: 1px solid white; } </style> <body> <h2></h2> <canvas></canvas> </body> <!-- Import math.js --> <script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/5.6.0/math.min.js"></script> <script> // The HTML elements we are using var header = document.querySelector('h2') var canvas = document.querySelector('canvas') var ctx = canvas.getContext('2d') // The size of our canvas var width = 200 var height = 200 // Set the size of our canvas canvas.width = width canvas.height = height // The XY coordinates of the mouse over the canvas var mouseX = 0 var mouseY = 0 </script> </html> ``` ## The Complex Plane Fractals arise from basic arithmetic with **complex numbers**. Despite their name, complex numbers are actually quite simple; instead of a number _line_, complex numbers exist on a _plane_. Complex numbers are usually written `x+y*i`. So `2+4i` is at the point (2, 4). ![Mousing around the complex plane](https://storage.googleapis.com/replit/images/1554408244144_33a071bc40ed05d44d33eda2e246dd90.gi) `i` is the square root of -1 (so `i*i=-1`). We can't find a value for `i` on the "real" number line, because `x*x` is _never_ negative. For a long time, mathematicians just ignored square roots of negative numbers—just like they used to ignore negative numbers. _They aren't "real" numbers, so what good are they?_ Then somebody thought to put `i` on its own separate, _vertical_ number line. The **Complex Plane** was born—you won't believe what happened next. ### From Pixels to Points Each _pixel_ on our canvas corresponds to a _point_ on the complex plane. We need a function to convert XY pixels to complex points. Complex numbers aren't "built in" for most programming languages. We'll use a library called math.js to work with them in JavaScript. To create a new complex number with math.js, we simply write `math.complex(x, y)` Add a function called `pixelToPoint` to the end of your script: ```javascript // the rest of your script... // Turn XY pixel coordinates into a point on the complex plane function pixelToPoint(x, y) { // Map percentage of total width/height to a value from -1 to +1 var zx = (x/width)*2-1 var zy = 1-(y/height)*2 // Create a complex number based on our new XY values return math.complex(zx, zy) } ``` This takes the X and Y coordinates for a pixel, divides each to get that pixel's percentage of the overall width/height, and maps that percentage to a value from -1 to +1. The result is a point between `-1-1i` and `1+1i`. Note how `zx` is `(x/width)*2-1`, but `zy` is `1-(y/height)*2`. `zy` is flipped—this is just because on a webpage, pixel coordinates go top-to-bottom (and we want our complex plane to be bottom-to-top). Now let's use that function to pick out a point on the plane with the mouse. Later on we'll need a point called `constant` for our fractal equation, so let's use that. Add a complex number called `constant` to the top of your script, just before `pixelToPoint` and just after `mouseX`/`mouseY`: ```javascript // mouseX/mouseY + the rest of your script... // The point we use for C in our Julia Set equation var constant = math.complex(0.28, 0.01) // pixelToPoint + the rest of your script... ``` Now let's hook up the mouse to the canvas. Add two new functions called `update` and `move` to the end of your script. `move` will fire every time the mouse moves to a new point on the canvas, and `update` will change the header to show that point. We'll also add an event listener to the canvas to trigger `move`: ```javascript // pixelToPoint + the rest of your script... // Update the elements that need to change function update() { header.innerHTML = constant.toString() } // What to do when the mouse moves over the canvas function move(event) { // Get the mouse's XY coordinates on canvas mouseX = event.clientX-canvas.offsetLeft mouseY = event.clientY-canvas.offsetTop // Turn mouse coordinates into a point on the complex plane constant = pixelToPoint(mouseX, mouseY) // Round that point off to the nearest 0.01 constant.re = math.round(constant.re*100)/100 constant.im = math.round(constant.im*100)/100 // Update everything! update() } // Trigger move every time the mouse moves over canvas canvas.addEventListener('pointermove', move) ``` Note that we're rounding `constant` to the nearest 0.01: ```javascript constant.re = math.round(constant.re*100)/100 constant.im = math.round(constant.im*100)/100 ``` This just looks a little neater. `constant.re` is the "real" part of the number—the X value. `constant.im` is the "imaginary" part—the Y value. Now if you run the page and mouse over the canvas, you should see `constant` updating in the header! ![Selecting points on the complex plane](https://storage.googleapis.com/replit/images/1554408364480_1d35dceddec7e5915d6eb7af1dd4a71a.gi) Your whole script should look like [this](https://repl.it/@polytrope/julia-fractals-complex-plane): ```html <script> // The HTML elements we are using var header = document.querySelector('h2') var canvas = document.querySelector('canvas') var ctx = canvas.getContext('2d') // The size of our canvas var width = 200 var height = 200 // Set the size of our canvas canvas.width = width canvas.height = height // The XY coordinates of the mouse over the canvas var mouseX = 0 var mouseY = 0 // The point we use for C in our Julia Set equation var constant = math.complex(0.28, 0.01) // Turn XY pixel coordinates into a point on the complex plane function pixelToPoint(x, y) { // Map percentage of total width/height to a value from -1 to +1 var zx = (x/width)*2-1 var zy = 1-(y/height)*2 // Create a complex number based on our new XY values return math.complex(zx, zy) } // Update the elements that need to change function update() { header.innerHTML = constant.toString() } // What to do when the mouse moves over the canvas function move(event) { // Get the mouse's XY coordinates on canvas mouseX = event.clientX-canvas.offsetLeft mouseY = event.clientY-canvas.offsetTop // Turn mouse coordinates into a point on the complex plane constant = pixelToPoint(mouseX, mouseY) // Round that point off to the nearest 0.01 constant.re = math.round(constant.re*100)/100 constant.im = math.round(constant.im*100)/100 // Update everything! update() } // Trigger move every time the mouse moves over canvas canvas.addEventListener('pointermove', move) </script> ``` ## Drawing Pixels Let's draw some colors on our canvas. Every _pixel_ maps to a _point_, and every _point_ maps to a _color_. Let's make it so that every time we change `constant` we draw in a color for that pixel. To do this, we need a new function called `pointToColor`. This function will turn any point into an RGB color, simply by using the "real" (X) value `point.re` for Red and the "imaginary" (Y) value `point.im` for green: ```javascript // constant + the rest of your script... // Turn a point on the complex plane into a color function pointToColor(point) { var red = point.re*255 var green = point.im*255 return `rgb(${red}, ${green}, 0)` } // pixelToPoint + the rest of your script... ``` We will also need two more functions, called `drawPixel` and `draw`. `drawPixel` will draw a given color at a given pixel. `draw` will ```javascript // pixelToPoint + the rest of your script... // Draw a single pixel on our canvas function drawPixel(x, y, color) { ctx.fillStyle = color ctx.fillRect(x, y, 1, 1) } // Redraw our canvas function draw() { // Turn the point under the mouse into a color var color = pointToColor(constant) // Draw over the pixel under the mouse with that color drawPixel(mouseX, mouseY, color) } // update + the rest of your script... ``` Let's quickly look at `drawPixel`. This is how basic drawing works with canvas. First you set properties like `fillStyle` on the "drawing context" (usually labelled `ctx`). Then you trigger a drawing operation like `fillRect` to draw shapes onto the canvas—in this case, a single 1x1 rectangle. Finally, we need to add `draw()` to `update` so that our canvas will redraw anytime we call `update`: ```javascript // draw + the rest of your script... // Update the elements that need to change function update() { header.innerHTML = constant.toString() draw() } // move + the rest of your script... ``` Now if you run the page, you should see little colored pixels show up as you mouse over the plane: ![Drawing in pixels on the complex plane](https://storage.googleapis.com/replit/images/1554408436658_ab92846587460e292ecc1c12bd469d5a.gi) Your script should now look like [this](https://repl.it/@polytrope/julia-fractals-drawing-pixels): ```html <script> // The HTML elements we are using var header = document.querySelector('h2') var canvas = document.querySelector('canvas') var ctx = canvas.getContext('2d') // The size of our canvas var width = 200 var height = 200 // Set the size of our canvas canvas.width = width canvas.height = height // The XY coordinates of the mouse over the canvas var mouseX = 0 var mouseY = 0 // The point we use for C in our Julia Set equation var constant = math.complex(0.28, 0.01) // Turn a point on the complex plane into a color function pointToColor(point) { var red = point.re*255 var green = point.im*255 return `rgb(${red}, ${green}, 0)` } // Turn XY pixel coordinates into a point on the complex plane function pixelToPoint(x, y) { // Map percentage of total width/height to a value from -1 to +1 var zx = (x/width)*2-1 var zy = 1-(y/height)*2 // Create a complex number based on our new XY values return math.complex(zx, zy) } // Draw a single pixel on our canvas function drawPixel(x, y, color) { ctx.fillStyle = color ctx.fillRect(x, y, 1, 1) } // Redraw our canvas function draw() { // Turn the point under the mouse into a color var color = pointToColor(constant) // Draw over the pixel under the mouse with that color drawPixel(mouseX, mouseY, color) } // Update the elements that need to change function update() { header.innerHTML = constant.toString() draw() } // What to do when the mouse moves over the canvas function move(event) { // Get the mouse's XY coordinates on canvas mouseX = event.clientX-canvas.offsetLeft mouseY = event.clientY-canvas.offsetTop // Turn mouse coordinates into a point on the complex plane constant = pixelToPoint(mouseX, mouseY) // Round that point off to the nearest 0.01 constant.re = math.round(constant.re*100)/100 constant.im = math.round(constant.im*100)/100 // Update everything! update() } // Trigger move every time the mouse moves over canvas canvas.addEventListener('pointermove', move) </script> ``` ## Drawing the Plane We don't just want to draw one pixel at a time—we want the whole plane at once. Let's modify our `draw` function so it fills in _every_ pixel: ```javascript // drawPixel + the rest of your script // Redraw our canvas function draw() { // Loop over every column of pixels for (var y = 0; y < height; y++) { // Loop over every row of pixels for (var x = 0; x < width; x++) { // Turn this pixel into a point in the complex plane var point = pixelToPoint(x, y) // Turn that point into a color var color = pointToColor(point) // Draw over this pixel with that color drawPixel(x, y, color) } } } // update + the rest of your script... ``` This new `draw` function is actually pretty simple. It uses two loops—one for X and one for Y—to go over every pixel in our canvas. Then it gets the complex plane point for that pixel. Then it gets the color for that point. Then it draws that color at that pixel. If you run the page, you should see the same field of red/green pixels—only now they are all filled in! ![The full plane, filled in](https://storage.googleapis.com/replit/images/1554408579988_3395add24c7bc35f64073bb512c34a3e.pn) The only problem is that the page waits for the mouse to move before drawing the canvas. Let's fix that with a call to `update` at the end of our script, just after we add the event listener: ```javascript // addEventListener + the rest of your script... // Update everything! update() ``` ### Simple Complex Arithmetic Let's make a few more changes to our `pointToColor` function, just to understand what's going on. First, try adding `point = point.sub(constant)` To the top of `pointToColor`: ```javascript // constant + the rest of your script... // Turn a point on the complex plane into a color function pointToColor(point) { point = point.sub(constant) var red = point.re*255 var green = point.im*255 return `rgb(${red}, ${green}, 0)` } // pixelToPoint + the rest of your script... ``` This means we _subtract_ `constant` from our `point` before we turn it into a color. Since complex numbers aren't built into JavaScript, we can't use `+-*/`—math.js has us use `.add()` `.sub()` `.mul()` `.div()` instead. What does it mean to add/subtract a complex number? Well, it's pretty much the same as adding regular numbers: 1+2i + 1+2i = 2+4i. However, there is a better, more _geometric_ way to think about this: we are using one point to _move_ another point _around the plane_: ![Adding points on the Complex Plane](https://storage.googleapis.com/replit/images/1554408625002_632c18d5e84faad25763a8a65a69275b.gi) And if you run the page, this is exactly what you should see—when we _subtract_ the mouse position from each point before turning it into a color, the entire plane will move with the mouse: ![Moving the complex plane with the mouse](https://storage.googleapis.com/replit/images/1554408698991_86513310aed2338a8dfd986d129abcbe.gi) What a convenient geometric representation! As it turns out, you can _multiply_ complex numbers too. Amazingly, this also has a simple geometric interpretation: _rotation_ and _scaling_: ![Multiplying points on the Complex Plane](https://storage.googleapis.com/replit/images/1554408735283_46d80839958d9124cc447011b9324908.gi) Try changing this line: `point = point.sub(constant)` to this: `point = point.div(constant)` This will _divide_ each point on the plane by `constant` before turning it into a color. And if you run the page, you should see the plane rotate and scale with the mouse: ![Rotating and scaling the complex plane](https://storage.googleapis.com/replit/images/1554408766533_9e05ae48eca48152992e059b836bb474.gi) This way of thinking about complex numbers—where add/subtract moves a point, and multiply/divide rotates and scales it—is _incredibly_ powerful. Let's make one more change, to show off an important function called `math.abs`. The **Absolute Value** of a complex number is its "length"—the distance from that point on the complex plane to 0+0i. Try changing your `pointToColor` function like so: ```javascript // constant + the rest of your script... // Turn a point on the complex plane into a color function pointToColor(point) { point = point.div(constant) var red = point.re*255 var green = point.im*255 var blue = math.abs(point)*255 return `rgb(${red}, ${green}, ${blue})` } // pixelToPoint + the rest of your script... ``` Now we have a `blue` value for our color, which shows `math.abs(point)`. If you run the page, it should look like this: ![Moving colors on the complex plane](https://storage.googleapis.com/replit/images/1554408807050_58ef5f105aee612c70997455d7bb8cac.gi) Think about the colors you see—why _these_ colors? Why is the blue in a circle? Why is one corner white? Your script should now look like [this](https://repl.it/@polytrope/julia-fractals-drawing-plane): ```html <script> // The HTML elements we are using var header = document.querySelector('h2') var canvas = document.querySelector('canvas') var ctx = canvas.getContext('2d') // The size of our canvas var width = 200 var height = 200 // Set the size of our canvas canvas.width = width canvas.height = height // The XY coordinates of the mouse over the canvas var mouseX = 0 var mouseY = 0 // The point we use for C in our Julia Set equation var constant = math.complex(0.28, 0.01) // Turn a point on the complex plane into a color function pointToColor(point) { point = point.sub(constant) var red = point.re*255 var green = point.im*255 var blue = math.abs(point)*255 return `rgb(${red}, ${green}, ${blue})` } // Turn XY pixel coordinates into a point on the complex plane function pixelToPoint(x, y) { // Map percentage of total width/height to a value from -1 to +1 var zx = (x/width)*2-1 var zy = 1-(y/height)*2 // Create a complex number based on our new XY values return math.complex(zx, zy) } // Draw a single pixel on our canvas function drawPixel(x, y, color) { ctx.fillStyle = color ctx.fillRect(x, y, 1, 1) } // Redraw our canvas function draw() { // Loop over every column of pixels for (var y = 0; y < height; y++) { // Loop over every row of pixels for (var x = 0; x < width; x++) { // Turn this pixel into a point in the complex plane var point = pixelToPoint(x, y) // Turn that point into a color var color = pointToColor(point) // Draw over this pixel with that color drawPixel(x, y, color) } } } // Update the elements that need to change function update() { header.innerHTML = constant.toString() draw() } // What to do when the mouse moves over the canvas function move(event) { // Get the mouse's XY coordinates on canvas mouseX = event.clientX-canvas.offsetLeft mouseY = event.clientY-canvas.offsetTop // Turn mouse coordinates into a point on the complex plane constant = pixelToPoint(mouseX, mouseY) // Round that point off to the nearest 0.01 constant.re = math.round(constant.re*100)/100 constant.im = math.round(constant.im*100)/100 // Update everything! update() } // Trigger move every time the mouse moves over canvas canvas.addEventListener('pointermove', move) // Update everything! update() </script> ``` ## The Julia Set Now for the main event—rendering a fractal. We're going to render the Julia Set. This fractal is defined by a very simple function: ![The equation that defines the Julia Set](https://storage.googleapis.com/replit/images/1554408840000_0c2499280c0116ec8a46201ca570e0ed.pn) We need to use this equation to generate a color for each point on the complex plane. However, this function doesn't give you a color directly—it defines a _process_ that you can apply to each point: 1. _Multiply_ that point by itself 2. _Add_ your `constant` value C 3. Repeat 1. Multiply this _new_ point by itself 2. Add your `constant` value C 3. Repeat 1. Multiply _this_ new point by itself 2. Add your `constant` value C 3. Repeat… You can apply this process _infinitely_ for any point. For most points, the number will just keep getting bigger and bigger and bigger. When this happens, we say the number **Escapes**. Any point with an absolute value of at least 2 will _always_ get bigger and bigger forever. So if `math.abs(z) >= 2`, we _know_ that `z` escapes. But for some numbers in that little circle around the origin—where `math.abs(z) < 2`—something peculiar happens. Each time we apply this process, the point will move… but it will never _escape_. It may just bounce around _forever_, rotating and moving around the origin without ever "escaping" it. To get a color from each point, we apply this process a bunch of times to see if that point escapes. We stop when `math.abs(z) > 2`, or when we hit some maximum number of iterations (we'll set a max of 64). Add a new value called `maxIterations` just below `constant`, and a new function called `julia` just after that: ```javascript // constant + the rest of your script... // The maximum number of times we iterate a point to see if it escapes var maxIterations = 64 // Apply the Julia Set formula to see if point z "escapes" function julia(z, i = 0) { // Apply the Julia Set formula: z*z+constant z = z.mul(z) z = z.add(constant) // Has our point escaped, or hit the iteration limit? if (math.abs(z) > 2 || i == maxIterations) // If so, return number of iterations return i else // If not, iterate again! return julia(z, i+1) } // pointToColor + the rest of your script... ``` Now we have a function `julia` which tells us how many iterations of the Julia Set equation it takes for a given point to escape. We need to turn that number of iterations into a color. We'll use a simple grayscale color scheme, where black is 0 iterations and white is our `maxIterations` value. Change your `pointToColor` function like so: ```javascript // julia + the rest of your script... // Turn a point on the complex plane into a color function pointToColor(point) { // How many iterations on this point before it escapes? var iterations = julia(point) // What percentage of our limit is that? var percentage = iterations/maxIterations var red = percentage*255 var green = percentage*255 var blue = percentage*255 // Create a color from that percentage return `rgb(${red}, ${green}, ${blue})` } // pixelToPoint + the rest of your script... ``` Now if your run your page, you should see a grayscale Julia fractal that morphs as your move the mouse: ![A grayscale render of the Julia Set](https://storage.googleapis.com/replit/images/1554408869865_d5d0e292cd1a4c157492aa8f1853cc6f.gi) Your whole script should now look like [this](https://repl.it/@polytrope/julia-fractals-julia-set): ```html <script> // The HTML elements we are using var header = document.querySelector('h2') var canvas = document.querySelector('canvas') var ctx = canvas.getContext('2d') // The size of our canvas var width = 200 var height = 200 // Set the size of our canvas canvas.width = width canvas.height = height // The XY coordinates of the mouse over the canvas var mouseX = 0 var mouseY = 0 // The point we use for C in our Julia Set equation var constant = math.complex(0.28, 0.01) // The maximum number of times we iterate a point to see if it escapes var maxIterations = 64 // Apply the Julia Set formula to see if point z "escapes" function julia(z, i = 0) { // Apply the Julia Set formula: z*z+constant z = z.mul(z) z = z.add(constant) // Has our point escaped, or hit the iteration limit? if (math.abs(z) > 2 || i == maxIterations) // If so, return number of iterations return i else // If not, iterate again! return julia(z, i+1) } // Turn a point on the complex plane into a color function pointToColor(point) { // How many iterations on this point before it escapes? var iterations = julia(point) // What percentage of our limit is that? var percentage = iterations/maxIterations var red = percentage*255 var green = percentage*255 var blue = percentage*255 // Create a color from that percentage return `rgb(${red}, ${green}, ${blue})` } // Turn XY pixel coordinates into a point on the complex plane function pixelToPoint(x, y) { // Map percentage of total width/height to a value from -1 to +1 var zx = (x/width)*2-1 var zy = 1-(y/height)*2 // Create a complex number based on our new XY values return math.complex(zx, zy) } // Draw a single pixel on our canvas function drawPixel(x, y, color) { ctx.fillStyle = color ctx.fillRect(x, y, 1, 1) } // Redraw our canvas function draw() { // Loop over every column of pixels for (var y = 0; y < height; y++) { // Loop over every row of pixels for (var x = 0; x < width; x++) { // Turn this pixel into a point in the complex plane var point = pixelToPoint(x, y) // Turn that point into a color var color = pointToColor(point) // Draw over this pixel with that color drawPixel(x, y, color) } } } // Update the elements that need to change function update() { header.innerHTML = constant.toString() draw() } // What to do when the mouse moves over the canvas function move(event) { // Get the mouse's XY coordinates on canvas mouseX = event.clientX-canvas.offsetLeft mouseY = event.clientY-canvas.offsetTop // Turn mouse coordinates into a point on the complex plane constant = pixelToPoint(mouseX, mouseY) // Round that point off to the nearest 0.01 constant.re = math.round(constant.re*100)/100 constant.im = math.round(constant.im*100)/100 // Update everything! update() } // Trigger move every time the mouse moves over canvas canvas.addEventListener('pointermove', move) // Update everything! update() </script> ``` ## Pan Now we have a fractal, which is pretty cool. But what if we want to move around _within_ our fractal? Let's start with a "pan" operation, that moves the image up/down/left/right as we click. We'll set this up so that the first click sets our `constant` value, and every click after that pans the image. Add two new values for `clicked` and `pan` at the top, just below `maxIterations` and above `julia`: ```javascript // maxIterations + the rest of your script... // Whether we have clicked yet var clicked = false // How much we move the image var pan = math.complex(0, 0) // julia + the rest of your script... ``` Now add a new function called `click`, just after `update`: ```javascript // update + the rest of your script... function click(event) { // Ignore the first click if (!clicked) { clicked = true return } // Get the mouse's XY coordinates on canvas mouseX = event.clientX-canvas.offsetLeft mouseY = event.clientY-canvas.offsetTop // Turn mouse coordinates into a point on the complex plane pan = pixelToPoint(mouseX, mouseY) // Update everything! update() } // the rest of your script... ``` Notice that if `clicked` is false, `click` will do nothing—except set `clicked` to true. Similarly, we need to change `move` so that it will do nothing if `clicked` is _true_: ```javascript // click + the rest of your script... // What to do when the mouse moves over the canvas function move(event) { // Don't move after first click if (clicked) { return } // Get the mouse's XY coordinates on canvas mouseX = event.clientX-canvas.offsetLeft mouseY = event.clientY-canvas.offsetTop // Turn mouse coordinates into a point on the complex plane constant = pixelToPoint(mouseX, mouseY) // Round that point off to the nearest 0.01 constant.re = math.round(constant.re*100)/100 constant.im = math.round(constant.im*100)/100 // Update everything! update() } ``` We also need to add a listener to trigger `click` whenever we click on the canvas. Let's put it just after our `move` function: ```javascript // move + the rest of your script... // Trigger click every time the canvas is clicked canvas.addEventListener('click', click) // the rest of your script... ``` Now when we click on the canvas, it will fix our `constant` value—and every click after that will change the `pan` value. Finally, we need to actually _use_ that `pan` value somewhere. We want `pan` to change which pixel maps to each point—so we need to change our `pixelToPoint` function so that our `pan` value is _added_ to each point: ```javascript // pointToColor + the rest of your script... // Turn XY pixel coordinates into a point on the complex plane function pixelToPoint(x, y) { // Map percentage of total width/height to a value from -1 to +1 var zx = (x/width)*2-1 var zy = 1-(y/height)*2 // Create a complex number based on our new XY values var z = math.complex(zx, zy) // Pan the camera z = z.add(pan) return z } // drawPixel + the rest of your script... ``` Now if you run the page, you should be able to set the `constant` value and pan around the image by clicking! ![Panning around the rendered fractal](https://storage.googleapis.com/replit/images/1554408921490_a3b850be4b61936cdc93c15ab4cd067a.gi) Your full script should look like [this](https://repl.it/@polytrope/julia-fractals-click-pan): ```html <script> // The HTML elements we are using var header = document.querySelector('h2') var canvas = document.querySelector('canvas') var ctx = canvas.getContext('2d') // The size of our canvas var width = 200 var height = 200 // Set the size of our canvas canvas.width = width canvas.height = height // The XY coordinates of the mouse over the canvas var mouseX = 0 var mouseY = 0 // The point we use for C in our Julia Set equation var constant = math.complex(0.28, 0.01) // The maximum number of times we iterate a point to see if it escapes var maxIterations = 64 // Whether we have clicked yet var clicked = false // How much we move the image var pan = math.complex(0, 0) // Apply the Julia Set formula to see if point z "escapes" function julia(z, i = 0) { // Apply the Julia Set formula: z*z+constant z = z.mul(z) z = z.add(constant) // Has our point escaped, or hit the iteration limit? if (math.abs(z) > 2 || i == maxIterations) // If so, return number of iterations return i else // If not, iterate again! return julia(z, i+1) } // Turn a point on the complex plane into a color function pointToColor(point) { // How many iterations on this point before it escapes? var iterations = julia(point) // What percentage of our limit is that? var percentage = iterations/maxIterations var red = percentage*255 var green = percentage*255 var blue = percentage*255 // Create a color from that percentage return `rgb(${red}, ${green}, ${blue})` } // Turn XY pixel coordinates into a point on the complex plane function pixelToPoint(x, y) { // Map percentage of total width/height to a value from -1 to +1 var zx = (x/width)*2-1 var zy = 1-(y/height)*2 // Create a complex number based on our new XY values var z = math.complex(zx, zy) // Pan the camera z = z.add(pan) return z } // Draw a single pixel on our canvas function drawPixel(x, y, color) { ctx.fillStyle = color ctx.fillRect(x, y, 1, 1) } // Redraw our canvas function draw() { // Loop over every column of pixels for (var y = 0; y < height; y++) { // Loop over every row of pixels for (var x = 0; x < width; x++) { // Turn this pixel into a point in the complex plane var point = pixelToPoint(x, y) // Turn that point into a color var color = pointToColor(point) // Draw over this pixel with that color drawPixel(x, y, color) } } } // Update the elements that need to change function update() { header.innerHTML = constant.toString() draw() } function click(event) { // Ignore the first click if (!clicked) { clicked = true return } // Get the mouse's XY coordinates on canvas mouseX = event.clientX-canvas.offsetLeft mouseY = event.clientY-canvas.offsetTop // Turn mouse coordinates into a point on the complex plane pan = pixelToPoint(mouseX, mouseY) // Update everything! update() } // What to do when the mouse moves over the canvas function move(event) { // Don't move after first click if (clicked) { return } // Get the mouse's XY coordinates on canvas mouseX = event.clientX-canvas.offsetLeft mouseY = event.clientY-canvas.offsetTop // Turn mouse coordinates into a point on the complex plane constant = pixelToPoint(mouseX, mouseY) // Round that point off to the nearest 0.01 constant.re = math.round(constant.re*100)/100 constant.im = math.round(constant.im*100)/100 // Update everything! update() } // Trigger click every time the canvas is clicked canvas.addEventListener('click', click) // Trigger move every time the mouse moves over canvas canvas.addEventListener('pointermove', move) // Update everything! update() </script> ``` ## Zoom Almost done here… all we need now is a zoom feature. Add a new variable for `zoom`, just after `pan`: ```javascript // pan + the rest of your script... // How much we zoom the image var zoom = 1 // julia + the rest of your script... ``` Let's make it so every click _doubles_ the zoom value. We just need to add one new line to our `click` function for `zoom *= 2`: ```javascript // update + the rest of your script... // What to do when the mouse clicks the canvas function click(event) { // Ignore the first click if (!clicked) { clicked = true return } // Get the mouse's XY coordinates on canvas mouseX = event.clientX-canvas.offsetLeft mouseY = event.clientY-canvas.offsetTop // Turn mouse coordinates into a point on the complex plane pan = pixelToPoint(mouseX, mouseY) // Zoom in twice as far zoom *= 2 // Update everything! update() } // move + the rest of your script... ``` Now we need to change our `pixelToPoint` function to use that `zoom` value. Like `pan`, this is pretty simple—we just need to _divide_ each point by `zoom`, just before we add `pan`: ```javascript // pointToColor + the rest of your script... // Turn XY pixel coordinates into a point on the complex plane function pixelToPoint(x, y) { // Map percentage of total width/height to a value from -1 to +1 var zx = (x/width)*2-1 var zy = 1-(y/height)*2 // Create a complex number based on our new XY values var z = math.complex(zx, zy) // Zoom the camera z = z.div(zoom) // Pan the camera z = z.add(pan) return z } // drawPixel + the rest of your script... ``` Finally, let's make one last change to our `update` function so that it will tell us how far we have zoomed in: ```javascript // draw + the rest of your script... // Update the elements that need to change function update() { header.innerHTML = constant.toString() + " at " + zoom + "X" draw() } // click + the rest of your script... ``` Now if you run the page, you should be able to zoom in on the image with every click! ![Zooming in on the Julia Set](https://storage.googleapis.com/replit/images/1554409105068_8d1427fc76f2fce738f17a9328036a71.gi) Your final script should look like [this](https://repl.it/@polytrope/julia-fractals-click-zoom): ```html <script> // The HTML elements we are using var header = document.querySelector('h2') var canvas = document.querySelector('canvas') var ctx = canvas.getContext('2d') // The size of our canvas var width = 200 var height = 200 // Set the size of our canvas canvas.width = width canvas.height = height // The XY coordinates of the mouse over the canvas var mouseX = 0 var mouseY = 0 // The point we use for C in our Julia Set equation var constant = math.complex(0.28, 0.01) // The maximum number of times we iterate a point to see if it escapes var maxIterations = 64 // Whether we have clicked yet var clicked = false // How much we move the image var pan = math.complex(0, 0) // How much we zoom the image var zoom = 1 // Apply the Julia Set formula to see if point z "escapes" function julia(z, i = 0) { // Apply the Julia Set formula: z*z+constant z = z.mul(z) z = z.add(constant) // Has our point escaped, or hit the iteration limit? if (math.abs(z) > 2 || i == maxIterations) // If so, return number of iterations return i else // If not, iterate again! return julia(z, i+1) } // Turn a point on the complex plane into a color function pointToColor(point) { // How many iterations on this point before it escapes? var iterations = julia(point) // What percentage of our limit is that? var percentage = iterations/maxIterations var red = percentage*255 var green = percentage*255 var blue = percentage*255 // Create a color from that percentage return `rgb(${red}, ${green}, ${blue})` } // Turn XY pixel coordinates into a point on the complex plane function pixelToPoint(x, y) { // Map percentage of total width/height to a value from -1 to +1 var zx = (x/width)*2-1 var zy = 1-(y/height)*2 // Create a complex number based on our new XY values var z = math.complex(zx, zy) // Zoom the camera z = z.div(zoom) // Pan the camera z = z.add(pan) return z } // Draw a single pixel on our canvas function drawPixel(x, y, color) { ctx.fillStyle = color ctx.fillRect(x, y, 1, 1) } // Redraw our canvas function draw() { // Loop over every column of pixels for (var y = 0; y < height; y++) { // Loop over every row of pixels for (var x = 0; x < width; x++) { // Turn this pixel into a point in the complex plane var point = pixelToPoint(x, y) // Turn that point into a color var color = pointToColor(point) // Draw over this pixel with that color drawPixel(x, y, color) } } } // Update the elements that need to change function update() { header.innerHTML = constant.toString() + " at " + zoom + "X" draw() } // What to do when the mouse clicks the canvas function click(event) { // Ignore the first click if (!clicked) { clicked = true return } // Get the mouse's XY coordinates on canvas mouseX = event.clientX-canvas.offsetLeft mouseY = event.clientY-canvas.offsetTop // Turn mouse coordinates into a point on the complex plane pan = pixelToPoint(mouseX, mouseY) // Zoom in twice as far zoom *= 2 // Update everything! update() } // What to do when the mouse moves over the canvas function move(event) { // Don't move after first click if (clicked) { return } // Get the mouse's XY coordinates on canvas mouseX = event.clientX-canvas.offsetLeft mouseY = event.clientY-canvas.offsetTop // Turn mouse coordinates into a point on the complex plane constant = pixelToPoint(mouseX, mouseY) // Round that point off to the nearest 0.01 constant.re = math.round(constant.re*100)/100 constant.im = math.round(constant.im*100)/100 // Update everything! update() } // Trigger click every time the canvas is clicked canvas.addEventListener('click', click) // Trigger move every time the mouse moves over canvas canvas.addEventListener('pointermove', move) // Update everything! update() </script> ``` ## Epilogue There are all kinds of fractals. You can make [fractal trees](https://hackclub.com/workshops/tree_machine): ![An animated fractal tree](https://storage.googleapis.com/replit/images/1554409134230_31b982c99a6ec62437824c0773d690e0.gi) Or how about some [3D fractals](http://www.mandelbulb.com/): ![The Mandelbulb 3D fractal](https://storage.googleapis.com/replit/images/1554409160676_105015d72a68bfef7e23ea14627fe503.jpe) You can even grow [broccoli with fractals](https://en.wikipedia.org/wiki/Romanesco_broccoli) (yes this is real broccoli that you can buy at some supermarkets): ![An image of romanesco broccoli](https://storage.googleapis.com/replit/images/1554409200197_7428d9ef5c9ccc288dd66ffc3f8f0666.jpe) But fractals are just the beginning of what you can do with complex numbers. Complex numbers are _essential_ to everything from quantum physics to guitar amplifiers. Pretty remarkable for such a simple idea. Want to learn more stuff like this? I recommend checking out [3Blue1Brown](https://www.youtube.com/watch?v=QJYmyhnaaek). ### Sources * Thanks to Simpsons Contributor on Wikimedia for the [fractal zoom gif](https://en.wikipedia.org/wiki/File:Mandelbrot_sequence_new.gif) * Thanks to Rafael Ruggiero for the [fractal tree gif](https://commons.wikimedia.org/wiki/File:Fractal_tree.gif) * Thanks to the mandelbulb.com team for the [mandelbulb image](http://www.mandelbulb.com/3d-fractal-art-mandelmorphs/) * Thanks to Jon Sullivan on Wikimedia for his [image of romanesco broccoli](https://commons.wikimedia.org/wiki/File:Fractal_Broccoli.jpg)
4
posted by polytrope (16) 15 days ago
7
Bash Scripting
# Important Notice - This tutorial is a **work in progress**, expect more topics to be covered later - *Everything* in this tutorial works in Repl.it, unless stated otherwise - This is important to mention because it can overcome a suprising number of Repl.it's limitiations - This tutorial assumes that you have basic knowledge of programming, specifically variables and functions (also known as procedures, methods) ************** # What is Bash [Bash](https://www.gnu.org/software/bash/) (*B*ourne *A*gain *SH*ell) is a open-source shell for the GNU project (replacing the Bourne Shell). It is the *default* shell for most Linux distros, macOS aswell, and in Windows 10 via *[WSL](https://docs.microsoft.com/en-us/windows/wsl/faq)*. The bash *language* is a *shell scripting* language, used for configuration, package management, automation of routine tasks and more. It is similar in *purpose* to powershell and (somewhat less so with) applescript. Everything covered in this tutorial can be utilized in the Repl.it implemenation of Bash. The (non comprehensive) list of known limitations (as of April 2019): - unavailabilty sudo (for security reasons) - aplay command (audio programming is not possible) **************** # Basics of Bash ## Hello World The function `echo` and `printf` can be used to print to the terminal ```bash > echo "hello world!" #echo automatically appends a newline hello world #'-n' flag is used to remove the newline (echo -n "str") > printf "hello world!\n" hello world ``` I recommend `printf` if you need to format tabs or newline as it is more consistent across different terminals ************************* ## Everything is a string In bash *everything* is a `string` and what they do is dependent on context. Bash uses *spaces* as delimiters (seperators) so, `hello world` is converted to the strings `'hello'` and `'world'`. Use single or double quotes to make it a single string, ie: `"hello world"` or `'hello world'`. The *first* string in a line is used as the command ```bash > echo hello world #The strings are 'echo', 'hello', 'world' #The first string echo is the command #'hello' and 'world' are the first and second arguments ``` ### Note: `echo hello`, `echo "hello"`, `"echo" "hello"` are equivalent, but not `"echo hello"` as the former are two strings and the latter is one string ************ ## Variables It is important to be careful with spaces during assignment ```bash > Name=Amjad #assign "Amjad" to Name > Name =Amjad #call Name with argument "=Amjad" > Name = Amjad #call Name with arguments '=' and "Amjad" ``` The `$` in `$Hello` tells Bash to replace the *string* `Hello` with the *variable* `Hello`. ```bash > Name=Amjad #Mutable (non-constant) variables > echo $Name #The '$' is used Amjad ``` ### Reassignment & Constants ```bash > Name="Haya" #Reassignment > echo "$Name" #"$NAME" is equal to $NAME Haya > echo '"$NAME"' #'"$NAME"' is not equal to $NAME $NAME readonly Change="Constant" #Constant variables > Change="Changing" #Causes error as variable is constant ``` **************** ## Command Flags Flags are used to toggle specific options Single hypens '-' are used for *multiple* single letter flags ```bash > rm -rf "dir" rm #remove command -r #option: remove folders recursively f #option: remove files "dir" #directory to delete ``` Double hypens '-' are used for *one* multi-letter flag ```bash > git --help ``` ************ ## Functions ### Special Parameters ```bash $1 #First parameter $2 #Second parameter $n #Nth parameter $# #Number of parameters $? #Return value of most recent function $_ ``` ```bash #$* and [email protected] are identical if not quoted #Otherwise they are different "$*" = "$1 $2 $3 $4 ..." "[email protected]" = ""$1""$2""$3"..." ``` ### Function Declaration Functions are declared as follows ```bash fn_name(){ #arguments are not placed here #function body } fn_name args #function call ``` **************************** # Bash as a Control Language Bash is a fundamental domain specific language in linux, and serves as it's *control interface*, like Apple's applescript and Window's powershell It can be used to automate many routine tasks such as file management ## Linux File Commands The basic file system of Linux is structured as follows (Only relevant files are shown) The starting directory is called the *root* directory '`/`', which is *approximately* equivalent to `C:\` on windows ```bash /bin /home /user /Desktop ... /usr /etc ... ``` File Command are ```bash cd #change working (current) directory ls #list segments (folders) mkdir #make (new) directory (folder) rm #remove file or folder ``` ## Compiling with GCC [@Scoder12](https://repl.it/@Scoder12) had provided the general idea of using Bash to compile programs GCC, Make and Git and installed in Repl.it ### Makefiles Makefiles can be used to reduce compilation time by only compiling the changed files ```makefile #Makefile .PHONY: build_c gcc -o output source.c ./output .PHONY: build_cpp g++ -o output source.cpp ./output ``` ```bash > make build_c > make build_cpp ``` ### Linking Libraries ```bash > g++ -o main main.cpp -lNAME_OF_LIBRARY > g++ -o main main.cpp -lncurses #to link ncurses ``` Default Linux libraries (ncurses.h, unistd.h) are already included in Repl.it Any unavailable libraries ([SDL2](https://www.libsdl.org/download-2.0.php), [SFML](https://www.sfml-dev.org/download.php), ...) can be downloaded from their respective sites and then uploaded to Repl.it to be used in your project *or* cloned and compiled via git ### Assembly GCC can compile C or C++ to assembly ```c //source.c //C source int main(){ return 0; } ``` ```bash > gcc -S -o assembly.s source.c #Compile to assembly ``` ```nasm ; assembly.s ; Assembly output .file "main.c" .text .globl main .type main, @function main: .LFB0: .cfi_startproc movl $0, %eax ret .cfi_endproc .LFE0: .size main, .-main .ident "GCC: (GNU) 8.1.0" .section .note.GNU-stack,"",@progbits ``` ```bash > gcc -c -o program.o assembly.s #Assemble > gcc -o executable program.o #Linking > ./executable #Execution ``` ****** ## Git It can also be used to access git ```bash > git --help > git clone "git-repo-url" ```
6
posted by SigmaPhi (7) 17 days ago
4
Graphics with Go
# Getting started with graphics development in Golang on repl.it ### Introduction Who doesn't love golang? some people, maybe.But no can resist the cuteness of the gopher. Fact. ![gopher](https://storage.googleapis.com/replit/images/1554188001496_b0ed474d1ded6473b090ec87088ecf8e.pn) What I want to say is... I've found a way to do graphics in Go on repl.it. This post teaches you how to make a sample gopher screensaver using a framework called pixel. ![pixel](https://storage.googleapis.com/replit/images/1554188058370_76c7f7a05f0a3963485e0e638499f234.pn) Please note that much of the code is from [the original tutorials]( https://github.com/faiface/pixel/wiki). It strongly recommended to go through them if you do want to make a game in go. To be honest, this is more of a half-baked amalgamation of @eankeen 's [original pygame tutorial]( https://repl.it/talk/learn/A-Starter-Guide-to-Pygame/11741) and the tutorials The final result will look like this: ![giphy](https://storage.googleapis.com/replit/images/1554188108706_2e6b2e16497f79b500b7152c4e5e3a60.gi) A bit glitchy.Don't know why ### Getting started First, start by making a polygott repl [here](https://repl.it/languages/polygott). Or even better, fork my repl at https://repl.it/@Lord_Poseidon/NarrowCrookedExternalcommand. You would see a makefile. Paste this there and make a folder called `src` ``` .PHONY: dependencies run clean deppaths := github.com/faiface/pixel github.com/faiface/pixel/pixelgl golang.org/x/image/colornames gopath := /tmp/gopath run: dependencies cd src && GOPATH=$(gopath) go build -o /tmp/main-go TERM=xterm /tmp/main-go clean: rm -rf /tmp/main-go /tmp/gopath dependencies: GOPATH=$(gopath) go get $(deppaths) ``` Thanks to @superwhiskers for this code. The reason we are doing this is because repl does not have a Go package manager *yet* .That makefile gets our dependencies, then runs the code in the folder `src` . create a file main.go in src folder and code away!! my code is mostly from the original tutorials [here]( https://github.com/faiface/pixel/wiki/Moving,-scaling-and-rotating-with-Matrix) but these are the changes: #### Code changes: ```go pos:=pixel.V(100,300) horizadder,vertadder:=1.0,1.0 for !win.Closed() { pos=pos.Add(pixel.V(horizadder,vertadder)) mat:=pixel.IM win.Clear(colornames.Black) sprite.Draw(win, mat.Moved(pos)) if pos.X < 0 || pos.X > 800{ horizadder = -horizadder } if pos.Y < 0 || pos.Y > 600{ vertadder = -vertadder } win.Update() time.Sleep(16666666) } ``` just standard edge detection, speed changing, movement and delay. #### Path: the tutorials assume that the source directory is the working directory. This is not the case with us. You have to do `src/hiking.png` even if you already are in src directory. Also, I had to resize the original image to make it smaller #### Size of the window: the tutorials assume 1074 by 768 pixels. We at repl.it have only 800 by 600 *** Thanks again to @superwhiskers and @eankeen. If you do decide to make a game in go,let me know in the comments
0
posted by Lord_Poseidon (52) 18 days ago
14
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](https://hackr.io/blog/19-python-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](https://hackr.io/blog/numpy-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](https://en.wikipedia.org/wiki/Tensor) 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](https://hackr.io/tutorials/learn-python) now!
0
posted by VijaySingh1 (14) 18 days ago
30
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](https://en.wikipedia.org/wiki/Steganography) I was one of those chaps who actually solved the secret, but didn't do anything. The challenge can be found [here](https://repl.it/@timmy_i_chen/secret-announcement?ref=newsletter). 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](https://en.wikipedia.org/wiki/Bitwise_operation).shift_amt 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 public=Image.open('out.png').convert('RGB') secret=Image.new('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.save('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](https://storage.googleapis.com/replit/images/1553919764220_1470a455120ad93feec70c9423124f04.pn) waow indeed
10
posted by Lord_Poseidon (52) 21 days ago