Playing with Jupyter Notebooks and Python
Playing with Jupyter Notebooks and Python
Playing Around With emojis
from emoji import emojize
print(emojize("If you're hungry, here some food: :red_apple: :pie: :pizza:"))
If you're hungry, here some food: 🍎 🥧 🍕
Extracting Data From Newspaper3k
from newspaper import Article
from IPython.display import display, Markdown
urls = ["https://www.sandiegouniontribune.com/2023/04/11/champions-again-poway-unified-has-nations-top-high-school-middle-school-cybersecurity-teams/",
"https://www.cnn.com/2023/04/30/entertainment/super-mario-bros-movie-1-billion-box-office/index.html"]
for url in urls:
article = Article(url)
article.download()
article.parse()
# Jupyter Notebook Display
# print(article.title)
display(Markdown(article.title)) # Jupyter display only
display(Markdown(article.text)) # Jupyter display only
print("\n")
Champions again: Poway Unified has nation’s top high school, middle school cybersecurity teams
The winning streak has continued for Poway Unified’s cybersecurity teams in the CyberPatriot national competition for high school and middle school students.
This is the sixth year in a row that a Poway Unified middle school has won the national title and fourth consecutive year for a Del Norte High team to win the national championship.
The teams had multiple challenges to defend computer systems from attacks by cyber security professionals playing the role of hackers. There were three components — the Windows and Linux operating systems and a Cisco networking software system.
“I’m extremely proud of my teams winning both the CyberPatriot Middle School Division and Open Division, for the fourth year in a row,” said coach Paul Johnson. “Eight new national champion teams in four years. During the extremely difficult and intense season-long competition, the teams displayed exceptional teamwork, leadership, grit, determination and passion.”
The middle school streak in the Air Force Association’s national youth cyber education program began in the 2017-18 season when an Oak Valley team won. The school also won the title in 2018-19 and 2020-21. This year a team from Design39Campus won the title — it also had the champion-winning teams in 2019-20 and 2021-22.
Johnson’s students this year came out as champions over the 5,584 teams that entered regional events across the country. The top 28 teams at the high school and middle school levels competing in the finals defended networks, services and mobile devices from attacks by hackers.
Last month’s CyberPatriot XV National Finals were held in Bethesda, Maryland.
“The students are always very hard working and sharp, always passionate,” Johnson said.
He credited that passion for the years of success by the teams. Several of the high school students on this year’s national teams were among those who also competed and won at nationals during their middle school years.
At this point, Johnson said the pressure on the teams is to continue their winning-streak tradition.
Four Del Norte High students — Akhil Guntur, Jonathan Lin, Akshay Rohatgi and Alvin Zheng — were named Cyber All-American Award Recipients because they qualified for the National Finals all four years of their high school competition seasons.
“The genius of my students continues to amaze me,” Johnson said. “I appreciate that they are such passionate competitors.”
Medals and trophies were presented to the finalists. Scholarships were also available to the high schoolers.
Del Norte High had two teams in the top three of the Open Division.
CyberAegis Tempest, the 2023 national champion, came in third in the Cisco Networking Challenge. Team members were captain Akshay Rohatgi, Alex Jiang, Rohan Juneja, Safin Singh, Ethan Zhao and Alvin Zheng.
CyberAegis Drift came in third place in the national contest and won the Cisco Networking Challenge. It consisted of team captain Aarav Arora, Akhil Guntur, Jonathan Lin, Raadwan Masum, Vardaan Sinha and Lily Wu.
This was the third time Arora was on a national team. The 17-year-old junior made it as a seventh- and eighth-grader, and his team won the national title when he was in eighth grade.
In addition to being his team’s captain this year, Arora was also the program’s president.
“It’s a good experience,” Arora said. “I worked more directly with Coach Paul and as president of the club … I built my leadership skills by working with older and younger students. The seniors could be more difficult to lead, and it was a bit of a challenge to lead students my age. They are my peers and I had to give them instructions … I learned how to balance personalities.”
Communication is the key to good teamwork, he said. While considering a career in data science or computer science, Arora said the leadership lessons he has learned will carry over in whatever career he ultimately chooses.
Going to Maryland for nationals was a “fun experience” because he could bond with his teammates away from home, he said.
Arora said he also enjoyed the program’s outreach events with elementary and low-income students throughout the year. Team members provided classes and workshops to introduce cybersecurity concepts and skills to students who otherwise would not be exposed to the field.
The CyberAegis Vitalis from Design39Campus won the national champion in the Middle School Division. They were team captain Yash Parikh, Neil Chandra, Risha Guha, Ansh Kumar, Krish Nandola and Anvay Vahia.
“I really love competing in this program. We do our best … and whatever happens give it our all,” said Guha, one of three girls on PUSD’s national teams.
The 14-year-old eighth-grader said more girls are getting interested in cybersecurity and STEM (science, technology, engineering and math), something she is trying to encourage. She was among the students who helped with training their peers in the CyberPatriot program and she organized outreach events, such as a workshop for 150 fifth-graders and for 30 Junior Girl Scouts in fourth and fifth grade.
This was Guha’s third time competing at nationals and second time winning the championship. She said the previous trips helped her team know what to expect in the competition.
“I enjoy the fact that we’re digging deep into computer infrastructure to find everyday problems and how to solve them,” Guha said, adding that the challenges are “really fun.”
The national runner-up was CyberAegis Aeris from Oak Valley Middle School, which also won the Cisco Networking Challenge. Its members were team captain Mihir Bapat, Aditya Katre, Kanhay Patil, Dhyan Soni, Xavier Thompson and Jacob Wu.
“It’s intimidating, being 40 to 50 feet from the hackers,” said Bapat, 13. “They are trying to get into your system to cause problems.”
While the students could not see the cybersecurity experts playing the role of hackers in the competition, Bapat said the event is “excruciating, but fun … it creates a lot of pressure.”
Bapat added, “During the entire competition you have to keep your cool because you do not want to panic or be frantic in any way because the hackers will take advantage of that.”
As team captain, Bapat, an eighth-grader, said his responsibilities included keeping his five other teammates motivated.
“If anyone needs something I have to be there for them,” he said. “No one is perfect, this is a team effort.”
His team won the Cisco Networking Challenge, a component of the competition. He said it consisted of two parts and his responsibility was working on the Windows operating system.
“I enjoy securing the system that I use daily,” Bapat said.
He explained that there are many ways a hacker can get into the system and there are simple ways people can fix weaknesses in their software, but they need to know where to look.
“Finding fixes is intriguing, I am finding the insecurities that are hiding in our systems,” Bapat said.
Johnson built the program for Del Norte, Oak Valley and Design39Campus over the past nine years, comparing it to the farm system in baseball. There is a training period during the spring — it has already begun for the 2023-24 season — where all middle and high school students at these campuses are offered an opportunity to learn about cyber security.
By the end of the school year, they will be tested and the top 120 students will continue training over the summer. He has the high school students and some eighth-graders take on mentorship roles, where they teach their peers the skills they need.
Johnson volunteers his time to coach the teams. He retired as a senior staff cyber systems engineer at Northrop Grumman, but now works part-time as a consultant for the company. He considered retiring as the CyberPatriot coach, but decided to continue for now.
“As long as they are performing at this level, as long as the students will have this winning drive (I’ll continue),” Johnson said.
‘Super Mario Bros. Movie’ becomes 10th animated film to cross $1 billion at the global box office
CNN —
Nearly one month after “The Super Mario Bros. Movie” premiered with an impressive opening weekend at the box office, the animated film has hit another major milestone.
The movie crossed $1 billion at the global box office on Sunday, and according to a news release from Universal, it continues to break box office records as it remains in the No. 1 spot for the fourth consecutive weekend.
“Super Mario Bros.” is the 10th animated film in history to cross $1 billion, making it the 10th biggest animated movie of all time globally, beating out the $942.5 million that “Minions: The Rise of the Gru” grossed in 2019.
The movie premiered in the US and Canada on April 5 and ran up the score with more than $200 million, and nearly $380 million internationally, for its five-day opening run. “Super Mario Bros.” surpassed Marvel’s “Ant Man and the Wasp: Quantumania” at the time, which brought in $225.3 million globally during its February opening.
The movie is based on the world of Nintendo’s classic “Super Mario” video game franchise, and stars Chris Pratt as Mario, Charlie Day as Luigi and Anya Taylor-Joy as Princess Peach.
“The Super Mario Bros. Movie” follows Brooklyn plumbers Mario and Luigi as they’re transported down a mysterious pipe while working underground to fix a water main. The brothers wander into a “magical new world” and when they’re separated, “Mario embarks on an epic quest to find Luigi,” according to a synopsis on the movie’s website.
Jack Black, Keegan-Michael Key, Seth Rogen, Fred Armisen, Kevin Michael Richardson and Sebastian Maniscalco round out the cast, with a special appearance by actor Charles Martinet who is the official voice of Mario in the video games.
Extracting Data From Wikipedia
import wikipedia
from IPython.display import display, Markdown # add for Jupyter
terms = ["Microsoft Windows", "ChromeOS"]
for term in terms:
# Search for a page
result = wikipedia.search(term)
# Get the summary of the first result
summary = wikipedia.summary(result[0])
print(term)
# print(summary) # console display
display(Markdown(summary)) # Jupyter display
Microsoft Windows
Microsoft Windows is a product line of proprietary graphical operating systems developed and marketed by Microsoft. It is grouped into families and sub-families that cater to particular sectors of the computing industry – Windows (unqualified) for a consumer or corporate workstation, Windows Server for a server and Windows IoT for an embedded system. Defunct families include Windows 9x, Windows Mobile, Windows Phone, and Windows Embedded Compact. The first version of Windows was released on November 20, 1985, as a graphical operating system shell for MS-DOS in response to the growing interest in graphical user interfaces (GUIs). Windows is the most popular desktop operating system in the world, with a 70% market share as of March 2023, according to StatCounter. However, Windows is not the most used operating system when including both mobile and desktop OSes, due to Android’s massive growth globally since the early 2010s. As of today, the most recent version of Windows is Windows 11 for consumer PCs and tablets, Windows 11 Enterprise for corporations, and Windows Server 2025 for servers. Still supported are some editions of Windows 10, Windows Server 2016 or later (and exceptionally with paid support down to Windows Server 2012 and Windows Embedded POSReady 7).
ChromeOS
ChromeOS, sometimes styled as chromeOS and formerly styled as Chrome OS, is a Linux distribution developed and designed by Google. It is derived from the open-source ChromiumOS, based on the Linux kernel, and uses the Google Chrome web browser as its principal user interface. Google announced the project in July 2009, initially describing it as an operating system where applications and user data would reside in the cloud. ChromeOS was used primarily to run web applications. All ChromiumOS and ChromeOS versions support progressive web applications (such as Google Docs or Microsoft Office 365). ChromeOS (but not ChromiumOS) from 2016 onwards can run Android applications from Google Play. Since 2018, ChromiumOS/ChromeOS version 69 onwards also support Linux applications, which are executed in a lightweight virtual machine with a Debian environment.
Inspect Code Documentation
import inspect
from newspaper import Article
# inspect newspaper Article function
print(inspect.getsource(Article))
class Article(object):
"""Article objects abstract an online news article page
"""
def __init__(self, url, title='', source_url='', config=None, **kwargs):
"""The **kwargs argument may be filled with config values, which
is added into the config object
"""
if isinstance(title, Configuration) or \
isinstance(source_url, Configuration):
raise ArticleException(
'Configuration object being passed incorrectly as title or '
'source_url! Please verify `Article`s __init__() fn.')
self.config = config or Configuration()
self.config = extend_config(self.config, kwargs)
self.extractor = ContentExtractor(self.config)
if source_url == '':
scheme = urls.get_scheme(url)
if scheme is None:
scheme = 'http'
source_url = scheme + '://' + urls.get_domain(url)
if source_url is None or source_url == '':
raise ArticleException('input url bad format')
# URL to the main page of the news source which owns this article
self.source_url = source_url
self.url = urls.prepare_url(url, self.source_url)
self.title = title
# URL of the "best image" to represent this article
self.top_img = self.top_image = ''
# stores image provided by metadata
self.meta_img = ''
# All image urls in this article
self.imgs = self.images = []
# All videos in this article: youtube, vimeo, etc
self.movies = []
# Body text from this article
self.text = ''
# `keywords` are extracted via nlp() from the body text
self.keywords = []
# `meta_keywords` are extracted via parse() from <meta> tags
self.meta_keywords = []
# `tags` are also extracted via parse() from <meta> tags
self.tags = set()
# List of authors who have published the article, via parse()
self.authors = []
self.publish_date = ''
# Summary generated from the article's body txt
self.summary = ''
# This article's unchanged and raw HTML
self.html = ''
# The HTML of this article's main node (most important part)
self.article_html = ''
# Keep state for downloads and parsing
self.is_parsed = False
self.download_state = ArticleDownloadState.NOT_STARTED
self.download_exception_msg = None
# Meta description field in the HTML source
self.meta_description = ""
# Meta language field in HTML source
self.meta_lang = ""
# Meta favicon field in HTML source
self.meta_favicon = ""
# Meta tags contain a lot of structured data, e.g. OpenGraph
self.meta_data = {}
# The canonical link of this article if found in the meta data
self.canonical_link = ""
# Holds the top element of the DOM that we determine is a candidate
# for the main body of the article
self.top_node = None
# A deepcopied clone of the above object before heavy parsing
# operations, useful for users to query data in the
# "most important part of the page"
self.clean_top_node = None
# lxml DOM object generated from HTML
self.doc = None
# A deepcopied clone of the above object before undergoing heavy
# cleaning operations, serves as an API if users need to query the DOM
self.clean_doc = None
# A property dict for users to store custom data.
self.additional_data = {}
def build(self):
"""Build a lone article from a URL independent of the source (newspaper).
Don't normally call this method b/c it's good to multithread articles
on a source (newspaper) level.
"""
self.download()
self.parse()
self.nlp()
def download(self, input_html=None, title=None, recursion_counter=0):
"""Downloads the link's HTML content, don't use if you are batch async
downloading articles
recursion_counter (currently 1) stops refreshes that are potentially
infinite
"""
if input_html is None:
try:
html = network.get_html_2XX_only(self.url, self.config)
except requests.exceptions.RequestException as e:
self.download_state = ArticleDownloadState.FAILED_RESPONSE
self.download_exception_msg = str(e)
log.debug('Download failed on URL %s because of %s' %
(self.url, self.download_exception_msg))
return
else:
html = input_html
if self.config.follow_meta_refresh:
meta_refresh_url = extract_meta_refresh(html)
if meta_refresh_url and recursion_counter < 1:
return self.download(
input_html=network.get_html(meta_refresh_url),
recursion_counter=recursion_counter + 1)
self.set_html(html)
self.set_title(title)
def parse(self):
self.throw_if_not_downloaded_verbose()
self.doc = self.config.get_parser().fromstring(self.html)
self.clean_doc = copy.deepcopy(self.doc)
if self.doc is None:
# `parse` call failed, return nothing
return
# TODO: Fix this, sync in our fix_url() method
parse_candidate = self.get_parse_candidate()
self.link_hash = parse_candidate.link_hash # MD5
document_cleaner = DocumentCleaner(self.config)
output_formatter = OutputFormatter(self.config)
title = self.extractor.get_title(self.clean_doc)
self.set_title(title)
authors = self.extractor.get_authors(self.clean_doc)
self.set_authors(authors)
meta_lang = self.extractor.get_meta_lang(self.clean_doc)
self.set_meta_language(meta_lang)
if self.config.use_meta_language:
self.extractor.update_language(self.meta_lang)
output_formatter.update_language(self.meta_lang)
meta_favicon = self.extractor.get_favicon(self.clean_doc)
self.set_meta_favicon(meta_favicon)
meta_description = \
self.extractor.get_meta_description(self.clean_doc)
self.set_meta_description(meta_description)
canonical_link = self.extractor.get_canonical_link(
self.url, self.clean_doc)
self.set_canonical_link(canonical_link)
tags = self.extractor.extract_tags(self.clean_doc)
self.set_tags(tags)
meta_keywords = self.extractor.get_meta_keywords(
self.clean_doc)
self.set_meta_keywords(meta_keywords)
meta_data = self.extractor.get_meta_data(self.clean_doc)
self.set_meta_data(meta_data)
self.publish_date = self.extractor.get_publishing_date(
self.url,
self.clean_doc)
# Before any computations on the body, clean DOM object
self.doc = document_cleaner.clean(self.doc)
self.top_node = self.extractor.calculate_best_node(self.doc)
if self.top_node is not None:
video_extractor = VideoExtractor(self.config, self.top_node)
self.set_movies(video_extractor.get_videos())
self.top_node = self.extractor.post_cleanup(self.top_node)
self.clean_top_node = copy.deepcopy(self.top_node)
text, article_html = output_formatter.get_formatted(
self.top_node)
self.set_article_html(article_html)
self.set_text(text)
self.fetch_images()
self.is_parsed = True
self.release_resources()
def fetch_images(self):
if self.clean_doc is not None:
meta_img_url = self.extractor.get_meta_img_url(
self.url, self.clean_doc)
self.set_meta_img(meta_img_url)
imgs = self.extractor.get_img_urls(self.url, self.clean_doc)
if self.meta_img:
imgs.add(self.meta_img)
self.set_imgs(imgs)
if self.clean_top_node is not None and not self.has_top_image():
first_img = self.extractor.get_first_img_url(
self.url, self.clean_top_node)
if self.config.fetch_images:
self.set_top_img(first_img)
else:
self.set_top_img_no_check(first_img)
if not self.has_top_image() and self.config.fetch_images:
self.set_reddit_top_img()
def has_top_image(self):
return self.top_img is not None and self.top_img != ''
def is_valid_url(self):
"""Performs a check on the url of this link to determine if article
is a real news article or not
"""
return urls.valid_url(self.url)
def is_valid_body(self):
"""If the article's body text is long enough to meet
standard article requirements, keep the article
"""
if not self.is_parsed:
raise ArticleException('must parse article before checking \
if it\'s body is valid!')
meta_type = self.extractor.get_meta_type(self.clean_doc)
wordcount = self.text.split(' ')
sentcount = self.text.split('.')
if (meta_type == 'article' and len(wordcount) >
(self.config.MIN_WORD_COUNT)):
log.debug('%s verified for article and wc' % self.url)
return True
if not self.is_media_news() and not self.text:
log.debug('%s caught for no media no text' % self.url)
return False
if self.title is None or len(self.title.split(' ')) < 2:
log.debug('%s caught for bad title' % self.url)
return False
if len(wordcount) < self.config.MIN_WORD_COUNT:
log.debug('%s caught for word cnt' % self.url)
return False
if len(sentcount) < self.config.MIN_SENT_COUNT:
log.debug('%s caught for sent cnt' % self.url)
return False
if self.html is None or self.html == '':
log.debug('%s caught for no html' % self.url)
return False
log.debug('%s verified for default true' % self.url)
return True
def is_media_news(self):
"""If the article is related heavily to media:
gallery, video, big pictures, etc
"""
safe_urls = ['/video', '/slide', '/gallery', '/powerpoint',
'/fashion', '/glamour', '/cloth']
for s in safe_urls:
if s in self.url:
return True
return False
def nlp(self):
"""Keyword extraction wrapper
"""
self.throw_if_not_downloaded_verbose()
self.throw_if_not_parsed_verbose()
nlp.load_stopwords(self.config.get_language())
text_keyws = list(nlp.keywords(self.text).keys())
title_keyws = list(nlp.keywords(self.title).keys())
keyws = list(set(title_keyws + text_keyws))
self.set_keywords(keyws)
max_sents = self.config.MAX_SUMMARY_SENT
summary_sents = nlp.summarize(title=self.title, text=self.text, max_sents=max_sents)
summary = '\n'.join(summary_sents)
self.set_summary(summary)
def get_parse_candidate(self):
"""A parse candidate is a wrapper object holding a link hash of this
article and a final_url of the article
"""
if self.html:
return RawHelper.get_parsing_candidate(self.url, self.html)
return URLHelper.get_parsing_candidate(self.url)
def build_resource_path(self):
"""Must be called after computing HTML/final URL
"""
res_path = self.get_resource_path()
if not os.path.exists(res_path):
os.mkdir(res_path)
def get_resource_path(self):
"""Every article object has a special directory to store data in from
initialization to garbage collection
"""
res_dir_fn = 'article_resources'
resource_directory = os.path.join(settings.TOP_DIRECTORY, res_dir_fn)
if not os.path.exists(resource_directory):
os.mkdir(resource_directory)
dir_path = os.path.join(resource_directory, '%s_' % self.link_hash)
return dir_path
def release_resources(self):
# TODO: implement in entirety
path = self.get_resource_path()
for fname in glob.glob(path):
try:
os.remove(fname)
except OSError:
pass
# os.remove(path)
def set_reddit_top_img(self):
"""Wrapper for setting images. Queries known image attributes
first, then uses Reddit's image algorithm as a fallback.
"""
try:
s = images.Scraper(self)
self.set_top_img(s.largest_image_url())
except TypeError as e:
if "Can't convert 'NoneType' object to str implicitly" in e.args[0]:
log.debug('No pictures found. Top image not set, %s' % e)
elif 'timed out' in e.args[0]:
log.debug('Download of picture timed out. Top image not set, %s' % e)
else:
log.critical('TypeError other than None type error. '
'Cannot set top image using the Reddit '
'algorithm. Possible error with PIL., %s' % e)
except Exception as e:
log.critical('Other error with setting top image using the '
'Reddit algorithm. Possible error with PIL, %s' % e)
def set_title(self, input_title):
if input_title:
self.title = input_title[:self.config.MAX_TITLE]
def set_text(self, text):
text = text[:self.config.MAX_TEXT]
if text:
self.text = text
def set_html(self, html):
"""Encode HTML before setting it
"""
if html:
if isinstance(html, bytes):
html = self.config.get_parser().get_unicode_html(html)
self.html = html
self.download_state = ArticleDownloadState.SUCCESS
def set_article_html(self, article_html):
"""Sets the HTML of just the article's `top_node`
"""
if article_html:
self.article_html = article_html
def set_meta_img(self, src_url):
self.meta_img = src_url
self.set_top_img_no_check(src_url)
def set_top_img(self, src_url):
if src_url is not None:
s = images.Scraper(self)
if s.satisfies_requirements(src_url):
self.set_top_img_no_check(src_url)
def set_top_img_no_check(self, src_url):
"""Provide 2 APIs for images. One at "top_img", "imgs"
and one at "top_image", "images"
"""
self.top_img = src_url
self.top_image = src_url
def set_imgs(self, imgs):
"""The motive for this method is the same as above, provide APIs
for both `article.imgs` and `article.images`
"""
self.images = imgs
self.imgs = imgs
def set_keywords(self, keywords):
"""Keys are stored in list format
"""
if not isinstance(keywords, list):
raise Exception("Keyword input must be list!")
if keywords:
self.keywords = keywords[:self.config.MAX_KEYWORDS]
def set_authors(self, authors):
"""Authors are in ["firstName lastName", "firstName lastName"] format
"""
if not isinstance(authors, list):
raise Exception("authors input must be list!")
if authors:
self.authors = authors[:self.config.MAX_AUTHORS]
def set_summary(self, summary):
"""Summary here refers to a paragraph of text from the
title text and body text
"""
self.summary = summary[:self.config.MAX_SUMMARY]
def set_meta_language(self, meta_lang):
"""Save langauges in their ISO 2-character form
"""
if meta_lang and len(meta_lang) >= 2 and \
meta_lang in get_available_languages():
self.meta_lang = meta_lang[:2]
def set_meta_keywords(self, meta_keywords):
"""Store the keys in list form
"""
self.meta_keywords = [k.strip() for k in meta_keywords.split(',')]
def set_meta_favicon(self, meta_favicon):
self.meta_favicon = meta_favicon
def set_meta_description(self, meta_description):
self.meta_description = meta_description
def set_meta_data(self, meta_data):
self.meta_data = meta_data
def set_canonical_link(self, canonical_link):
self.canonical_link = canonical_link
def set_tags(self, tags):
self.tags = tags
def set_movies(self, movie_objects):
"""Trim video objects into just urls
"""
movie_urls = [o.src for o in movie_objects if o and o.src]
self.movies = movie_urls
def throw_if_not_downloaded_verbose(self):
"""Parse ArticleDownloadState -> log readable status
-> maybe throw ArticleException
"""
if self.download_state == ArticleDownloadState.NOT_STARTED:
raise ArticleException('You must `download()` an article first!')
elif self.download_state == ArticleDownloadState.FAILED_RESPONSE:
raise ArticleException('Article `download()` failed with %s on URL %s' %
(self.download_exception_msg, self.url))
def throw_if_not_parsed_verbose(self):
"""Parse `is_parsed` status -> log readable status
-> maybe throw ArticleException
"""
if not self.is_parsed:
raise ArticleException('You must `parse()` an article first!')
Python Data Types Testing
import sys
from typing import Union
# Define types for mean function, trying to analyze input possibilities
Number = Union[int, float] # Number can be either int or float type
Numbers = list[Number] # Numbers is a list of Number types
Scores = Union[Number, Numbers] # Scores can be single or multiple
def mean(scores: Scores, method: int = 1) -> float:
"""
Calculate the mean of a list of scores.
Average and Average2 are hidden functions performing mean algorithm
If a single score is provided in scores, it is returned as the mean.
If a list of scores is provided, the average is calculated and returned.
"""
def average(scores):
"""Calculate the average of a list of scores using a Python for loop with rounding."""
sum = 0
len = 0
for score in scores:
if isinstance(score, Number):
sum += score
len += 1
else:
print("Bad data: " + str(score) + " in " + str(scores))
sys.exit()
return sum / len
def average2(scores):
"""Calculate the average of a list of scores using the built-in sum() function with rounding."""
return sum(scores) / len(scores)
# test to see if scores is a list of numbers
if isinstance(scores, list):
if method == 1:
# long method
result = average(scores)
else:
# built in method
result = average2(scores)
return round(result + 0.005, 2)
return scores # case where scores is a single valu
# try with one number
singleScore = 100
print("Print test data: " + str(singleScore)) # concat data for single line
print("Mean of single number: " + str(mean(singleScore)))
print()
# define a list of numbers
testScores = [90.5, 100, 85.4, 88]
print("Print test data: " + str(testScores))
print("Average score, loop method: " + str(mean(testScores)))
print("Average score, function method: " + str(mean(testScores, 2)))
print()
badData = [100, "NaN", 90]
print("Print test data: " + str(badData))
print("Mean with bad data: " + str(mean(badData)))
Print test data: 100
Mean of single number: 100
Print test data: [90.5, 100, 85.4, 88]
Average score, loop method: 90.98
Average score, function method: 90.98
Print test data: [100, 'NaN', 90]
Bad data: NaN in [100, 'NaN', 90]
An exception has occurred, use %tb to see the full traceback.
SystemExit
My Own Unique Implmentation
import wikipedia
# Ask the user what they want to learn about
search_term = input("What would you like to learn about? ")
try:
# Search for the page on Wikipedia
search_results = wikipedia.search(search_term)
if search_results:
# Get the summary of the first search result
page_summary = wikipedia.summary(search_results[0])
# Print the result
print(f"\nHere's what Wikipedia says about {search_results[0]}:\n")
print(page_summary)
else:
print("Sorry, no results found on Wikipedia for your search term.")
except wikipedia.exceptions.PageError:
# Handle page not found errors
print("Sorry, the page could not be found.")
Here's what Wikipedia says about JavaScript:
JavaScript (), often abbreviated as JS, is a programming language and core technology of the Web, alongside HTML and CSS. 99% of websites use JavaScript on the client side for webpage behavior.
Web browsers have a dedicated JavaScript engine that executes the client code. These engines are also utilized in some servers and a variety of apps. The most popular runtime system for non-browser usage is Node.js.
JavaScript is a high-level, often just-in-time compiled language that conforms to the ECMAScript standard. It has dynamic typing, prototype-based object-orientation, and first-class functions. It is multi-paradigm, supporting event-driven, functional, and imperative programming styles. It has application programming interfaces (APIs) for working with text, dates, regular expressions, standard data structures, and the Document Object Model (DOM).
The ECMAScript standard does not include any input/output (I/O), such as networking, storage, or graphics facilities. In practice, the web browser or other runtime system provides JavaScript APIs for I/O.
Although Java and JavaScript are similar in name, syntax, and respective standard libraries, the two languages are distinct and differ greatly in design.