10 more things you can do with the Python programming language. Python is used in science, engineer, and forward thinking entrepreneurial projects like Instagram and Pinterest.
10 more things you can do with the Python programming language. Python is used in science, engineer, and forward thinking entrepreneurial projects like Instagram and Pinterest.
How to train your python: iterables (FR)Jordi Riera
Les iterables de python3 101: Slides axées sur les itérables (list, tuple, dict, etc.) décrivant de bonnes pratiques pour développeurs python débutants
Implementasi Full Textsearch pada DatabaseDony Riyanto
Ini juga dokumen pendukung untuk sebuah kementerian yang hendak mengimplementasikan Full Textsearch pada database existing. Dokumen ini mengambil contoh kasus implementasi Full Textsearch pada stackoverflow menggunakan database PG
A simple explanation of why we use Python and how popular it is according to Stackoverflow survey and Github statement. The variety of benefits using Python and also mention about Open Source.
In the Python community we are taught from the outset of learning the language that the Zen of Python serves as a guide for how we should construct our codebases and projects. Rather than go into the zen-like meanings of each statement, this talk will explore how individual koans are implemented via detailed displays of sophisticated code examples.
How to Write a Popular Python Library by AccidentDaniel Greenfeld
We gave this talk as the opening keynote speech at PyCon Singapore. The theme of the talk is that most complex projects begin from humble origins. That you should create your own projects, sharing your knowledge and expertise.
My keynote speech from EuroPython, this talk explores what it is like being a developer in a community filled with experts from around the world. The goal of the talk is to provide useful content for beginners and topics of discussion for more advanced developers, while also focusing on Python’s strengths. Video of this talk is at http://www.youtube.com/watch?v=7TImWbnUDeI
How to train your python: iterables (FR)Jordi Riera
Les iterables de python3 101: Slides axées sur les itérables (list, tuple, dict, etc.) décrivant de bonnes pratiques pour développeurs python débutants
Implementasi Full Textsearch pada DatabaseDony Riyanto
Ini juga dokumen pendukung untuk sebuah kementerian yang hendak mengimplementasikan Full Textsearch pada database existing. Dokumen ini mengambil contoh kasus implementasi Full Textsearch pada stackoverflow menggunakan database PG
A simple explanation of why we use Python and how popular it is according to Stackoverflow survey and Github statement. The variety of benefits using Python and also mention about Open Source.
In the Python community we are taught from the outset of learning the language that the Zen of Python serves as a guide for how we should construct our codebases and projects. Rather than go into the zen-like meanings of each statement, this talk will explore how individual koans are implemented via detailed displays of sophisticated code examples.
How to Write a Popular Python Library by AccidentDaniel Greenfeld
We gave this talk as the opening keynote speech at PyCon Singapore. The theme of the talk is that most complex projects begin from humble origins. That you should create your own projects, sharing your knowledge and expertise.
My keynote speech from EuroPython, this talk explores what it is like being a developer in a community filled with experts from around the world. The goal of the talk is to provide useful content for beginners and topics of discussion for more advanced developers, while also focusing on Python’s strengths. Video of this talk is at http://www.youtube.com/watch?v=7TImWbnUDeI
Sphinx autodoc - automated api documentation - PyCon.MY 2015Takayuki Shimizukawa
Using the automated documentation feature of Sphinx, you can make with ease the extensive documentation of Python program.
You just write python function documents (docstrings), Sphinx organizes them into the document, can be converted to a variety of formats.
In this session, I'll explain a documentation procedure that uses with sphinx autodoc and autosummary extensions.
Sphinx autodoc - automated api documentation - PyCon.KR 2015Takayuki Shimizukawa
Using the automated documentation feature of Sphinx, you can make with ease the extensive documentation of Python program.
You just write python function documents (docstrings), Sphinx organizes them into the document, can be converted to a variety of formats.
In this session, I'll explain a documentation procedure that uses with sphinx autodoc and autosummary extensions.
introduction to Python by Mohamed Hegazy , in this slides you will find some code samples , these slides first presented in TensorFlow Dev Summit 2017 Extended by GDG Helwan
Python and Oracle : allies for best of data managementLaurent Leturgez
In this presentation, I described Python and how Python can Interact with Oracle database, and Oracle Cloud Infrastructure in various project : from data visualisation to data science.
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
Python
Language
is uesd in engineeringStory adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
Story adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
Story adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they should believe the change is really going to happen.
The decision maker:
Leaders usually control resources such as people, budgets, and equipment, and thus have the authority to make decisions (as per their span of control) that affect the initiative.
During change, leaders must leverage their decision-making authority and choose the options that will support the initiative.
The Decision-Maker is decisive and sets priorities that support change.
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they should believe the change is really going to happen.
The decision maker:
Leaders usually control resources such as people, budgets, and equipment, and thus have the authority to make decisions (as per their span of control) that affect the initiative.
During change, leaders must leverage their decision-making authority and choose the options that will support the initiative.
The Decision-Maker is decisive and sets priorities that support change.
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they s
An advanced forms presentation given with Miguel Araujo (marajop) at DjangoCon 2011. The transcript and slides is aimed at getting into Django Core, and Jacob Kaplan-Moss has stated this is his plan.
Admitting my flaws and turning them into virtues! This is a full length talk given it at DjangoCon US 2011, PyCon Australia 2011, and LA Django. The earliest version was a lightning talk given at the 2011 Hollywood hackathon.
Just to be clear, all of these things suck. Please DO NOT use these techniques! It was a joke, and if you attempt any of these things you are making a big mistake.
The slides printed for attendees of the Pycon 2010 Long Pinax Tutorial. James Tauber was the co-author and deserves tons of credit for his work. So does Brian Rosner and the rest of the Pinax team.
Why Django is created and maintained by myself, James Tauber, and others. Its purpose is to help individuals sell Django as a working platform. It is a work in progress, and will be updated periodically.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
3. Tons of content
• Please hold your questions until the end
• Latest slides: http://slidesha.re/intro-to-python
• Special thanks to: http://bit.ly/x610Au
• Raymond Hettinger
• David Beazley
• Audrey Roy
• The Python community
4. Daniel Greenfeld
• pydanny
• twitter.com/pydanny
• github.com/pydanny
• pydanny.blogspot.com
• pydanny-event-notes.rtfd.org
IMG goes here
http://www.flickr.com/photos/pydanny/4442245488/
5. Daniel Greenfeld
• Python/Django Developer
• Cartwheel Web
• Makers of
• Makers of Open Comparison
• Los Angeles
IMG goes here • Capoeira
• Fiancee is Audrey Roy
http://www.flickr.com/photos/pydanny/4442245488/
10. What is Python?
• Over 20 years old
• Dynamic, strongly typed scripting language
• Multi-paradigm programming language
• Object Oriented
• Functional
• Procedural
• Reflective
11. What is Python?
• Free and open source
• Fast enough
• Check out PyPy
• Batteries included language
12. What is Python?
http://en.wikipedia.org/wiki/File:Flyingcircus_2.jpg
It’s named after Monty Python
16. Whitespace!
""" whitespace.py """
from random import randrange
def numberizer():
# Generate a random number from 1 to 10.
return randrange(1, 11)
number = numberizer()
if number > 5:
print("This number is big!")
class RandomNumberHolder(object):
# Create and hold 20 random numbers using numberizer
def __init__(self):
self.numbers = [numberizer(x) for x in range(20)]
random_numbers = RandomNumberHolder()
19. Whitespace!
class RandomNumberHolder(object):
# Create and hold 20 random numbers
# using numberizer
def __init__(self):
self.numbers = [numberizer(x) for x...
random_numbers = RandomNumberHolder()
20. Philosophy of
Core Developers
• Conservative growth
• Aim for a simple implementation
• “We read Knuth so you don’t have to”
21. Zen of Python
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
22. Culture of Documentation
• Django Web Framework
• http://djangoproject.com
• Document everything and document well
• Make your documentation accessible
• http://readthedocs.org
• http://python-requests.org
• http://bit.ly/oc_ref (Open Comparison reference)
28. #1 Run it anywhere
Linux Windows
FreeBSD Mac OS X JVM
OpenBSD Solaris .NET
NetBSD HP-UX Android OS
BSD OS/2
http://en.wikipedia.org/wiki/CPython#Supported_platforms
29. #2 Learn it fast
Python is easy to learn but powerful.
Experienced developers get up to speed in days.
Lots of tutorials in the area taught by PyLadies.
http://learnpythonthehardway.org/
31. #3 Introspect
a.k.a Introducing the String type
>>> fun
'spam and EGGS '
>>> fun.strip()
'spam and EGGS' type() returns the type of object
>>> spam.title()
'Spam And Eggs '
>>> fun.capitalize()
'Spam and eggs '
>>> fun.index('a') Line comments start with ‘# ‘
2
>>> type(fun)
<type 'str'>
>>> len(fun) # built-in that gives length of object
16
>>> fun[0:5] # String slicing help() is a
'spam '
>>> help(fun) Python built-in
no Python documentation found for 'spam and EGGS '
>>> help(str)
str is the Python
string type object
32. #3 Introspect
a.k.a Introducing the String type
>>> help(str)
Help on class str in module __builtin__:
class str(basestring)
| str(object) -> string
|
| Return a nice string representation of the object.
| If the argument is a string, the return value is the same object.
|
| Method resolution order:
| str
| basestring
| object
|
| Methods defined here:
|
| __add__(...)
| x.__add__(y) <==> x+y
|
| __contains__(...)
| x.__contains__(y) <==> y in x
33. #3 Introspect
a.k.a Introducing the String type
>>> help(str)
| capitalize(...)
| S.capitalize() -> string
|
| Return a copy of the string S with only its first character
| capitalized.
|
| center(...)
| S.center(width[, fillchar]) -> string
|
| Return S centered in a string of length width. Padding is
| done using the specified fill character (default is a space)
|
| count(...)
| S.count(sub[, start[, end]]) -> int
|
| Return the number of non-overlapping occurrences of substring sub
in
| string S[start:end]. Optional arguments start and end are
interpreted
| as in slice notation.
34. #4 Things with Strings
>>> scale = 'Southern California Linux Expo'
>>> scale[0]
'S'
>>> scale[0:8]
'Southern'
>>> scale[:-5]
'Southern California Linux'
Strings are immutable
>>> scale[0:8] = 'Northern'
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> scale.replace('Southern California','SoCal')
'SoCal Linux Expo'
>>> scale
'Southern California Linux Expo'
>>> scale = scale.replace('Southern California','SoCal')
>>> scale
'SoCal Linux Expo'
>>> scale.startswith('Windows')
False
>>> scale.endswith('Windows')
False
>>> scale.startswith('SoCal')
True
>>> 'Windows' in scale
False
>>> 'Linux' in scale
True
35. #5 String formatting
>>> a = "Daniel"
>>> b = "Adam"
>>> c = "Greenfeld"
>>> a + b + c
'DanielAdamGreenfeld'
>>> "{0} {1} {2}".format(a, b, c)
'Daniel Adam Greenfeld'
>>> "{first} {middle} {last}".format(first=a, middle=b, last=c)
'Daniel Adam Greenfeld'
>>> lst = [a,b,c]
>>> lst
['Daniel', 'Adam', 'Greenfeld']
>>> name =" ".join(lst)
>>> name
'Daniel Adam Greenfeld'
36. #6 Basic Operations
>>> x, y, z = 5, 10, 15
>>> 5 < 10
True
>>> 5 > 10
False
Python has advanced math
>>> True == False features that comes with
False
>>> (5 == x) or (10 == x) the standard library.
True
>>> (5 == x) and (10 == x)
False
>>> x + y - z
0
>>> 10 * 5 For scientific needs,
50
>>> 10 / 5 numpy is available.
2
>>> 10 + 5
15
>>> 10 ** 2
100
38. #8 Lists + Functional Programming
>>> def divisible_by_2(x):
... return x % 2 == 0
...
>>> Filter constructs a list from
>>> def cube(x):
... return x ** 3
those elements of an iterable
... for which the specified function
>>>
>>> numbers = [1, 2, 3, 4, 6, 31]
returns True.
>>>
>>> filter(divisible_by_2, numbers)
[2, 4, 6]
>>>
>>> map(cube, numbers)
[1, 8, 27, 64, 216, 29791] Map applies the specified
function to every item of the
iterable and returns the results.
39. #9 List Comprehensions
Remember
""" whitespace.py """
from random import randrange this
def numberizer(): from the
# Generate a random number from 1 to 10.
return randrange(1, 11)
beginning?
number = numberizer()
if number > 5:
List Comprehension!
print("This number is big!")
class RandomNumberHolder(object):
# Create and hold 20 random numbers using numberizer
def __init__(self):
self.numbers = [numberizer(x) for x in range(20)]
random_numbers = RandomNumberHolder()
40. #9 List Comprehensions
>>> items = [x for x in range(20)]
>>> items
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> [x for x in range(20) if x % 2]
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
List Comprehensions are
wonderful syntactical sugar.
>>> # Fizzbuzz solved using Python's List Comprehension
>>> lst = [(x, 'Fizz', 'Buzz', 'FizzBuzz')
... [(not x % 3) | (not x % 5) << 1] for x in range(20)]
Backslash can be used to
break up long statements.
Please use sparingly!
41. #10 Generators
>>> def countdown(n):
... print("Counting down from {0}".format(n))
... while n > 0:
... yield n A generator evaluates only when the
... n -= 1 iterable is at that iteration. This is really
powerful, especially when working with
>>> x = countdown(10) large iterables.
>>> x
<generator object at 0x58490>
>>> x.next()
Counting down from 10
10 A billion iterations for
>>> x.next()
9 a generator is NOTHING.
>>> x.next()
8
>>> x.next()
7
http://dabeaz.com/generators/Generators.pdf
42. #11 Generator Expressions
>>> items = (str(x) for x in xrange(10000)) Generator expressions are
>>> items
<generator object <genexpr> at 0x100721460> shorthand for generators. Just
like list comprehensions, but
with () instead of [].
http://dabeaz.com/generators/Generators.pdf
43. #11 Generator Expressions
Problem: count the bytes saved to huge apache access log.
wwwlog = open("access-log")
total = 0 Open the whole file, then
for line in wwwlog:
bytestr = line.rsplit(None,1)[1] iterate through the results.
if bytestr != '-':
total += int(bytestr)
Lots of memory usage!
print "Total", total
# generator expressions way
Generator wwwlog = open("access-log")
bytecolumn = (line.rsplit(None,1)[1] for line in wwwlog)
way bytes = (int(x) for x in bytecolumn if x != '-')
print "Total", sum(bytes)
http://dabeaz.com/generators/Generators.pdf
44. #12 Sets
>>> lst = [1,1,1,1,1,2,2,2,3,3,3,3,3,3]
>>> s = set(lst)
>>> s
set([1,2,3])
Counting unique words in the Gettysburg Address
>>> address = """Four score and seven years ago our fathers brought..."""
>>> for r in [',','.','-']:
... address = address.replace(r,'')
>>>
>>>
words = address.split(' ')
len(words)
All items in a set need to
278
>>> unique_words = set(words)
be of the same type.
>>> len(unique_words)
143
48. #16 Colorize Code
How Github and Bitbucket do it
$ pip install pygments
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
if __name__ == '__main__':
# get this file
pygments_demo.py
code = open("pygments_demo.py", "rw").read()
# figure out the lexer
lexer = get_lexer_by_name("python", stripall=True)
# construct the formatter
formatter = HtmlFormatter(linenos=False, cssclass="source")
# style and formatting
css = HtmlFormatter().get_style_defs('.source')
highlighted_code = highlight(code, lexer, formatter)
page = """
$ python pygments_demo.py > text.html
<html>
<head><style>{css}</style></head>
<body>{highlighted_code}</body>
</html>
""".format(css=css, highlighted_code=highlighted_code)
print(page)
49. Output of the program
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter text.html
if __name__ == '__main__':
# get this file
code = open("pygments_demo.py", "rw").read()
# figure out the lexer
lexer = get_lexer_by_name("python", stripall=True)
# construct the formatter
formatter = HtmlFormatter(linenos=False, cssclass="source")
# style and formatting
css = HtmlFormatter().get_style_defs('.source')
highlighted_code = highlight(code, lexer, formatter)
page = """
<html>
<head><style>{css}</style></head>
<body>{highlighted_code}</body>
</html>
""".format(css=css, highlighted_code=highlighted_code)
print(page)
50. #17 Work with Relational Databases
(my_env)$ pip install django
from datetime import datetime Internationalization!
from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Post(models.Model):
author = models.ForeignKey(User)
title = models.CharField(_('Title'), max_length=100)
content = models.TextField(_("Content"))
pub_date = models.DateTimeField(_("Publication date"))
class Comment(models.Model):
post = models.ForeignKey(Post)
name = models.CharField(_('Title'), max_length=100)
content = models.TextField(_("Content"))