Coding Articles
Basic coding terminology, planning your coding career, programming for web, freelancing tips, example coding projects, and more.
Articles From Coding
Filter Results
Cheat Sheet / Updated 11-14-2022
Coding, or computer programming, is your way of communicating with technology. It’s the new literacy you need to master to be successful in the coming decades. Like any form of communication, coding takes place through language. Just as there are many human languages (English, French, Mandarin, Spanish, and so on), there are many coding languages! Two examples of coding languages are Scratch and JavaScript. Scratch is perfect as a coding language for kids because it’s easy and fun to use, Scratch coding for kids allows you to build programs by snapping together commands in the same way you assemble a puzzle. JavaScript is a step up in difficulty because it’s an authentic programming language, used by real coders. JavaScript powers many technologies, and you can use it to make both apps for your phone and control code for operating electronics gadgets. You can ease into JavaScript by using blocks to build programs (just like Scratch) and then switching to text-based coding when you’re ready. Here, discover tips for creating programs in Scratch, coding JavaScript apps in App Lab, and writing JavaScript code in MakeCode to operate the micro:bit electronics board.
View Cheat SheetArticle / Updated 08-16-2022
One way of styling specific elements in CSS is to name your HTML elements. You name your code by using either the id or class attribute, and then style your code by referring to the id or class selector. Naming your code using the id attribute Use the id attribute to style one specific element on your web page. The id attribute can name any HTML element, and is always placed in the opening HTML tag. Additionally, each element can have only one id attribute value, and the attribute value must appear only once within the HTML file. After you define the attribute in the HTML file, you refer to the HTML element in your CSS by writing a hashtag (#) followed by the attribute value. Using the id attribute, the following code styles the Modern Seinfeld Twitter link the color red with a yellow background: HTML: <p><a href="http://twitter.com/SeinfeldToday" id="jerry">Modern Seinfeld</a></p> CSS: #jerry { color: red; background-color: yellow; } Naming your code using the class attribute Use the class attribute to style multiple elements on your web page. The class attribute can name any HTML element and is always placed in the opening HTML tag. The attribute value need not be unique within the HTML file. After you define the attribute in the HTML file, you refer to the HTML element by writing a period (.) followed by the attribute value. With the class attribute, the following code styles all the Parody Tech Twitter account links the color red with no underline: HTML: <ul> <li> <a href="<u>http://twitter.com/BoredElonMusk</u>" class="tech">Bored Elon Musk</a> </li> <li> <a href="<span style="text-decoration: underline;">http://twitter.com/VinodColeslaw</span>" class="tech">Vinod Coleslaw</a> </li> <li> <a href="<span style="text-decoration: underline;">http://twitter.com/Horse_ebooks</span>" class="tech">Horse ebooks</a> </li> </ul> CSS: .tech { color: red; text-decoration: none; } Proactively use a search engine, such as Google, to search for additional CSS effects. For example, if you want to increase the spacing between each list item, open your browser and search for list item line spacing css. Links appearing in the top ten results should include: W3Schools: A beginner tutorial site Stack Overflow: A discussion board for experienced developers Mozilla: A reference guide initially created by the foundation that maintains the Firefox browser and now maintained by a community of developers Each of these sites is a good place to start; be sure to look for answers that include example code.
View ArticleArticle / Updated 07-27-2022
Python is a general-purpose programming language typically used for web development. This may sound similar to Ruby, and really both languages are more similar than they are different. Python, like Ruby, allows for storing data after the user has navigated away from the page or closed the browser, unlike HTML, CSS, and JavaScript. Using Python commands you can create, update, store, and retrieve this data in a database. For example, imagine you wanted to create a local search and ratings site like Yelp.com. The reviews users write are stored in a central database. Any review author can exit the browser, turn off the computer, and come back to the website later to find their reviews. Additionally, when others search for venues, this same central database is queried, and the same review is displayed. Storing data in a database is a common task for Python developers, and existing Python libraries include pre-built code to easily create and query databases. SQLite is one free lightweight database commonly used by Python programmers to store data. Many highly trafficked websites, such as YouTube, are created using Python. Other websites currently using Python include: Quora for its community question and answer site. Spotify for internal data analysis. Dropbox for its desktop client software. Reddit for generating crowd-sourced news. Industrial Light & Magic and Disney Animation for creating film special effects. From websites to software to special effects, Python is an extremely versatile language, powerful enough to support a range of applications. In addition, to help spread Python code, Python programmers create libraries, which are stand-alone pre-written code that do certain tasks, and make them publicly available for others to use and improve. For example, a library called Scrapy performs web scaping, while another library called SciPy performs math functions used by scientists and mathematicians. The Python community maintains thousands of libraries like these, and most are free and open-source software. You can generally confirm the front-end programming language used by any major website with BuiltWith. After entering the website address in the search bar, look under the Frameworks section for Python. Note that websites may use Python for backend services not visible to BuiltWith.
View ArticleArticle / Updated 07-27-2022
Dates can present problems in data. For one thing, dates are stored as numeric values. However, the precise value of the number depends on the representation for the particular platform and could even depend on the users’ preferences. For example, Excel users can choose to start dates in 1900 or 1904. The numeric encoding for each is different, so the same date can have two numeric values depending on the starting date. In addition to problems of representation, you also need to consider how to work with time values. Creating a time value format that represents a value the user can understand is hard. For example, you might need to use Greenwich Mean Time (GMT) in some situations but a local time zone in others. Transforming between various times is also problematic. Formatting date and time values Obtaining the correct date and time representation can make performing analysis a lot easier. For example, you often have to change the representation to obtain a correct sorting of values. Python provides two common methods of formatting date and time. The first technique is to call str(), which simply turns a datetime value into a string without any formatting. The strftime() function requires more work because you must define how you want the datetime value to appear after conversion. When using strftime(), you must provide a string containing special directives that define the formatting. Now that you have some idea of how time and date conversions work, it’s time to see an example. The following example creates a datetime object and then converts it into a string using two different approaches: import datetime as dt now = dt.datetime.now() print str(now) print now.strftime('%a, %d %B %Y') In this case, you can see that using str() is the easiest approach. However, as shown by the following output, it may not provide the output you need. Using strftime() is infinitely more flexible. 2017-01-16 17:26:45.986000 Mon, 16 January 2017 Using the right time transformation Time zones and differences in local time can cause all sorts of problems when performing analysis. For that matter, some types of calculations simply require a time shift in order to get the right results. No matter what the reason, you may need to transform one time into another time at some point. The following examples show some techniques you can employ to perform the task. import datetime as dt now = dt.datetime.now() timevalue = now + dt.timedelta(hours=2) print now.strftime('%H:%M:%S') print timevalue.strftime('%H:%M:%S') print timevalue - now The timedelta() function makes the time transformation straightforward. You can use any of these parameter names with timedelta() to change a time and date value: days seconds microseconds milliseconds minutes hours weeks You can also manipulate time by performing addition or subtraction on time values. You can even subtract two time values to determine the difference between them. Here’s the output from this example: 17:44:40 19:44:40 2:00:00 Notice that now is the local time, timevalue is two time zones different from this one, and there is a two-hour difference between the two times. You can perform all sorts of transformations using these techniques to ensure that your analysis always shows precisely the time-oriented values you need.
View ArticleArticle / Updated 07-27-2022
There are many tools available to help coders do their best work. Before you start coding, do a few housekeeping items. First, ensure that you are doing all of the following: Using the Chrome browser: Download and install the latest version of Chrome, as it offers the most support for the latest HTML standards. Working on a desktop or laptop computer: Although it is possible to code on a mobile device, it can be more difficult and all layouts may not appear properly. Remembering to indent your code to make it easier to read: One main source of mistakes is forgetting to close a tag or curly brace, and indenting your code will make spotting these errors easier. Remembering to enable location services on your browser and computer: To enable location services within Chrome, click on the settings icon (three horizontal lines on the top right of the browser), and click on Settings. Then click on the Settings tab, and at the bottom of the screen click on “Show Advanced settings … ” Under the Privacy menu heading, click on “Content settings … ” and scroll down to Location and make sure that “Ask when a site tries to track your physical location” is selected. To enable location services on a PC no additional setting is necessary, but on a Mac using OS X Mountain Lion or later, from the Apple menu choose System Preferences, then click on the Security & Privacy icon, and click the Privacy tab. Click the padlock icon on the lower left, and select Location Services, and check Enable Location Services. Finally, you need to set up your development environment. To emulate a development environment without instructional content use Codepen.io. Codepen.io offers a free stand-alone development environment, and makes it easy to share your code.
View ArticleArticle / Updated 07-14-2022
When coding, it’s important to teach kids the basics of setting and finding position. Setting the position of an object means assigning it coordinates to put it in a specific place onscreen. Finding the position of an object means identifying its coordinates to know where it’s located. Using pseudocode While each programming language uses its own structure for setting and finding coordinates, a typical pseudocode expression you may write to set the position of an object looks like this: setx <em>x-coordinate</em> sety <em>y-coordinate</em> Or setposition <em>(x-coordinate, y-coordinate)</em> To find the current position of an object, you can write pseudocode for each separate coordinate: x-position for the x-coordinate of the object, and y-position for the y-coordinate of the object. You can also write position to describe the object position as a coordinate pair. Using Scratch to set position To set the x-coordinate of an object in Scratch, use the set x to <em>number</em> command in the Motion category. The minimum value of the x-coordinate ranges is -240, and the maximum value is 240. To set the y-coordinate of an object in Scratch, use the set y to <em>number</em> command in the Motion category. The minimum value of the y-coordinate ranges is -180, and the maximum value is 180. To set both the x-coordinate and y-coordinate of an object in Scratch, use the go to x: <em>number</em> y: <em>number</em> command in the Motion category. The range of the x-coordinate value is -240 to 240, and the range of the y-coordinate value is -180 to 180. In Scratch, you can set the size of an object using the set size to number % command in the Looks category. This sets the size of the object as a percentage of its original size. Percentages smaller than 100 shrink the object. Percentages larger than 100 grow the object. Using Scratch to find position To find the x-coordinate of an object in Scratch, use the x position command in the Motion category. To find the y-coordinate of an object in Scratch, use the y position command in the Motion category. You and your coder can use these commands in your programs when you need to write commands that require information about an object's position. As you code, sometimes you want to position an object (sprite) onscreen and then get its coordinates. You can do this for any sprite using either of these methods: Select the checkbox next to the x position command and the y position command in the Motion category to show these values onscreen. On the thumbnail of the sprite, click the “i” icon to expand its information center and then view the x: and y: values displayed there. In both methods, the coordinates of Scratch Cat are (60, -18). Using JavaScript To set both the x-coordinate and y-coordinate of an object in JavaScript, identify the object you want to position, and then use the setPosition command. Here are the steps for how to position an image of a mouse onscreen in the Code.org App Lab, using JavaScript. In App Lab, click the Design button above the emulator of the mobile device. In the Workspace, select Image → Choose. The Choose Assets dialog box opens. Click the Upload button. Select the file you want, and then click the Choose button. The uploaded file appears in the dialog box. The name of the uploaded image file shown here is mouse.png. In the App Lab program workspace, type these commands: >image("character", "mouse.png"); setPosition("character", 160, 225, 100, 100); Here is what these commands do: The first command creates an image reference identification, character, and links the file, mouse.png, to this identification. The second command displays the image in character according to four quantities: the x-coordinate of the object, the y-coordinate of the object, the width of the object in pixels, and the height of the object in pixels. In App Lab, the range of the x-coordinate value is 0 to 320, and the range of the y-coordinate value is 0 to 450. When using JavaScript to program images displayed on a webpage, these values have larger maximum values, representing the larger size of a computer screen. The image below shows the mouse positioned at the coordinates (160, 225), which is the exact center of the screen. You can see that the mouse is positioned by its upper-left corner where the tip of its tail is located. The mouse has a width of 100 pixels and a height of 100 pixels. To find the x-coordinate of an object in JavaScript, use the getXPosition("character"); command where character is the identification reference of the object. To find the y-coordinate of an object in JavaScript, use the getYPosition("character"); command where character is the identification reference of the object. You and your coder can write the following code to find and display onscreen the coordinates of an object named character. This assumes you have uploaded an image file and assigned it to the reference identification, character. Type this code in the App Lab program workspace. var x = getXPosition("character"); var y = getYPosition("character"); textLabel("xcor"); textLabel("ycor"); setText("xcor", "x-coordinate is " + x); setText("ycor", "y-coordinate is " + y); Here is how this code works: The var x variable gets the x position and the var y variable gets the y position of the object. The two textLabel commands create locations onscreen, called xcor and ycor, to display information. Each setText command displays a value in a text label. The value of x displays in the xcor label and the value of y displays in the ycor
View ArticleCheat Sheet / Updated 06-30-2022
Coding is equal parts vocabulary, logic, and syntax. Coding may at first seem intimidating, but with practice, though, it's easy to get comfortable with its terminology, concepts, and structure. Understanding coding is not unlike learning a new language: Use it often enough and you'll find yourself able to speak, think, and write in code. Still, it's natural for beginners to have questions. There are many coding resources available to you, both on- and off-line. Ask around and you'll find you're not alone — many other people are learning. After all, coding is a never-ending education. Master one facet or another and a new one opens in front of you.
View Cheat SheetCheat Sheet / Updated 04-27-2022
Coding is fast becoming a skill that every child needs to be educated for in the 21st Century. But coding is taught at only a small fraction of schools, and often only at the high school level. Helping kids learn how to code also means you’re assisting them in developing a skill that is highly marketable and sets them apart from peers at school and later, in their careers. The topics in this cheat sheet can assist you on getting started when your kid expresses an interest in learning how to code.
View Cheat SheetCheat Sheet / Updated 01-19-2022
Coding is equal parts vocabulary, logic, and syntax. Coding may at first seem intimidating, but with practice, though, it’s easy to get comfortable with its terminology, concepts, and structure. Understanding coding is not unlike learning a new language: Use it often enough and you’ll find yourself able to speak, think, and write in code. Still, it’s natural for beginners to have questions. There are many coding resources available to you, both on- and off-line. Ask around and you’ll find you’re not alone — many other people are learning. After all, coding is a never-ending education. Master one facet or another and a new one opens in front of you.
View Cheat SheetArticle / Updated 07-01-2020
Unstructured data files consist of a series of bits. The file doesn’t separate the bits from each other in any way. You can’t simply look into the file and see any structure because there isn’t any to see. Unstructured file formats rely on the file user to know how to interpret the data. For example, each pixel of a picture file could consist of three 32-bit fields. Knowing that each field is 32-bits is up to you. A header at the beginning of the file may provide clues about interpreting the file, but even so, it’s up to you to know how to interact with the file. This example shows how to work with a picture as an unstructured file. The example image is a public domain offering from commons.wikimedia.org. To work with images, you need to access the scikit-image library, which is a free-of-charge collection of algorithms used for image processing. Here’s a tutorial for this library. The first task is to be able to display the image on-screen using the following code. (This code can require a little time to run. The image is ready when the busy indicator disappears from the IPython Notebook tab.) from skimage.io import imread from skimage.transform import resize from matplotlib import pyplot as plt import matplotlib.cm as cm example_file = ("http://upload.wikimedia.org/" + "wikipedia/commons/7/7d/Dog_face.png") image = imread(example_file, as_grey=True) plt.imshow(image, cmap=cm.gray) plt.show() The code begins by importing a number of libraries. It then creates a string that points to the example file online and places it in example_file. This string is part of the imread() method call, along with as_grey, which is set to True. The as_grey argument tells Python to turn color images into grayscale. Any images that are already in grayscale remain that way. Now that you have an image loaded, it’s time to render it (make it ready to display on-screen. The imshow() function performs the rendering and uses a grayscale color map. The show() function actually displays image for you. Close the image when you’re finished viewing it. (The asterisk in the In [*]: entry tells you that the code is still running and you can’t move on to the next step.) The act of closing the image ends the code segment. You now have an image in memory, and you may want to find out more about it. When you run the following code, you discover the image type and size: print("data type: %s, shape: %s" % (type(image), image.shape)) The output from this call tells you that the image type is a numpy.ndarray and that the image size is 90 pixels by 90 pixels. The image is actually an array of pixels that you can manipulate in various ways. For example, if you want to crop the image, you can use the following code to manipulate the image array: image2 = image[5:70,0:70] plt.imshow(image2, cmap=cm.gray) plt.show() The numpy.ndarray in image2 is smaller than the one in image, so the output is smaller as well. Typical results are shown below. The purpose of cropping the image is to make it a specific size. Both images must be the same size for you to analyze them. Cropping is one way to ensure that the images are the correct size for analysis. Another method that you can use to change the image size is to resize it. The following code resizes the image to a specific size for analysis: image3 = resize(image2, (30, 30), mode='nearest') plt.imshow(image3, cmap=cm.gray) print("data type: %s, shape: %s" % (type(image3), image3.shape)) The output from the print() function tells you that the image is now 30 pixels by 30 pixels in size. You can compare it to any image with the same dimensions. After you have all the images in the right size, you need to flatten them. A data set row is always a single dimension, not two dimensions. The image is currently an array of 30 pixels by 30 pixels, so you can’t make it part of a data set. The following code flattens image3 so that it becomes an array of 900 elements that is stored in image_row: image_row = image3.flatten() print("data type: %s, shape: %s" % (type(image_row), image_row.shape)) Notice that the type is still a numpy.ndarray. You can add this array to a data set and then use the data set for analysis purposes. The size is 900 elements, as anticipated.
View Article