Technology Articles
Technology. It makes the world go 'round. And whether you're a self-confessed techie or a total newbie, you'll find something to love among our hundreds of technology articles and books.
Articles From Technology
Filter Results
Article / Updated 10-28-2024
The simplest data collection in Python is a list. A list is any list of data items, separated by commas, inside square brackets. Typically, you assign a name to the Python list using an = sign, just as you would with variables. If the list contains numbers, then don't use quotation marks around them. For example, here is a list of test scores: scores = [88, 92, 78, 90, 98, 84] If the list contains strings then, as always, those strings should be enclosed in single or double quotation marks, as in this example: To display the contents of a list on the screen, you can print it just as you would print any regular variable. For example, executing print(students) in your code after defining that list shows this on the screen. ['Mark', 'Amber', 'Todd', 'Anita', 'Sandy'] This may not be exactly what you had in mind. But don’t worry, Python offers lots of great ways to access data in lists and display it however you like. Referencing Python list items by position Each item in a list has a position number, starting with zero, even though you don’t see any numbers. You can refer to any item in the list by its number using the name for the list followed by a number in square brackets. In other words, use this syntax: <em>listname</em>[<em>x</em>] Replace <em><code>listname</code></em> with the name of the list you're accessing and replace <em><code>x</code></em> with the position number of item you want. Remember, the first item is always number zero, not one. For example, in the first line below, I define a list named <code>students</code>, and then print item number zero from that list. The result, when executing the code, is that the name <code>Mark</code> is displayed. students = ["Mark", "Amber", "Todd", "Anita", "Sandy"] print(students[0]) Mark When reading access list items, professionals use the word sub before the number. For example, students[0] would be spoken as students sub zero. This next example shows a list named scores. The print() function prints the position number of the last score in the list, which is 4 (because the first one is always zero). scores = [88, 92, 78, 90, 84] print(scores[4]) 84 If you try to access a list item that doesn't exist, you get an “index out of range” error. The index part is a reference to the number inside the square brackets. For example, the image below shows a little experiment in a Jupyter notebook where a list of scores was created and then the printing of score[5] was attempted. It failed and generated an error because there is no scores[5]. There's only scores[0], scores[1], scores[2], scores[3], and scores[4] because the counting always starts at zero with the first one on the list. Looping through a Python list To access each item in a list, just use a for loop with this syntax: for <em>x</em> in <em>list</em>: Replace >x with a variable name of your choosing. Replace list with the name of the list. An easy way to make the code readable is to always use a plural for the list name (such as students, scores). Then you can use the singular name (student, score) for the variable name. You don't need to use subscript numbers (numbers in square brackets) with this approach either. For example, the following code prints each score in the scores list: for score in scores: print(score) Remember to always indent the code that’s to be executed within the loop. This image shows a more complete example where you can see the result of running the code in a Jupyter notebook. Seeing whether a Python list contains an item If you want your code to check the contents of a list to see whether it already contains some item, use in <em>listname</em> in an if statement or a variable assignment. For example, the code in the image below creates a list of names. Then, two variables store the results of searching the list for the names Anita and Bob. Printing the contents of each variable shows True for the one where the name (Anita) is in the list. The test to see whether Bob is in the list proves False. Getting the length of a Python list To determine how many items are in a list, use the len() function (short for length). Put the name of the list inside the parentheses. For example, type the following code into a Jupyter notebook or Python prompt or whatever: students = ["Mark", "Amber", "Todd", "Anita", "Sandy"] print(len(students)) Running that code produces this output: 5 There are indeed five items in the list, though the last one is always one less than the number because Python starts counting at zero. So the last one, Sandy, actually refers to students[4] and not students[5]. Appending an item to the end of a Python list When you want your Python code to add a new item to the end of a list, use the .append() method with the value you want to add inside the parentheses. You can use either a variable name or a literal value inside the quotation marks. For instance, in the following image the line that reads students.append("Goober") adds the name Goober to the list. The line that reads students.append(new_student) adds whatever name is stored in the variable named new_student to the list. The .append() method always adds to the end of the list. So when you print the list you see those two new names at the end. You can use a test to see whether an item is in a list and then append it only when the item isn't already there. For example, the code below won’t add the name Amber to the list because that name is already in the list: student_name = "Amanda" #Add student_name but only if not already in the list. if student_name in students: print (student_name + " already in the list") else: students.append(student_name) print (student_name + " added to the list") Inserting an item into a Python list Although the append() method allows you to add an item to the end of a list, the insert() method allows you to add an item to the list in any position. The syntax for insert() is <em>listname</em>.insert(<em>position</em>, <em>item</em>) Replace listname with the name of the list, position with the position at which you want to insert the item (for example, 0 to make it the first item, 1 to make it the second item, and so forth). Replace item with the value, or the name of a variable that contains the value, that you want to put into the list. For example, the following code makes Lupe the first item in the list: #Create a list of strings (names). students = ["Mark", "Amber", "Todd", "Anita", "Sandy"] student_name = "Lupe" # Add student name to front of the list. students.insert(0,student_name) #Show me the new list. print(students) If you run the code, print(students) will show the list after the new name has been inserted, as follows: ['Lupe', 'Mark', 'Amber', 'Todd', 'Anita', 'Sandy'] Changing an item in a Python list You can change an item in a list using the = assignment operator (check out these common Python operators) just like you do with variables. Just make sure you include the index number in square brackets of the item you want to change. The syntax is: listname[index]=newvalue Replace listname with the name of the list; replace index with the subscript (index number) of the item you want to change; and replace newvalue with whatever you want to put in the list item. For example, take a look at this code: #Create a list of strings (names). students = ["Mark", "Amber", "Todd", "Anita", "Sandy"] students[3] = "Hobart" print(students) When you run this code, the output is as follows, because Anita's name has been changed to Hobart. ['Mark', 'Amber', 'Todd', 'Hobart', 'Sandy'] Combining Python lists If you have two lists that you want to combine into a single list, use the extend() function with the syntax: <em>original_list</em>.extend(<em>additional_items_list</em>) In your code, replace original_list with the name of the list to which you’ll be adding new list items. Replace additional_items_list with the name of the list that contains the items you want to add to the first list. Here is a simple example using lists named list1 and list2. After executing list1.extend(list2), the first list contains the items from both lists, as you can see in the output of the print() statement at the end. # Create two lists of Names. list1 = ["Zara", "Lupe", "Hong", "Alberto", "Jake"] list2 = ["Huey", "Dewey", "Louie", "Nader", "Bubba"] # Add list2 names to list1. list1.extend(list2) # Print list 1. print(list1) ['Zara', 'Lupe', 'Hong', 'Alberto', 'Jake', 'Huey', 'Dewey', 'Louie', 'Nader', 'Bubba'] Easy Parcheesi, no? Removing Python list items Python offers a remove() method so you can remove any value from the list. If the item is in the list multiple times, only the first occurrence is removed. For example, the following code shows a list of letters with the letter C repeated a few times. Then the code uses letters.remove("C") to remove the letter C from the list: # Remove "C" from the list. letters.remove("C") #Show me the new list. print(letters) When you actually execute this code and then print the list, you'll see that only the first letter C has been removed: ['A', 'B', 'D', 'C', 'E', 'C'] If you need to remove all of an item, you can use a while loop to repeat the .remove as long as the item still remains in the list. For example, this code repeats the .remove as long as the “C” is still in the list. #Create a list of strings. letters = ["A", "B", "C", "D", "C", "E", "C"] If you want to remove an item based on its position in the list, use pop() with an index number rather than remove() with a value. If you want to remove the last item from the list, use pop() without an index number. For example, the following code creates a list, one line removes the first item (0), and another removes the last item (pop() with nothing in the parentheses). Printing the list shows those two items have been removed: #Create a list of strings. letters = ["A", "B", "C", "D", "E", "F", "G"] #Remove the first item. letters.pop(0) #Remove the last item. letters.pop() #Show me the new list. print(letters) Running the code shows that the popping the first and last items did, indeed, work: ['B', 'C', 'D', 'E', 'F'] When you pop() an item off the list, you can store a copy of that value in some variable. For example this image shows the same code as above. However, it stores copies of what's been removed in variables named first_removed and last_removed. At the end it prints the Python list, and also shows which letters were removed. Python also offers a del (short for delete) command that deletes any item from a list based on its index number (position). But again, you have to remember that the first item is zero. So, let's say you run the following code to delete item number 2 from the list: # Create a list of strings. letters = ["A", "B", "C", "D", "E", "F", "G"] # Remove item sub 2. del letters[2] print(letters) Running that code shows the list again, as follows. The letter C has been deleted, which is the correct item to delete because letters are numbered 0, 1, 2, 3, and so forth. ['A', 'B', 'D', 'E', 'F', 'G'] You can also use del to delete an entire list. Just don’t use the square brackets and the index number. For example, the code you see below creates a list then deletes it. Trying to print the list after the deletion causes an error, because the list no longer exists when the print() statement is executed. Clearing out a Python list If you want to delete the contents of a list but not the list itself, use .clear(). The list still exists; however, it contains no items. In other words, it's an empty list. The following code shows how you could test this. Running the code displays [] at the end, which lets you know the list is empty: # Create a list of strings. letters = ["A", "B", "C", "D", "E", "F", "G"] # Clear the list of all entries. letters.clear() # Show me the new list. print(letters) Counting how many times an item appears in a Python list You can use the Python count() method to count how many times an item appears in a list. As with other list methods, the syntax is simple: <em>listname</em>.count(<em>x</em>) Replace listname with the name of your list, and x with the value you're looking for (or the name of a variable that contains that value). The code in the image below counts how many times the letter B appears in the list, using a literal B inside the parentheses of .count(). This same code also counts the number of C grades, but that value was stored in a variable just to show the difference in syntax. Both counts worked, as you can see in the output of the program at the bottom. One was added to count the F's, not using any variables. The F’s were counted right in the code that displays the message. There are no F grades, so this returns zero, as you can see in the output. When trying to combine numbers and strings to form a message, remember you have to convert the numbers to strings using the str() function. Otherwise, you get an error that reads something like can only concatenate str (not "int") to str. In that message, int is short for integer, and str is short for string. Finding a Python list item's index Python offers an .index() method that returns a number indicating the position, based on index number, of an item in a list. The syntax is: <em>listname</em>.index(<em>x</em>) As always, replace listname with name of the list you want to search. Replace x what whatever you're looking for (either as a literal or as a variable name, as always). Of course, there’s no guarantee that the item is in the list, and even if it is, there’s no guarantee that the item is in the list only once. If the item isn’t in the list, then an error occurs. If the item is in the list multiple times, then the index of the first matching item is returned. The following image shows an example where the program crashes at the line f_index = grades.index(look_for) because there is no F in the list. An easy way to get around that problem is to use an if statement to see whether an item is in the list before you try to get its index number. If the item isn't in the list, display a message saying so. Otherwise, get the index number and show it in a message. That code is as follows: # Create a list of strings. grades = ["C", "B", "A", "D", "C", "B", "C"] # Decide what to look for look_for = "F" # See if the item is in the list. if look_for in grades: # If it's in the list, get and show the index. print(str(look_for) + " is at index " + str(grades.index(look_for))) else: # If not in the list, don't even try for index number. print(str(look_for) + " isn't in the list.") Alphabetizing and sorting Python lists Python offers a sort() method for sorting lists. In its simplest form, it alphabetizes the items in the list (if they’re strings). If the list contains numbers, they’re sorted smallest to largest. For a simple sort like that, just use sort() with empty parentheses: <em>listname</em>.sort() Replace listname with the name of your list. The following image shows an example using a list of strings and a list of numbers. In the example, a new list was created for each of them simply by assigning each sorted list to a new list name. Then the code prints the contents of each sorted list. If your list contains strings with a mixture of uppercase and lowercase letters, and if the results of the sort don't look right, try replacing .sort() with .sort(key=lambda s:s.lower()) and then running the code again. Dates are a little trickier because you can’t just type them in as strings, like "12/31/2020". They have to be the date data type to sort correctly. This means using the datetime module and the date() method to define each date. You can add the dates to the list as you would any other list. For example, in the following line, the code creates a list of four dates, and the code is perfectly fine. dates = [dt.date(2020,12,31), dt.date(2019,1,31), dt.date(2018,2,28), dt.date(2020,1,1)] The computer certainly won't mind if you create the list this way. But if you want to make the code more readable to yourself or other developers, you may want to create and append each date, one at a time, so just so it’s a little easier to see what’s going on and so you don’t have to deal with so many commas in one line of code. The image below shows an example where an empty list named datelist was created: datelist = [] Then one date at a time was appended to the list using the dt.date(<em>year</em>,<em>month</em>,<em>day</em>) syntax. After the list is created, the code uses datelist.sort() to sort them into chronological order (earliest to latest). You don’t need to use print(datelist) in that code because that method displays the dates with the data type information included, like this: [datetime.date(2018, 2, 28), datetime.date(2019, 1, 31), datetime.date (2020, 1, 1), datetime.date(2020, 12, 31)] Not the easiest list to read. So, rather than print the whole list with one print() statement, you can loop through each date in the list, and printed each one formatted with the f-string %m/%d/%Y. This displays each date on its own line in mm/dd/yyyy format, as you can see at the bottom of the image above. If you want to sort items in reverse order, put reverse=True inside the sort() parentheses (and don't forget to make the first letter uppercase). The image below shows examples of sorting all three lists in descending (reverse) order using reverse=True. Reversing a Python list You can also reverse the order of items in a list using the .reverse method. This is not the same as sorting in reverse, because when you sort in reverse, you still actually sort: Z–A for strings, largest to smallest for numbers, latest to earliest for dates. When you reverse a list, you simply reverse the items in the list, no matter their order, without trying to sort them in any way. The following code shows an example in which you reverse the order of the names in the list and then print the list. The output shows the list items reversed from their original order: # Create a list of strings. names = ["Zara", "Lupe", "Hong", "Alberto", "Jake"] # Reverse the list names.reverse() # Print the list print(names) ['Jake', 'Alberto', 'Hong', 'Lupe', 'Zara'] Copying a Python list If you ever need to work with a copy of a list, use the .copy() method so as not to alter the original list,. For example, the following code is similar to the preceding code, except that instead of reversing the order of the original list, you make a copy of the list and reverse that one. Printing the contents of each list shows how the first list is still in the original order whereas the second one is reversed: # Create a list of strings. names = ["Zara", "Lupe", "Hong", "Alberto", "Jake"] # Make a copy of the list backward_names = names.copy() # Reverse the copy backward_names.reverse() # Print the list print(names) print(backward_names) ['Zara', 'Lupe', 'Hong', 'Alberto', 'Jake'] ['Jake', 'Alberto', 'Hong', 'Lupe', 'Zara'] For future references, the following table summarizes the methods you've learned about. Methods for Working with Lists Method What it Does append() Adds an item to the end of the list. clear() Removes all items from the list, leaving it empty. copy() Makes a copy of a list. count() Counts how many times an element appears in a list. extend() Appends the items from one list to the end of another list. index() Returns the index number (position) of an element within a list. insert() Inserts an item into the list at a specific position. pop() Removes an element from the list, and provides a copy of that item that you can store in a variable. remove() Removes one item from the list. reverse() Reverses the order of items in the list. sort() Sorts the list in ascending order. Put reverse=True inside the parentheses to sort in descending order.
View ArticleArticle / Updated 10-28-2024
Bayes’ theorem can help you deduce how likely something is to happen in a certain context, based on the general probabilities of the fact itself and the evidence you examine, and combined with the probability of the evidence given the fact. Seldom will a single piece of evidence diminish doubts and provide enough certainty in a prediction to ensure that it will happen. As a true detective, to reach certainty, you have to collect more evidence and make the individual pieces work together in your investigation. Noticing that a person has long hair isn’t enough to determine whether person is female or a male. Adding data about height and weight could help increase confidence. The Naïve Bayes algorithm helps you arrange all the evidence you gather and reach a more solid prediction with a higher likelihood of being correct. Gathered evidence considered singularly couldn’t save you from the risk of predicting incorrectly, but all evidence summed together can reach a more definitive resolution. The following example shows how things work in a Naïve Bayes classification. This is an old, renowned problem, but it represents the kind of capability that you can expect from an AI. The dataset is from the paper “Induction of Decision Trees,” by John Ross Quinlan. Quinlan is a computer scientist who contributed to the development of another machine learning algorithm, decision trees, in a fundamental way, but his example works well with any kind of learning algorithm. The problem requires that the AI guess the best conditions to play tennis given the weather conditions. The set of features described by Quinlan is as follows: Outlook: Sunny, overcast, or rainy Temperature: Cool, mild, or hot Humidity: High or normal Windy: True or false The following table contains the database entries used for the example: Outlook Temperature Humidity Windy PlayTennis Sunny Hot High False No Sunny Hot High True No Overcast Hot High False Yes Rainy Mild High False Yes Rainy Cool Normal False Yes Rainy Cool Normal True No Overcast Cool Normal True Yes Sunny Mild High False No Sunny Cool Normal False Yes Rainy Mild Normal False Yes Sunny Mild Normal True Yes Overcast Mild High True Yes Overcast Hot Normal False Yes Rainy Mild High True No The option of playing tennis depends on the four arguments shown here. The result of this AI learning example is a decision as to whether to play tennis, given the weather conditions (the evidence). Using just the outlook (sunny, overcast, or rainy) won’t be enough, because the temperature and humidity could be too high or the wind might be strong. These arguments represent real conditions that have multiple causes, or causes that are interconnected. The Naïve Bayes algorithm is skilled at guessing correctly when multiple causes exist. The algorithm computes a score, based on the probability of making a particular decision and multiplied by the probabilities of the evidence connected to that decision. For instance, to determine whether to play tennis when the outlook is sunny but the wind is strong, the algorithm computes the score for a positive answer by multiplying the general probability of playing (9 played games out of 14 occurrences) by the probability of the day’s being sunny (2 out of 9 played games) and of having windy conditions when playing tennis (3 out of 9 played games). The same rules apply for the negative case (which has different probabilities for not playing given certain conditions): likelihood of playing: 9/14 * 2/9 * 3/9 = 0.05 likelihood of not playing: 5/14 * 3/5 * 3/5 = 0.13 Because the score for the likelihood is higher, the algorithm decides that it’s safer not to play under such conditions. It computes such likelihood by summing the two scores and dividing both scores by their sum: probability of playing : 0.05 / (0.05 + 0.13) = 0.278 probability of not playing : 0.13 / (0.05 + 0.13) = 0.722 You can further extend Naïve Bayes to represent relationships that are more complex than a series of factors that hint at the likelihood of an outcome using a Bayesian network, which consists of graphs showing how events affect each other. Bayesian graphs have nodes that represent the events and arcs showing which events affect others, accompanied by a table of conditional probabilities that show how the relationship works in terms of probability. The figure shows a famous example of a Bayesian network taken from a 1988 academic paper, “Local computations with probabilities on graphical structures and their application to expert systems,” by Lauritzen, Steffen L. and David J. Spiegelhalter, published by the Journal of the Royal Statistical Society. The depicted network is called Asia. It shows possible patient conditions and what causes what. For instance, if a patient has dyspnea, it could be an effect of tuberculosis, lung cancer, or bronchitis. Knowing whether the patient smokes, has been to Asia, or has anomalous x-ray results (thus giving certainty to certain pieces of evidence, a priori in Bayesian language) helps infer the real (posterior) probabilities of having any of the pathologies in the graph. Bayesian networks, though intuitive, have complex math behind them, and they’re more powerful than a simple Naïve Bayes algorithm because they mimic the world as a sequence of causes and effects based on probability. Bayesian networks are so effective that you can use them to represent any situation. They have varied applications, such as medical diagnoses, the fusing of uncertain data arriving from multiple sensors, economic modeling, and the monitoring of complex systems such as a car. For instance, because driving in highway traffic may involve complex situations with many vehicles, the Analysis of MassIve Data STreams (AMIDST) consortium, in collaboration with the automaker Daimler, devised a Bayesian network that can recognize maneuvers by other vehicles and increase driving safety.
View ArticleArticle / Updated 10-28-2024
YouTube is a video-sharing website where users post all kinds of media. YouTube is so popular that it has one billion unique visits every single month. From how-tos to educational cartoons, YouTube has a large selection of videos from every genre. You’ve likely watched videos on YouTube and seen something that you might want to watch when you don’t have access to the internet. Need a cartoon for your child who watch while on an airplane? Or, maybe an instructional video to review while actually doing the task later? Downloading YouTube videos is quite simple. How to download YouTube videos with Keepvid You can use keepvid.com to download YouTube videos. Follow these steps to use Keepvid: Go to YouTube and find the video you’d like to download. Click the Share button underneath the video on YouTube to copy the link. Open a new window and navigate to keepvid.com. Paste the link into the download text box. Click download and save the video.All done! Keepvid can also download videos from other websites, including videos posted to social media. Before you begin downloading videos from YouTube, you need to understand the legal issues that accompany your use of those videos. YouTube content is copyrighted. That means that you absolutely cannot download it for anything other than personal use. Also, Google (the owner of YouTube) includes terms of service for users. These terms specifically state: “You shall not download any Content unless you see a 'download' or similar link displayed by YouTube on the Service for that Content” (Section 5 – B). The following is provided for informational purposes only. There are several methods for downloading YouTube videos. The instructions above discuss one popular way to complete the task, but other options exist. There are numerous software suites available to download these videos. If you prefer this method, you can easily find choices by searching the internet for “YouTube downloading software.” The directions you find here discuss the use of websites that are specifically created to download YouTube videos.
View ArticleArticle / Updated 10-28-2024
The words int and double are examples of primitive types (also known as simple types) in Java. The Java language has exactly eight primitive types. As a newcomer to Java, you can pretty much ignore all but four of these types. (As programming languages go, Java is nice and compact that way.) The types that you shouldn’t ignore are int, double, char, and boolean. The char type Several decades ago, people thought computers existed only for doing big number-crunching calculations. Nowadays, nobody thinks that way. So, if you haven’t been in a cryogenic freezing chamber for the past 20 years, you know that computers store letters, punctuation symbols, and other characters. The Java type that’s used to store characters is called char. The code below has a simple program that uses the char type. This image shows the output of the program in the code below. public class CharDemo { public static void main(String args[]) { char myLittleChar = 'b'; char myBigChar = Character.toUpperCase(myLittleChar); System.out.println(myBigChar); } } In this code, the first initialization stores the letter b in the variable myLittleChar. In the initialization, notice how b is surrounded by single quote marks. In Java, every char literally starts and ends with a single quote mark. In a Java program, single quote marks surround the letter in a char literal. Character.toUpperCase. The Character.toUpperCase method does just what its name suggests — the method produces the uppercase equivalent of the letter b. This uppercase equivalent (the letter B) is assigned to the myBigChar variable, and the B that’s in myBigChar prints onscreen. If you’re tempted to write the following statement, char myLittleChars = 'barry'; //Don't do this please resist the temptation. You can’t store more than one letter at a time in a char variable, and you can’t put more than one letter between a pair of single quotes. If you’re trying to store words or sentences (not just single letters), you need to use something called a String. If you’re used to writing programs in other languages, you may be aware of something called ASCII character encoding. Most languages use ASCII; Java uses Unicode. In the old ASCII representation, each character takes up only 8 bits, but in Unicode, each character takes up 8, 16, or 32 bits. Whereas ASCII stores the letters of the Roman (English) alphabet, Unicode has room for characters from most of the world’s commonly spoken languages. The only problem is that some of the Java API methods are geared specially toward 16-bit Unicode. Occasionally, this bites you in the back (or it bytes you in the back, as the case may be). If you’re using a method to write Hello on the screen and H e l l o shows up instead, check the method’s documentation for mention of Unicode characters. It’s worth noticing that the two methods, Character.toUpperCase and System.out.println, are used quite differently in the code above. The method Character.toUpperCase is called as part of an initialization or an assignment statement, but the method System.out.println is called on its own. The boolean type A variable of type boolean stores one of two values: true or false. The code below demonstrates the use of a boolean variable. public class ElevatorFitter2 { public static void main(String args[]) { System.out.println("True or False?"); System.out.println("You can fit all ten of the"); System.out.println("Brickenchicker dectuplets"); System.out.println("on the elevator:"); System.out.println(); int weightOfAPerson = 150; int elevatorWeightLimit = 1400; int numberOfPeople = elevatorWeightLimit / weightOfAPerson; <strong> boolean allTenOkay = numberOfPeople >= 10;</strong> System.out.println(allTenOkay); } } In this code, the allTenOkay variable is of type boolean. To find a value for the allTenOkay variable, the program checks to see whether numberOfPeople is greater than or equal to ten. (The symbols >= stand for greater than or equal to.) At this point, it pays to be fussy about terminology. Any part of a Java program that has a value is an expression. If you write weightOfAPerson = 150; then 150 ,is an expression (an expression whose value is the quantity 150). If you write numberOfEggs = 2 + 2; then 2 + 2 is an expression (because 2 + 2 has the value 4). If you write int numberOfPeople = elevatorWeightLimit / weightOfAPerson; then elevatorWeightLimit / weightOfAPerson is an expression. (The value of the expression elevatorWeightLimit / weightOfAPerson depends on whatever values the variables elevatorWeightLimit and weightOfAPerson have when the code containing the expression is executed.) Any part of a Java program that has a value is an expression. In the second set of code, numberOfPeople >= 10 is an expression. The expression’s value depends on the value stored in the numberOfPeople variable. But, as you know from seeing the strawberry shortcake at the Brickenchicker family’s catered lunch, the value of numberOfPeople isn’t greater than or equal to ten. As a result, the value of numberOfPeople >= 10 is false. So, in the statement in the second set of code, in which allTenOkay is assigned a value, the allTenOkay variable is assigned a false value. In the second set of code, System.out.println() is called with nothing inside the parentheses. When you do this, Java adds a line break to the program’s output. In the second set of code, System.out.println() tells the program to display a blank line.
View ArticleArticle / Updated 10-28-2024
When coding your app, you will almost inevitably write code that does not behave as you intended. HTML and CSS are relatively forgiving, with the browser even going so far as to insert tags so the page renders properly. However, JavaScript isn’t so forgiving, and the smallest error, such as a missing quotation mark, can cause the page to not render properly. Errors in web applications can consist of syntax errors, logic errors, and display errors. Often, the most likely culprit causing errors in your code will be syntax related. Here are some common errors to check when debugging your code: Opening and closing tags: In HTML, every opening tag has a closing tag, and you always close the most recently opened tag first. Right and left angle brackets: In HTML, every left angle bracket < has a right angle bracket >. Right and left curly brackets: In CSS and JavaScript, every left curly bracket must have a right curly bracket. It can be easy to accidentally delete it or forget to include it. Indentation: Indent your code and use plenty of tabs and returns to make your code as readable as possible. Proper indentation will make it easier for you to identify missing tags, angle brackets, and curly brackets. Misspelled statements: Tags in any language can be misspelled, or spelled correctly but not part of the specification. For example, in HTML, <img scr="image.jpg"> is incorrect because scr should really be src for the image to render properly. Similarly, in CSS font-color looks like it is spelled correctly but no such property exists. The correct property to set font color is just color. Keep these errors in mind when debugging — they may not solve all your problems, but they should solve many of them. If you have tried the steps above and still cannot debug your code, tweet @nikhilgabraham and include the #codingFD hashtag and your codepen.io URL in your tweet.
View ArticleArticle / Updated 10-28-2024
When a demonstration of the product you are selling on eBay would benefit from more graphic illustration, consider adding a video. The easiest way to add a video to your eBay listing is to use eBay's new listing tool when you are creating or revising your listing. Follow these steps Click on the Add video button. Select a file on your device or drag and drop the video to the web page. You can also use the Import from mobile and Import from web buttons. When you type your description, you have the option of jazzing things up with a bit of HTML coding, or you can use eBay’s HTML text editor. If you know how to use a word processor, you’ll have no trouble touching up your text with this tool. Here are a few additional codes if you’d like to manually insert the code in the HTML view. HTML Code How to Use It What It Does cool collectible cool collectible (bold type) cool collectible cool collectible (italic type) cool collectible cool collectible (bold and italic type) cool collectible Selected text appears in red. cool collectible cool collectible (font size normal +1 through 4, increases size x times) coolcollectible cool collectible (inserts line break) coolcollectible cool collectible (inserts paragraph space) cool collectiblecheap cool collectible_____________cheap (inserts horizontal rule) cool collectible cool collectible (converts text to headline size) You can go back and forth from the HTML text editor to regular input and add additional codes here and there by clicking from the Standard form to the HTML entry form tabs. You can prepare your listings ahead of time and save them in My eBay folder as plain HTML files — that way they’re always retrievable for use (you can just copy and paste) — no matter what program or form you’re using to list. To insert additional photos in your description, use the following code. (Just insert the URL of your hosted picture, along with the photo’s file name.) The example above used the following code: <img scr=##http://www.collierad.com/catbed.jpg##> Occasionally, sellers offer an item as a presale, or an item that the seller doesn’t yet have in stock but expects to. If you’re offering this kind of item, make sure that you spell out all the details in the description. eBay policy states that you must ship a presale item within 30 days of the auction’s end, so be sure that you will have the item within that time span and include the actual shipping date. Putting an item up for sale without having it in hand is a practice fraught with risk. The item you’re expecting may not arrive in time or may arrive damaged. There are many sellers who have had to go out and purchase an item at retail for a buyer to preserve their feedback when caught in this situation.
View ArticleArticle / Updated 10-28-2024
A paper database is useful for storing information, but not so useful for finding it again. With Access 2019, searching and finding information is easy. If you have a thousand business cards stored in a Rolodex file, how much time do you want to waste trying to find the phone number of a single person? With Access 2019, that is no longer a concern. Searching a database is crucial to make your data useful, so Access provides two ways to search a database: Search for a specific record. Use a filter to show one or more records that meet a specific criterion. Searching MS Access for a specific record The simplest type of search looks for a specific record. To search for a record, you need to know the data stored in at least one of its fields, such as a phone number or an email address. The more information you already know, the more likely Access will find the one record you want. If you search for all records that contain the first name Bill, Access could find dozens of records. If you just search for all records that contain the first name Bill, the last name Johnson, and a state address of Alaska, Access will likely find just the record you want. To search for a specific record in an Access database table, follow these steps: In the All Access Objects pane on the left of the screen, double-click the name of the database table you want to search. Access displays the Datasheet view of your database. Click the Home tab. In the Find group, click the Find icon. The Find and Replace dialog box appears. Click in the Find What text box and type the data you know is stored in the record you want to find. For example, if you want to find the phone number of a person but you know only the person’s last name, type the last name in the Find What text box. Click the Look In list box and choose Current field or Current document (searches in all fields). (Optional) Click in the Match list box and choose one of the following: Any Part of Field: The Find What text can appear in any part of a field. Whole Field: The Find What text is the only text stored in a field. Start of Field: The Find What text can be only at the beginning of a field. (Optional) Click in the Search list box and choose one of the following: Up: Searches from the record where the cursor appears, up to the beginning of the database table Down: Searches from the record where the cursor appears, down to the end of the database table All: Searches the entire database table Click Find Next. Access highlights the field where it finds the text you typed in Step 4. Repeat Step 8 to search for more records that may contain the text you typed in Step 4. Click Cancel or the Close button. Filtering an Access database Searching a database is easy but somewhat limited because you can retrieve only a single record at a time that matches any text that you want to find. If you want to find multiple records, you can use a filter. A filter lets you tell Access to display only those records that meet certain criteria, such all records that contain people who earn more than $200,000 a year, are currently married, live in Las Vegas, Nevada, and own two or more cats. To filter a database table, you must tell Access which field or fields to use as a filter, and then you must define the criteria for that filter. For example, if you want to filter your database table to see only records listing the names of people who are at least 65, you filter the Age field and set the criterion to Greater than or equal to 65. Filtering simply hides all records in a database table that don’t match your criteria. Filtering doesn’t delete or erase any records. Using an exact match for a filter in Access 2019 The simplest filtering criterion searches for an exact match. When you filter a field by an exact match, you’re telling Access, “I want to see only those records that contain this specific chunk of data in this particular field.” By using an exact match filter, you can display, for example, only the records that contain CA in the State field. To filter a database table, follow these steps: In the All Access Objects pane on the left of the screen, double-click the name of the database table you want to filter. Access displays the Datasheet view of your database. Click the Home tab. Click in the field (column) that you want to use as a filter. In the Sort & Filter group, click the Filter icon.A pop-up menu appears. You can either Select or clear check boxes from this menu. Continue with Steps 5 through 7 for more flexibility. Choose Text Filters. A submenu appears. Choose a filter option, such as Equals, Begins With, or Contains. A Custom Filter dialog box appears. Type the data you want to find and click OK. Access displays your filtered data, and a filter icon appears in the column heading. Access remembers your filter settings. If you want to clear the filter, click the filter icon in the column heading; when a pop-up menu appears, choose Clear Filter. To view all the data in your database table, click the Home tab. Then in the Sort & Filter group, click the Toggle Filter icon. Filtering Access databases by form One problem with defining filters in Datasheet view is that you have all your database table records cluttering the screen. To avoid this problem, Access lets you define filters by using a form, which basically displays an empty record so you can click the fields that you want to use to filter your database table. To define a filter by form, follow these steps: In the All Access Objects pane on the left of the screen, double-click the name of the database table that you want to filter. Access displays the Datasheet view of your database. Click the Home tab. In the Sort & Filter group, click the Advanced icon. A pull-down menu appears. Choose Filter by Form. Access displays a blank record. Click in any field, then type the data you want to filter such as a last name. In the Sort & Filter group, click the Advanced icon and then click Apply Filter/Sort. Access displays a filtered view of your database table. You can click the Toggle Filter icon again to view all the data in your database table. Using a filter criteria in Access 2019 Searching for an exact match in a field can be handy, but sometimes you may want to see records that meet certain criteria, such as finding the names of everyone whose salary is greater than $50,000 a year. Instead of filtering by an exact match, you have to define the filter criteria. The type of data stored in each field determines the type of criteria you can create. Three common types of data stored in fields are text, numbers, and dates, which you can filter in different ways. Common Criteria for Filtering Text Data Filtering Criteria Description Equals Field must match filter text exactly. Does Not Equal Field must not match filter text. Begins With Field must start with the filter text. Does Not Begin With Field must not begin with the filter text. Contains Field must contain the filter text. Does Not Contain Field must not contain any part of the filter text. Ends With Field ends with the filter text. Does Not End With Field does not end with the filter text. Common Criteria for Filtering Numeric Data Filtering Criteria Description Equals Field must equal filter number. Does Not Equal Field must not equal filter number. Less Than or Equal To Field must contain a number less than or equal to the filter number. Greater Than or Equal To Field must contain a number greater than or equal to the filter number. Between Field must contain a number that falls between two filter numbers. Common Criteria for Filtering Dates Filtering Criteria Description Equals Field must equal the filter date. Does Not Equal Field must not equal the filter date. On or Before Field date must be equal or earlier than the filter date. On or After Field date must be equal or later than the filter date. To create the filter criteria, follow these steps: In the All Access Objects pane on the left of the screen, double-click the name of the database table you want to filter. Access displays the Datasheet view of your database. Click the Home tab. Click in the field (column) that you want to use as a filter. In the Sort & Filter group, click the Filter icon. A pop-up menu appears. Select the Filters option, such as Text Filters or Number Filters. A submenu of filter options appears. Click a filter option, such as Between or Less Than. The Custom Filter dialog box appears. The Custom Filter dialog box contains the name of your filter option, such as Between Numbers or Less Than. Type one or more values in each text box in the Custom Filter dialog box, and then click OK. Access filters your database table according to your criteria. Repeat Steps 5 through 7 for each additional filter you want to add. You can click the Toggle Filter icon again to view all the data in your database table. Clearing a filter in Access 2019 When you apply a filter to a database table, you see only those records that match that filter. Access displays a Filtered message at the bottom of the screen to let you know when you’re looking at a filtered database table. To remove a filter so you can see all the records, choose one of the following: Click the Toggle Filter icon in the Sort & Filter group. Click the Filtered or Unfiltered button on the status bar near the bottom of the screen. Access temporarily turns off any filters so you can see all the information stored in your database table. When you choose the Save command (Ctrl+S) to save a database table, Access also saves your last filter. The next time you open that database table, you’ll be able to use the last filter you created. If you want to save multiple filters, you’ll have to save them as a query. See these handy Access keyboard shortcuts for further information.
View ArticleStep by Step / Updated 10-28-2024
Windows usually detects the presence of a network adapter automatically; typically, you don’t have to install device drivers manually for the adapter. When Windows detects a network adapter, Windows automatically creates a network connection and configures it to support basic networking protocols. You may need to change the configuration of a network connection manually, however. The following steps show you how to configure your network adapter on a Windows 10 system:
View Step by StepCheat Sheet / Updated 10-17-2024
The first public release of ChatGPT ignited the world’s demand for increasingly sophisticated Generative AI (GenAI) models and tools, and the market was quick to deliver. But what’s the use of having so many GenAI tools if you get stuck using them? And make no mistake, everyone gets stuck quite often! This cheat sheet helps you get the very best results by introducing you to advanced (but pretty easy) prompting techniques and giving you useful tips on how to choose models or applications that are right for the task.
View Cheat SheetArticle / Updated 09-24-2024
Both linear and logistic regression see a lot of use in data science but are commonly used for different kinds of problems. You need to know and understand both types of regression to perform a full range of data science tasks. Of the two, logistic regression is harder to understand in many respects because it necessarily uses a more complex equation model. The following information gives you a basic overview of how linear and logistic regression differ. The equation model Any discussion of the difference between linear and logistic regression must start with the underlying equation model. The equation for linear regression is straightforward. y = a + bx You may see this equation in other forms and you may see it called ordinary least squares regression, but the essential concept is always the same. Depending on the source you use, some of the equations used to express logistic regression can become downright terrifying unless you’re a math major. However, the start of this discussion can use one of the simplest views of logistic regression: p = f(a + bx) >p, is equal to the logistic function, f, applied to two model parameters, a and b, and one explanatory variable, x. When you look at this particular model, you see that it really isn’t all that different from the linear regression model, except that you now feed the result of the linear regression through the logistic function to obtain the required curve. The output (dependent variable) is a probability ranging from 0 (not going to happen) to 1 (definitely will happen), or a categorization that says something is either part of the category or not part of the category. (You can also perform multiclass categorization, but focus on the binary response for now.) The best way to view the difference between linear regression output and logistic regression output is to say that the following: Linear regression is continuous. A continuous value can take any value within a specified interval (range) of values. For example, no matter how closely the height of two individuals matches, you can always find someone whose height fits between those two individuals. Examples of continuous values include: Height Weight Waist size Logistic regression is discrete. A discrete value has specific values that it can assume. For example, a hospital can admit only a specific number of patients in a given day. You can’t admit half a patient (at least, not alive). Examples of discrete values include: Number of people at the fair Number of jellybeans in the jar Colors of automobiles produced by a vendor The logistic function Of course, now you need to know about the logistic function. You can find a variety of forms of this function as well, but here’s the easiest one to understand: f(x) = e<sup>x</sup> / e<sup>x</sup> + 1 You already know about f, which is the logistic function, and x equals the algorithm you want to use, which is a + bx in this case. That leaves e, which is the natural logarithm and has an irrational value of 2.718, for the sake of discussion (check out a better approximation of the whole value). Another way you see this function expressed is f(x) = 1 / (1 + e<sup>-x</sup>) Both forms are correct, but the first form is easier to use. Consider a simple problem in which a, the y-intercept, is 0, and ">b, the slope, is 1. The example uses x values from –6 to 6. Consequently, the first f(x) value would look like this when calculated (all values are rounded): (1) e<sup>-6</sup> / (1 + e<sup>-6</sup>) (2) 0.00248 / 1 + 0.00248 (3) 0.002474 As you might expect, an xvalue of 0 would result in an f(x) value of 0.5, and an x value of 6 would result in an f(x) value of 0.9975. Obviously, a linear regression would show different results for precisely the same x values. If you calculate and plot all the results from both logistic and linear regression using the following code, you receive a plot like the one below. import matplotlib.pyplot as plt %matplotlib inline from math import exp x_values = range(-6, 7) lin_values = [(0 + 1*x) / 13 for x in range(0, 13)] log_values = [exp(0 + 1*x) / (1 + exp(0 + 1*x)) for x in x_values] plt.plot(x_values, lin_values, 'b-^') plt.plot(x_values, log_values, 'g-*') plt.legend(['Linear', 'Logistic']) plt.show() This example relies on list comprehension to calculate the values because it makes the calculations clearer. The linear regression uses a different numeric range because you must normalize the values to appear in the 0 to 1 range for comparison. This is also why you divide the calculated values by 13. The exp(x) call used for the logistic regression raises e to the power of x, e<sup>x</sup>, as needed for the logistic function. The model discussed here is simplified, and some math majors out there are probably throwing a temper tantrum of the most profound proportions right now. The Python or R package you use will actually take care of the math in the background, so really, what you need to know is how the math works at a basic level so that you can understand how to use the packages. This section provides what you need to use the packages. However, if you insist on carrying out the calculations the old way, chalk to chalkboard, you’ll likely need a lot more information. The problems that logistic regression solves You can separate logistic regression into several categories. The first is simple logistic regression, in which you have one dependent variable and one independent variable, much as you see in simple linear regression. However, because of how you calculate the logistic regression, you can expect only two kinds of output: Classification: Decides between two available outcomes, such as male or female, yes or no, or high or low. The outcome is dependent on which side of the line a particular data point falls. Probability: Determines the probability that something is true or false. The values true and false can have specific meanings. For example, you might want to know the probability that a particular apple will be yellow or red based on the presence of yellow and red apples in a bin. Fit the curve As part of understanding the difference between linear and logistic regression, consider this grade prediction problem, which lends itself well to linear regression. In the following code, you see the effect of trying to use logistic regression with that data: x1 = range(0,9) y1 = (0.25, 0.33, 0.41, 0.53, 0.59, 0.70, 0.78, 0.86, 0.98) plt.scatter(x1, y1, c='r') lin_values = [0.242 + 0.0933*x for x in x1] log_values = [exp(0.242 + .9033*x) / (1 + exp(0.242 + .9033*x)) for x in range(-4, 5)] plt.plot(x1, lin_values, 'b-^') plt.plot(x1, log_values, 'g-*') plt.legend(['Linear', 'Logistic', 'Org Data']) plt.show() The example has undergone a few changes to make it easier to see precisely what is happening. It relies on the same data that was converted from questions answered correctly on the exam to a percentage. If you have 100 questions and you answer 25 of them correctly, you have answered 25 percent (0.25) of them correctly. The values are normalized to produce values between 0 and 1 percent. As you can see from the image above, the linear regression follows the data points closely. The logistic regression doesn’t. However, logistic regression often is the correct choice when the data points naturally follow the logistic curve, which happens far more often than you might think. You must use the technique that fits your data best, which means using linear regression in this case. A pass/fail example An essential point to remember is that logistic regression works best for probability and classification. Consider that points on an exam ultimately predict passing or failing the course. If you get a certain percentage of the answers correct, you pass, but you fail otherwise. The following code considers the same data used for the example above, but converts it to a pass/fail list. When a student gets at least 70 percent of the questions correct, success is assured. y2 = [0 if x < 0.70 else 1 for x in y1] plt.scatter(x1, y2, c='r') lin_values = [0.242 + 0.0933*x for x in x1] log_values = [exp(0.242 + .9033*x) / (1 + exp(0.242 + .9033*x)) for x in range(-4, 5)] plt.plot(x1, lin_values, 'b-^') plt.plot(x1, log_values, 'g-*') plt.legend(['Linear', 'Logistic', 'Org Data']) plt.show() This is an example of how you can use list comprehensions in Python to obtain a required dataset or data transformation. The list comprehension for y2 starts with the continuous data in y1 and turns it into discrete data. Note that the example uses precisely the same equations as before. All that has changed is the manner in which you view the data, as you can see below. Because of the change in the data, linear regression is no longer the option to choose. Instead, you use logistic regression to fit the data. Take into account that this example really hasn’t done any sort of analysis to optimize the results. The logistic regression fits the data even better if you do so.
View Article