A tour of Python: slides from presentation given in 2012.
[Some slides are not properly rendered in SlideShare: the original is still available at http://www.aleksa.org/2015/04/python-presentation_7.html.]
This document discusses different options for parsing command line arguments in Python scripts, including raw argv parsing, getopt, argparse, and docopt. It notes that raw argv parsing and getopt are old-style parsing methods, while argparse is built into Python but may be complex. Docopt is introduced as a module that focuses on usage documentation rather than code, allowing the usage to be defined in a script's docstring. Examples are provided for argparse and more complex usages with docopt.
[PyConKR 2018] Imugi: Compiler made with Python.
https://www.pycon.kr/2018/program/2/
GitHub: https://github.com/hahnlee/imugi
The document summarizes the key features of ES6 (ECMAScript 2015), the next version of JavaScript. It discusses new features like block scoping with let and const, arrow functions, classes, enhanced object literals, template strings, and promises. It also covers iterators and generators, which allow iterable objects to be looped over and asynchronous code to be written more cleanly. The presentation provides examples to illustrate how developers can take advantage of these new language features in their code.
[Droid knights 2019] Tensorflow Lite 부터 ML Kit, Mobile GPU 활용 까지Jeongah Shin
Droid Knights 2019 세션 발표 내용입니다.
주제 : Tensorflow Lite 부터 ML Kit, Mobile GPU 활용 까지
내용 : 간단한 데모앱의 제작 과정을 되짚어보며 안드로이드 환경에서 Tensorflow Lite과 ML Kit을 활용하여 모바일 머신러닝 앱을 만드는 방법에 대해 설명 합니다. 더불어, Tensorflow Lite에서 2019년 1월 출시된 Feature인 Mobile GPU의 활용 까지 다룹니다.
* gif 움짤이 많아 세션 내용을 담은 문서를 따로 정리하였습니다.
https://github.com/motlabs/awesome-ml-demos-with-android
This document contains tips and explanations about various Ruby on Rails concepts and methods, including:
1) Object::try, which allows calling methods on an object that may be nil without raising an error.
2) Object::presence, which returns the object itself unless it is nil or an empty object, in which case it returns nil.
3) Object::send, which allows calling methods by name as a string, including private methods.
4) Other methods like freeze, inject, tap, and ways to extend Ruby classes are also explained briefly.
FITC events. For digital creators.
Save 10% off ANY FITC event with discount code 'slideshare'
See our upcoming events at www.fitc.ca
An Intro To ES6
with Grant Skinner
OVERVIEW
ECMAScript 6 is the approved and published standard for the next version of JavaScript. It offers new syntax and language features that provide new ways of tackling coding problems, and increase your productivity.
This session will introduce ES6 and delve into many of the new features of the language. It will also cover real-world use, including transpilers, runtimes, and browser support.
OBJECTIVE
Create confidence in evaluating and getting started using ES6.
TARGET AUDIENCE
JavaScript developers.
ASSUMED AUDIENCE KNOWLEDGE
JavaScript.
FOUR THINGS AUDIENCE MEMBERS WILL LEARN
Status of ES6
How to get started with ES6
ES6 feature overview
Practical considerations for adopting ES6
The document describes ray tracing and how it can be implemented in a modular way using ZIO. It discusses:
1. The key components of ray tracing including a world (spheres, light source, camera), incident rays, reflected rays, discarded rays, and colored pixels on a canvas.
2. Options for computing rays, including computing all rays or only those from the camera through the canvas.
3. How transformations can be handled in a module with services to apply transformations and compose them.
4. Other modules including for camera, world, and rastering to generate colored pixels from the world and camera. The overall architecture is designed to be composable using ZIO.
This document provides an overview of advanced Python concepts including: inheritance and the MRO; mixins; variable scope; iterators and generators; list comprehensions; itertools; coroutines; operator overloading; __getattr__ and __dict__; decorators; descriptors; properties; functions vs methods; type and metaprogramming; and using __metaclass__. It includes code examples to demonstrate these concepts.
The document describes ZIO, a functional programming library for Scala. It discusses how:
- ZIO programs are values that define effects to run concurrently using fibers.
- The R in ZIO[R, E, A] represents requirements - services required to run the program.
- Requirements can be eliminated by providing values using ZIO.provide.
- Modules define services using Has and provide accessor methods via ZIO.accessM.
- ZLayer represents recipes for building requirement outputs from inputs or resources. It is backed by ZManaged for safe acquisition/release.
Highlights a bunch of different Python tricks and tips - from the stupid to the awesome (and a bit of both).
See how to register a 'str'.decode('hail_mary') codec, call_functions[1, 2, 3] instead of call_functions(1, 2, 3), creating a "Clojure-like" threading syntax by overloading the pipe operator, create useful equality mocks by overloading the equality operator, ditch JSON for pySON and put together a tiny lisp based on Norvig's awesome article.
The document provides an introduction to C++ programming. It outlines topics that will be covered such as basic syntax, compiling programs, argument passing, dynamic memory, and object-oriented programming. It recommends some useful books and websites for learning C++ and notes that the tutorial will demonstrate features of the language through examples while emphasizing learning through practice.
io.Reader, io.Writer, and io.ReadWriter are some of the most powerful, yet surprisingly subtle, tools in the Go standard library. In this talk, we'll explore two concrete examples leveraging these building blocks to construct expressive and performant abstractions. We'll also cover details of package bufio, the LimitReader, and other techniques to rain kittens on our code and dial it up to 11.
The document provides an introduction to C++ programming. It outlines topics that will be covered, including basic syntax, compiling programs, passing arguments, dynamic memory allocation, and object-oriented programming. It recommends several useful books and web resources for learning C++ and offers a live coding demonstration of a simple image class to illustrate C++ concepts. The overall tone is informative but acknowledges that C++ is complex and learning requires practice.
The document discusses queues and their implementation. It defines a queue as a FIFO data structure where new items are added to the rear and removed from the front. Key queue operations are described like add, remove, isEmpty and isFull. The document then provides examples of implementing a queue using arrays and pointers in C++. It includes functions for initialization, insertion, removal, checking if empty, and printing all elements.
RHadoop is an open source project aiming to combine two rising star in the analytics firmament: R and Hadoop. With more than 2M users, R is arguably the dominant language to express complex statistical computations. Hadoop needs no introduction at HUG. With RHadoop we are trying to combine the expressiveness of R with the scalability of Hadoop and to pave the way for the statistical community to tackle big data with the tools they are familiar with. At this time RHadoop is a collection of three packages that interface with HDFS, HBase and mapreduce, respectively. For mapreduce, the package is called rmr and we tried to give it a simple, high level interface that's true to the mapreduce model and integrated with the rest of the language. We will cover the API and provide some examples.
The document compares and contrasts object-oriented programming concepts between JavaScript and ActionScript 3. Some key differences include:
- JavaScript uses prototypes instead of classes for inheritance and does not have keywords like "extends"
- Scope in JavaScript functions can be tricky due to closures
- Animation in JavaScript requires manually redrawing the entire canvas each frame rather than updating individual objects
- Interactivity on HTML5 canvas elements only occurs at the canvas level rather than on child objects
This document discusses various Ruby array and string methods like capitalize, each_char, map, sample, shuffle, zip, and more. Code snippets demonstrate how to use these methods on arrays and strings in Ruby. The document also discusses using Node.js and IRB to test Ruby code snippets and the potential to write tests for Ruby code using a BDD style.
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPythonakaptur
This document discusses Byterun, a Python interpreter written in Python. It explains how Python code is compiled to bytecode which is then interpreted. Key points made include:
- Python code is first compiled to bytecode, which is a sequence of bytes representing operations and arguments.
- The dis module can disassemble bytecode back into a human-readable format showing the instructions.
- The interpreter works by reading each bytecode instruction and carrying out the corresponding operation, such as loading variables or performing arithmetic.
- This dynamic execution allows Python to behave differently based on the types of values at runtime, like formatting strings.
Diving into byte code optimization in python Chetan Giridhar
The document discusses byte-code optimization in Python. It begins by explaining that Python source code is compiled into byte code, which is then executed by the CPython interpreter. It describes some of the key steps in the compilation process, including parsing the source code and generating an abstract syntax tree (AST) before compiling to bytecodes. The document then discusses some approaches for optimizing Python code at the byte-code level, including using tools like Pyrex, Psyco and the Python bytecode manipulation library BytePlay. It recommends always profiling applications to identify optimization opportunities and considering writing performance-critical portions as C extensions.
The document introduces OCaml×Scope, a new API search engine for OCaml similar to Hoogle for Haskell. It summarizes the limitations of existing OCaml API search tools and describes how OCaml×Scope addresses these by scraping documentation from cmt/cmti files of over 100 OPAM packages. Future work includes improving search results grouping, adding a better web GUI, and integrating remote querying. The tool provides name and type-based searching of OCaml APIs to help programmers.
This document provides an overview of programming with Go Lang. It discusses why Go Lang is useful, including its support for multicore performance, microservices, concurrency, static binaries, and testing. It then covers various Go Lang content like first apps, types, loops, functions, arrays/slices/maps, interfaces, methods, empty interfaces, pointers, and error handling. Code examples are provided to demonstrate many of these concepts.
Implementing virtual machines in go & c 2018 reduxEleanor McHugh
An updated version of my talk on virtual machine cores comparing techniques in C and Go for implementing dispatch loops, stacks & hash maps.
Lots of tested and debugged code is provided as well as references to some useful/interesting books.
Presented by Stephen Murtagh, Etsy.com, Inc.
TF-IDF (term frequency, inverse document frequency) is a standard method of weighting query terms for scoring documents, and is the method that is used by default in Solr/Lucene. Unfortunately, TF-IDF is really only a measure of rarity, not quality or usefulness. This means it would give more weight to a useless, rare term, such as a misspelling, than to a more useful, but more common, term.
In this presentation, we will discuss our experiences replacing Lucene's TF-IDF based scoring function with a more useful one using information gain, a standard machine-learning measure that combines frequency and specificity. Information gain is much more expensive to compute, however, so this requires periodically computing the term weights outside of Solr/Lucene and making the results accessible within Solr/Lucene.
This document discusses using the C to Go translation tool c2go to translate C code implementing quicksort algorithms into Go code. It provides examples of translating simple quicksort C code, improving the translation by using a configuration file, and how c2go handles standard C functions like qsort by translating them to their Go equivalents. The examples demonstrate how c2go can generate valid Go code from C code but may require some manual fixes or configuration to handle certain data structures or language differences.
This document provides a summary of key C++ concepts for an online certification course from the Global Open University, including pointers, arrays, parameter passing, classes, constructors/destructors, inheritance, virtual functions, and coding tips. It includes code examples and explanations for working with pointers, arrays, strings, parameter passing, classes, inheritance, polymorphism, and best practices for avoiding errors. The full course material can be accessed online at the provided URL.
The document discusses strategies for understanding the CPython implementation of Python without reading the code. It recommends using observation and experimentation techniques like inspecting code behavior, examining commit histories, understanding internal structures through disassembly, running performance tests, and writing tests. Tools mentioned include inspect, timeit, and custom inspection modules. The key message is that these hands-on techniques allow one to critically examine and experiment with the code in ways that provide deeper understanding than just reading it.
The document discusses benchmarking and profiling in Elixir. It begins with an introduction to Elixir and some of its common uses like web applications. It then covers topics like what benchmarking is, different types of benchmarks, and tools for benchmarking in Elixir. An example is provided benchmarking tail call optimization by comparing recursive and iterative sum functions. The document ends by discussing parallelism benchmarks and noting that benchmarks may not represent real user performance.
The document discusses functional programming concepts in Swift such as functors, monads, and higher-order functions. It provides examples of how to use functions like map, flatMap, filter and reduce to transform collections. It also discusses topics like cognitive complexity, pure functions, and how functors are containers that can be mapped while monads support flatMapping to flatten nested collections.
This document provides an overview of dictionaries in Python. It discusses how dictionaries are defined using curly braces {}, how keys can be any immutable object like strings or numbers while values can be any object, and how to access values using keys. It also covers adding and deleting key-value pairs, checking for keys, shallow and deep copying, and creating dictionaries from keys or sequences.
This document provides an introduction to Python including:
- The major versions of Python and their differences
- Popular integrated development environments for Python
- How to set up Python environments using Anaconda and Eclipse
- An overview of Python basics like variables, numbers, strings, lists, dictionaries, modules and functions
- Examples of Python control flow structures like conditionals and loops
The document describes ZIO, a functional programming library for Scala. It discusses how:
- ZIO programs are values that define effects to run concurrently using fibers.
- The R in ZIO[R, E, A] represents requirements - services required to run the program.
- Requirements can be eliminated by providing values using ZIO.provide.
- Modules define services using Has and provide accessor methods via ZIO.accessM.
- ZLayer represents recipes for building requirement outputs from inputs or resources. It is backed by ZManaged for safe acquisition/release.
Highlights a bunch of different Python tricks and tips - from the stupid to the awesome (and a bit of both).
See how to register a 'str'.decode('hail_mary') codec, call_functions[1, 2, 3] instead of call_functions(1, 2, 3), creating a "Clojure-like" threading syntax by overloading the pipe operator, create useful equality mocks by overloading the equality operator, ditch JSON for pySON and put together a tiny lisp based on Norvig's awesome article.
The document provides an introduction to C++ programming. It outlines topics that will be covered such as basic syntax, compiling programs, argument passing, dynamic memory, and object-oriented programming. It recommends some useful books and websites for learning C++ and notes that the tutorial will demonstrate features of the language through examples while emphasizing learning through practice.
io.Reader, io.Writer, and io.ReadWriter are some of the most powerful, yet surprisingly subtle, tools in the Go standard library. In this talk, we'll explore two concrete examples leveraging these building blocks to construct expressive and performant abstractions. We'll also cover details of package bufio, the LimitReader, and other techniques to rain kittens on our code and dial it up to 11.
The document provides an introduction to C++ programming. It outlines topics that will be covered, including basic syntax, compiling programs, passing arguments, dynamic memory allocation, and object-oriented programming. It recommends several useful books and web resources for learning C++ and offers a live coding demonstration of a simple image class to illustrate C++ concepts. The overall tone is informative but acknowledges that C++ is complex and learning requires practice.
The document discusses queues and their implementation. It defines a queue as a FIFO data structure where new items are added to the rear and removed from the front. Key queue operations are described like add, remove, isEmpty and isFull. The document then provides examples of implementing a queue using arrays and pointers in C++. It includes functions for initialization, insertion, removal, checking if empty, and printing all elements.
RHadoop is an open source project aiming to combine two rising star in the analytics firmament: R and Hadoop. With more than 2M users, R is arguably the dominant language to express complex statistical computations. Hadoop needs no introduction at HUG. With RHadoop we are trying to combine the expressiveness of R with the scalability of Hadoop and to pave the way for the statistical community to tackle big data with the tools they are familiar with. At this time RHadoop is a collection of three packages that interface with HDFS, HBase and mapreduce, respectively. For mapreduce, the package is called rmr and we tried to give it a simple, high level interface that's true to the mapreduce model and integrated with the rest of the language. We will cover the API and provide some examples.
The document compares and contrasts object-oriented programming concepts between JavaScript and ActionScript 3. Some key differences include:
- JavaScript uses prototypes instead of classes for inheritance and does not have keywords like "extends"
- Scope in JavaScript functions can be tricky due to closures
- Animation in JavaScript requires manually redrawing the entire canvas each frame rather than updating individual objects
- Interactivity on HTML5 canvas elements only occurs at the canvas level rather than on child objects
This document discusses various Ruby array and string methods like capitalize, each_char, map, sample, shuffle, zip, and more. Code snippets demonstrate how to use these methods on arrays and strings in Ruby. The document also discusses using Node.js and IRB to test Ruby code snippets and the potential to write tests for Ruby code using a BDD style.
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPythonakaptur
This document discusses Byterun, a Python interpreter written in Python. It explains how Python code is compiled to bytecode which is then interpreted. Key points made include:
- Python code is first compiled to bytecode, which is a sequence of bytes representing operations and arguments.
- The dis module can disassemble bytecode back into a human-readable format showing the instructions.
- The interpreter works by reading each bytecode instruction and carrying out the corresponding operation, such as loading variables or performing arithmetic.
- This dynamic execution allows Python to behave differently based on the types of values at runtime, like formatting strings.
Diving into byte code optimization in python Chetan Giridhar
The document discusses byte-code optimization in Python. It begins by explaining that Python source code is compiled into byte code, which is then executed by the CPython interpreter. It describes some of the key steps in the compilation process, including parsing the source code and generating an abstract syntax tree (AST) before compiling to bytecodes. The document then discusses some approaches for optimizing Python code at the byte-code level, including using tools like Pyrex, Psyco and the Python bytecode manipulation library BytePlay. It recommends always profiling applications to identify optimization opportunities and considering writing performance-critical portions as C extensions.
The document introduces OCaml×Scope, a new API search engine for OCaml similar to Hoogle for Haskell. It summarizes the limitations of existing OCaml API search tools and describes how OCaml×Scope addresses these by scraping documentation from cmt/cmti files of over 100 OPAM packages. Future work includes improving search results grouping, adding a better web GUI, and integrating remote querying. The tool provides name and type-based searching of OCaml APIs to help programmers.
This document provides an overview of programming with Go Lang. It discusses why Go Lang is useful, including its support for multicore performance, microservices, concurrency, static binaries, and testing. It then covers various Go Lang content like first apps, types, loops, functions, arrays/slices/maps, interfaces, methods, empty interfaces, pointers, and error handling. Code examples are provided to demonstrate many of these concepts.
Implementing virtual machines in go & c 2018 reduxEleanor McHugh
An updated version of my talk on virtual machine cores comparing techniques in C and Go for implementing dispatch loops, stacks & hash maps.
Lots of tested and debugged code is provided as well as references to some useful/interesting books.
Presented by Stephen Murtagh, Etsy.com, Inc.
TF-IDF (term frequency, inverse document frequency) is a standard method of weighting query terms for scoring documents, and is the method that is used by default in Solr/Lucene. Unfortunately, TF-IDF is really only a measure of rarity, not quality or usefulness. This means it would give more weight to a useless, rare term, such as a misspelling, than to a more useful, but more common, term.
In this presentation, we will discuss our experiences replacing Lucene's TF-IDF based scoring function with a more useful one using information gain, a standard machine-learning measure that combines frequency and specificity. Information gain is much more expensive to compute, however, so this requires periodically computing the term weights outside of Solr/Lucene and making the results accessible within Solr/Lucene.
This document discusses using the C to Go translation tool c2go to translate C code implementing quicksort algorithms into Go code. It provides examples of translating simple quicksort C code, improving the translation by using a configuration file, and how c2go handles standard C functions like qsort by translating them to their Go equivalents. The examples demonstrate how c2go can generate valid Go code from C code but may require some manual fixes or configuration to handle certain data structures or language differences.
This document provides a summary of key C++ concepts for an online certification course from the Global Open University, including pointers, arrays, parameter passing, classes, constructors/destructors, inheritance, virtual functions, and coding tips. It includes code examples and explanations for working with pointers, arrays, strings, parameter passing, classes, inheritance, polymorphism, and best practices for avoiding errors. The full course material can be accessed online at the provided URL.
The document discusses strategies for understanding the CPython implementation of Python without reading the code. It recommends using observation and experimentation techniques like inspecting code behavior, examining commit histories, understanding internal structures through disassembly, running performance tests, and writing tests. Tools mentioned include inspect, timeit, and custom inspection modules. The key message is that these hands-on techniques allow one to critically examine and experiment with the code in ways that provide deeper understanding than just reading it.
The document discusses benchmarking and profiling in Elixir. It begins with an introduction to Elixir and some of its common uses like web applications. It then covers topics like what benchmarking is, different types of benchmarks, and tools for benchmarking in Elixir. An example is provided benchmarking tail call optimization by comparing recursive and iterative sum functions. The document ends by discussing parallelism benchmarks and noting that benchmarks may not represent real user performance.
The document discusses functional programming concepts in Swift such as functors, monads, and higher-order functions. It provides examples of how to use functions like map, flatMap, filter and reduce to transform collections. It also discusses topics like cognitive complexity, pure functions, and how functors are containers that can be mapped while monads support flatMapping to flatten nested collections.
This document provides an overview of dictionaries in Python. It discusses how dictionaries are defined using curly braces {}, how keys can be any immutable object like strings or numbers while values can be any object, and how to access values using keys. It also covers adding and deleting key-value pairs, checking for keys, shallow and deep copying, and creating dictionaries from keys or sequences.
This document provides an introduction to Python including:
- The major versions of Python and their differences
- Popular integrated development environments for Python
- How to set up Python environments using Anaconda and Eclipse
- An overview of Python basics like variables, numbers, strings, lists, dictionaries, modules and functions
- Examples of Python control flow structures like conditionals and loops
This document provides an overview and introduction to NumPy, a fundamental package for scientific computing in Python. It discusses NumPy's core capabilities like N-dimensional arrays and universal functions for fast element-wise operations. The document also briefly introduces SciPy which builds upon NumPy and provides many scientific algorithms. Finally, it demonstrates basic NumPy operations like creating arrays, slicing, indexing, and plotting to visualize data.
This document provides an overview of the Python programming language. It discusses that Python is a popular, object-oriented scripting language that emphasizes code readability. The document summarizes key Python features such as rapid development, automatic memory management, object-oriented programming, and embedding/extending with C. It also outlines common uses of Python and when it may not be suitable.
This document provides an introduction to the Python programming language. It covers basic Python concepts like data types, strings, data structures, classes, methods, exceptions, iterations, generators, and scopes. Python is described as an easy to learn, read, and use dynamic language with a large selection of stable libraries. It is presented as being much easier than bash scripts for building and maintaining complex system infrastructure.
A high level introduction to R statistical programming language that was presented at the Chicago Data Visualization Group's Graphing in R and ggplot2 workshop on October 8, 2012.
En esta charla veremos con detalle algunas de las construcciones más pythonicas y las posibilidades de expresar de forma clara, concisa y elegante cosas que en otros lenguajes nos obligarían a dar muchos rodeos.
A veces es fácil olvidar algunos recursos como que una función puede devolver varios valores, cómo manipular listas y diccionarios de forma sencilla, contextos, generadores... En esta charla veremos de forma entretenida y práctica cómo mejorar nuestro nivel de Python "nativo".
Python 101 language features and functional programmingLukasz Dynowski
1. The document provides examples of using various programming languages like JavaScript, Java, PHP, Python to perform common operations like reversing a string, finding an element in an array, and using data structures like lists, dictionaries, tuples, and sets.
2. It also discusses functional programming concepts like iterators, generators, map, filter and reduce functions, and using lambda expressions.
3. Examples are given for file handling, pickling, list and generator comprehensions in Python.
This document provides an introduction to the Python programming language. It outlines key topics like why use Python, running Python code, data types and operators, basic statements like if/while/for loops, functions, and examples of simple Python programs. It also discusses common industry applications of Python like web development, scientific applications, databases, and education. Major companies that use Python extensively are listed, such as Google, NASA, Industrial Light & Magic, Yahoo, and RedHat.
This document discusses refactoring Java code to Clojure using macros. It provides examples of refactoring Java code that uses method chaining to equivalent Clojure code using the threading macros (->> and -<>). It also discusses other Clojure features like type hints, the doto macro, and polyglot projects using Leiningen.
Elixir is a functional programming language that is well-suited for building scalable and fault-tolerant applications. The document provides an introduction to Elixir by discussing its roots in Erlang and how it builds upon Erlang's strengths like concurrency, distribution, and fault tolerance. It also demonstrates some basic Elixir concepts like functions, pattern matching, recursion, and the BEAM virtual machine. Finally, it provides examples of real-world applications of Elixir like building Phoenix web applications and developing embedded hardware projects with Nerves.
The document discusses various built-in functions in Python including numeric, string, and container data types. It provides examples of using list comprehensions, dictionary comprehensions, lambda functions, enumerate, zip, filter, any, all, map and reduce to manipulate data in Python. It also includes references to online resources for further reading.
GE8151 Problem Solving and Python ProgrammingMuthu Vinayagam
The document provides information about various Python concepts like print statement, variables, data types, operators, conditional statements, loops, functions, modules, exceptions, files and packages. It explains print statement syntax, how variables work in Python, built-in data types like numbers, strings, lists, dictionaries and tuples. It also discusses conditional statements like if-else, loops like while and for, functions, modules, exceptions, file handling operations and packages in Python.
This document contains a presentation on self-learning modules in Python. It discusses:
1. Assigning modules to different students for learning.
2. Modules, packages, and libraries as different ways to reuse code in Python. A module is a file with the .py extension, a package is a folder containing modules, and a library is a collection of packages.
3. The Python standard library contains built-in functions and modules that are part of the Python installation. Common modules discussed include math, random, and urllib.
This document discusses various techniques for optimizing Python code, including:
1. Using the right algorithms and data structures to minimize time complexity, such as choosing lists, sets or dictionaries based on needed functionality.
2. Leveraging Python-specific optimizations like string concatenation, lookups, loops and imports.
3. Profiling code with tools like timeit, cProfile and visualizers to identify bottlenecks before optimizing.
4. Optimizing only after validating a performance need and starting with general strategies before rewriting hotspots in Python or other languages. Premature optimization can complicate code.
C++ allows for concise summaries in 3 sentences or less:
The document provides an overview of C++ concepts including data types, variables, operators, functions, classes, inheritance and virtual members. It also covers process and thread concepts at a high level. Code examples are provided to illustrate namespaces, input/output, program flow control, overloading, dynamic memory allocation, and classes. The document serves as a brief review of fundamental C++ and system programming concepts.
Python 101++: Let's Get Down to Business!Paige Bailey
You've started the Codecademy and Coursera courses; you've thumbed through Zed Shaw's "Learn Python the Hard Way"; and now you're itching to see what Python can help you do. This is the workshop for you!
Here's the breakdown: we're going to be taking you on a whirlwind tour of Python's capabilities. By the end of the workshop, you should be able to easily follow any of the widely available Python courses on the internet, and have a grasp on some of the more complex aspects of the language.
Please don't forget to bring your personal laptop!
Audience: This course is aimed at those who already have some basic programming experience, either in Python or in another high level programming language (such as C/C++, Fortran, Java, Ruby, Perl, or Visual Basic). If you're an absolute beginner -- new to Python, and new to programming in general -- make sure to check out the "Python 101" workshop!
Download Wondershare Filmora Crack [2025] With Latesttahirabibi60507
Copy & Past Link 👉👉
http://drfiles.net/
Wondershare Filmora is a video editing software and app designed for both beginners and experienced users. It's known for its user-friendly interface, drag-and-drop functionality, and a wide range of tools and features for creating and editing videos. Filmora is available on Windows, macOS, iOS (iPhone/iPad), and Android platforms.
Join Ajay Sarpal and Miray Vu to learn about key Marketo Engage enhancements. Discover improved in-app Salesforce CRM connector statistics for easy monitoring of sync health and throughput. Explore new Salesforce CRM Synch Dashboards providing up-to-date insights into weekly activity usage, thresholds, and limits with drill-down capabilities. Learn about proactive notifications for both Salesforce CRM sync and product usage overages. Get an update on improved Salesforce CRM synch scale and reliability coming in Q2 2025.
Key Takeaways:
Improved Salesforce CRM User Experience: Learn how self-service visibility enhances satisfaction.
Utilize Salesforce CRM Synch Dashboards: Explore real-time weekly activity data.
Monitor Performance Against Limits: See threshold limits for each product level.
Get Usage Over-Limit Alerts: Receive notifications for exceeding thresholds.
Learn About Improved Salesforce CRM Scale: Understand upcoming cloud-based incremental sync.
Adobe Master Collection CC Crack Advance Version 2025kashifyounis067
🌍📱👉COPY LINK & PASTE ON GOOGLE http://drfiles.net/ 👈🌍
Adobe Master Collection CC (Creative Cloud) is a comprehensive subscription-based package that bundles virtually all of Adobe's creative software applications. It provides access to a wide range of tools for graphic design, video editing, web development, photography, and more. Essentially, it's a one-stop-shop for creatives needing a broad set of professional tools.
Key Features and Benefits:
All-in-one access:
The Master Collection includes apps like Photoshop, Illustrator, InDesign, Premiere Pro, After Effects, Audition, and many others.
Subscription-based:
You pay a recurring fee for access to the latest versions of all the software, including new features and updates.
Comprehensive suite:
It offers tools for a wide variety of creative tasks, from photo editing and illustration to video editing and web development.
Cloud integration:
Creative Cloud provides cloud storage, asset sharing, and collaboration features.
Comparison to CS6:
While Adobe Creative Suite 6 (CS6) was a one-time purchase version of the software, Adobe Creative Cloud (CC) is a subscription service. CC offers access to the latest versions, regular updates, and cloud integration, while CS6 is no longer updated.
Examples of included software:
Adobe Photoshop: For image editing and manipulation.
Adobe Illustrator: For vector graphics and illustration.
Adobe InDesign: For page layout and desktop publishing.
Adobe Premiere Pro: For video editing and post-production.
Adobe After Effects: For visual effects and motion graphics.
Adobe Audition: For audio editing and mixing.
Explaining GitHub Actions Failures with Large Language Models Challenges, In...ssuserb14185
GitHub Actions (GA) has become the de facto tool that developers use to automate software workflows, seamlessly building, testing, and deploying code. Yet when GA fails, it disrupts development, causing delays and driving up costs. Diagnosing failures becomes especially challenging because error logs are often long, complex and unstructured. Given these difficulties, this study explores the potential of large language models (LLMs) to generate correct, clear, concise, and actionable contextual descriptions (or summaries) for GA failures, focusing on developers’ perceptions of their feasibility and usefulness. Our results show that over 80% of developers rated LLM explanations positively in terms of correctness for simpler/small logs. Overall, our findings suggest that LLMs can feasibly assist developers in understanding common GA errors, thus, potentially reducing manual analysis. However, we also found that improved reasoning abilities are needed to support more complex CI/CD scenarios. For instance, less experienced developers tend to be more positive on the described context, while seasoned developers prefer concise summaries. Overall, our work offers key insights for researchers enhancing LLM reasoning, particularly in adapting explanations to user expertise.
https://arxiv.org/abs/2501.16495
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfTechSoup
In this webinar we will dive into the essentials of generative AI, address key AI concerns, and demonstrate how nonprofits can benefit from using Microsoft’s AI assistant, Copilot, to achieve their goals.
This event series to help nonprofits obtain Copilot skills is made possible by generous support from Microsoft.
What You’ll Learn in Part 2:
Explore real-world nonprofit use cases and success stories.
Participate in live demonstrations and a hands-on activity to see how you can use Microsoft 365 Copilot in your own work!
Adobe Lightroom Classic Crack FREE Latest link 2025kashifyounis067
🌍📱👉COPY LINK & PASTE ON GOOGLE http://drfiles.net/ 👈🌍
Adobe Lightroom Classic is a desktop-based software application for editing and managing digital photos. It focuses on providing users with a powerful and comprehensive set of tools for organizing, editing, and processing their images on their computer. Unlike the newer Lightroom, which is cloud-based, Lightroom Classic stores photos locally on your computer and offers a more traditional workflow for professional photographers.
Here's a more detailed breakdown:
Key Features and Functions:
Organization:
Lightroom Classic provides robust tools for organizing your photos, including creating collections, using keywords, flags, and color labels.
Editing:
It offers a wide range of editing tools for making adjustments to color, tone, and more.
Processing:
Lightroom Classic can process RAW files, allowing for significant adjustments and fine-tuning of images.
Desktop-Focused:
The application is designed to be used on a computer, with the original photos stored locally on the hard drive.
Non-Destructive Editing:
Edits are applied to the original photos in a non-destructive way, meaning the original files remain untouched.
Key Differences from Lightroom (Cloud-Based):
Storage Location:
Lightroom Classic stores photos locally on your computer, while Lightroom stores them in the cloud.
Workflow:
Lightroom Classic is designed for a desktop workflow, while Lightroom is designed for a cloud-based workflow.
Connectivity:
Lightroom Classic can be used offline, while Lightroom requires an internet connection to sync and access photos.
Organization:
Lightroom Classic offers more advanced organization features like Collections and Keywords.
Who is it for?
Professional Photographers:
PCMag notes that Lightroom Classic is a popular choice among professional photographers who need the flexibility and control of a desktop-based application.
Users with Large Collections:
Those with extensive photo collections may prefer Lightroom Classic's local storage and robust organization features.
Users who prefer a traditional workflow:
Users who prefer a more traditional desktop workflow, with their original photos stored on their computer, will find Lightroom Classic a good fit.
FL Studio Producer Edition Crack 2025 Full Versiontahirabibi60507
Copy & Past Link 👉👉
http://drfiles.net/
FL Studio is a Digital Audio Workstation (DAW) software used for music production. It's developed by the Belgian company Image-Line. FL Studio allows users to create and edit music using a graphical user interface with a pattern-based music sequencer.
AgentExchange is Salesforce’s latest innovation, expanding upon the foundation of AppExchange by offering a centralized marketplace for AI-powered digital labor. Designed for Agentblazers, developers, and Salesforce admins, this platform enables the rapid development and deployment of AI agents across industries.
Email: [email protected]
Phone: +1(630) 349 2411
Website: https://www.fexle.com/blogs/agentexchange-an-ultimate-guide-for-salesforce-consultants-businesses/?utm_source=slideshare&utm_medium=pptNg
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMaxim Salnikov
Imagine if apps could think, plan, and team up like humans. Welcome to the world of AI agents and agentic user interfaces (UI)! In this session, we'll explore how AI agents make decisions, collaborate with each other, and create more natural and powerful experiences for users.
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AIdanshalev
If we were building a GenAI stack today, we'd start with one question: Can your retrieval system handle multi-hop logic?
Trick question, b/c most can’t. They treat retrieval as nearest-neighbor search.
Today, we discussed scaling #GraphRAG at AWS DevOps Day, and the takeaway is clear: VectorRAG is naive, lacks domain awareness, and can’t handle full dataset retrieval.
GraphRAG builds a knowledge graph from source documents, allowing for a deeper understanding of the data + higher accuracy.
Solidworks Crack 2025 latest new + license codeaneelaramzan63
Copy & Paste On Google >>> https://dr-up-community.info/
The two main methods for installing standalone licenses of SOLIDWORKS are clean installation and parallel installation (the process is different ...
Disable your internet connection to prevent the software from performing online checks during installation
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDinusha Kumarasiri
AI is transforming APIs, enabling smarter automation, enhanced decision-making, and seamless integrations. This presentation explores key design principles for AI-infused APIs on Azure, covering performance optimization, security best practices, scalability strategies, and responsible AI governance. Learn how to leverage Azure API Management, machine learning models, and cloud-native architectures to build robust, efficient, and intelligent API solutions
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?steaveroggers
Migrating from Lotus Notes to Outlook can be a complex and time-consuming task, especially when dealing with large volumes of NSF emails. This presentation provides a complete guide on how to batch export Lotus Notes NSF emails to Outlook PST format quickly and securely. It highlights the challenges of manual methods, the benefits of using an automated tool, and introduces eSoftTools NSF to PST Converter Software — a reliable solution designed to handle bulk email migrations efficiently. Learn about the software’s key features, step-by-step export process, system requirements, and how it ensures 100% data accuracy and folder structure preservation during migration. Make your email transition smoother, safer, and faster with the right approach.
Read More:- https://www.esofttools.com/nsf-to-pst-converter.html
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...Andre Hora
Unittest and pytest are the most popular testing frameworks in Python. Overall, pytest provides some advantages, including simpler assertion, reuse of fixtures, and interoperability. Due to such benefits, multiple projects in the Python ecosystem have migrated from unittest to pytest. To facilitate the migration, pytest can also run unittest tests, thus, the migration can happen gradually over time. However, the migration can be timeconsuming and take a long time to conclude. In this context, projects would benefit from automated solutions to support the migration process. In this paper, we propose TestMigrationsInPy, a dataset of test migrations from unittest to pytest. TestMigrationsInPy contains 923 real-world migrations performed by developers. Future research proposing novel solutions to migrate frameworks in Python can rely on TestMigrationsInPy as a ground truth. Moreover, as TestMigrationsInPy includes information about the migration type (e.g., changes in assertions or fixtures), our dataset enables novel solutions to be verified effectively, for instance, from simpler assertion migrations to more complex fixture migrations. TestMigrationsInPy is publicly available at: https://github.com/altinoalvesjunior/TestMigrationsInPy.
Secure Test Infrastructure: The Backbone of Trustworthy Software DevelopmentShubham Joshi
A secure test infrastructure ensures that the testing process doesn’t become a gateway for vulnerabilities. By protecting test environments, data, and access points, organizations can confidently develop and deploy software without compromising user privacy or system integrity.
Avast Premium Security Crack FREE Latest Version 2025mu394968
🌍📱👉COPY LINK & PASTE ON GOOGLE https://dr-kain-geera.info/👈🌍
Avast Premium Security is a paid subscription service that provides comprehensive online security and privacy protection for multiple devices. It includes features like antivirus, firewall, ransomware protection, and website scanning, all designed to safeguard against a wide range of online threats, according to Avast.
Key features of Avast Premium Security:
Antivirus: Protects against viruses, malware, and other malicious software, according to Avast.
Firewall: Controls network traffic and blocks unauthorized access to your devices, as noted by All About Cookies.
Ransomware protection: Helps prevent ransomware attacks, which can encrypt your files and hold them hostage.
Website scanning: Checks websites for malicious content before you visit them, according to Avast.
Email Guardian: Scans your emails for suspicious attachments and phishing attempts.
Multi-device protection: Covers up to 10 devices, including Windows, Mac, Android, and iOS, as stated by 2GO Software.
Privacy features: Helps protect your personal data and online privacy.
In essence, Avast Premium Security provides a robust suite of tools to keep your devices and online activity safe and secure, according to Avast.
Exploring Wayland: A Modern Display Server for the FutureICS
Wayland is revolutionizing the way we interact with graphical interfaces, offering a modern alternative to the X Window System. In this webinar, we’ll delve into the architecture and benefits of Wayland, including its streamlined design, enhanced performance, and improved security features.
⭕️➡️ FOR DOWNLOAD LINK : http://drfiles.net/ ⬅️⭕️
Maxon Cinema 4D 2025 is the latest version of the Maxon's 3D software, released in September 2024, and it builds upon previous versions with new tools for procedural modeling and animation, as well as enhancements to particle, Pyro, and rigid body simulations. CG Channel also mentions that Cinema 4D 2025.2, released in April 2025, focuses on spline tools and unified simulation enhancements.
Key improvements and features of Cinema 4D 2025 include:
Procedural Modeling: New tools and workflows for creating models procedurally, including fabric weave and constellation generators.
Procedural Animation: Field Driver tag for procedural animation.
Simulation Enhancements: Improved particle, Pyro, and rigid body simulations.
Spline Tools: Enhanced spline tools for motion graphics and animation, including spline modifiers from Rocket Lasso now included for all subscribers.
Unified Simulation & Particles: Refined physics-based effects and improved particle systems.
Boolean System: Modernized boolean system for precise 3D modeling.
Particle Node Modifier: New particle node modifier for creating particle scenes.
Learning Panel: Intuitive learning panel for new users.
Redshift Integration: Maxon now includes access to the full power of Redshift rendering for all new subscriptions.
In essence, Cinema 4D 2025 is a major update that provides artists with more powerful tools and workflows for creating 3D content, particularly in the fields of motion graphics, VFX, and visualization.
2. OVERVIEW• Introduction
• Syntax
• Types and objects
• Operators and expressions
• Structure and control flow
• Functions and functional programming
• Classes and OOP
• Modules, packages, and distribution
• Input and output
• Execution environment
• Testing, debugging, profiling and tuning
4. PYTHON INTERPRETER
PythonCPython
Jython
Python for .NET
IronPython
PyPy
Python is defined “by
implementation”. CPython is
default Python.
CPython is a bytecode interpreter.
It has a foreign function interface
with several languages including C,
in which one must explicitly write
bindings in a language other than
Python.
5. DATA MODEL
Type hierarchy
None
NotImplemented
Ellipsis
Numbers
numbers.Integral
Plain integers
Long integers
Booleans
numbers.Real
numbers.Complex
Sequences
Immutable
Mutable
Strings
Unicode
Tuples
Lists
Byte arrays
Sets
Mutable
Immutable
Set
Frozen setMappingsDictionaries
Callable
User defined functions
User defined methods
Generator functions
Built-in functions
Built-in methods
Class types
Classic classes
Class instances
Modules
ClassesClass instances
Files
Internal types
Code objects
Frame objects
Traceback objects
Slice objects
Static method objects
Class method objects
6. OPERATIONS
Operations
Numeric
Integer
int
Boolean subtype
32 bits+
Unlimited precision long
Operations
x | y
x ^ y
x & y
x << n
x >> n
~x
x + y
x - y
x * y
x // y
x % y
-x
+x
abs(x)
int(x)
long(x)
complex(re, im)
z.conjugate()
divmod(x, y)
power
pow(x, y)
x ** y
complex
z.real
z.imag
Additional methods
numbers.Real
math.trunc()
round(x[, n])
math.floor(x)
math.ceil(x)
For floats only
float.as_integer_ratio()
float.is_integer()
float.hex()
float.fromhex()
numbers.Integral
int.bit_length()
long.bit_length()
Sequence
x in s
x not in s
s + t
s * n, n * s
s[i]
s[i:j]
s[i:j:k]
len(s)
min(s)
max(s)
s.index(i)
s.count(i)
7. COMPARISONS
Truth value testing
True False
Zero
0
0L
0.0
0j
Empty sequence
''
()
[]
Empty mapping {}
User defined classes
__nonzero__()
__len__()
None
Boolean operations
and
or
not
Comparisons
Sequence types
in
not in
Class instances__cmp__() All objects
<
<=
>
>=
==
!=
Object identity
is
is not
8. BUILT-IN FUNCTIONS
• Refrain from using names that hide built in functions. Common errors: id,
min, max.
• If you are using vim add to your .vimrc:
let python_highlight_builtins=1
9. LISTS ANDTUPLES
>>> a = [66.25, 333, 333, 1, 1234.5]
>>> print a.count(333), a.count(66.25), a.count('x')
2 1 0
>>> a.insert(2, -1)
>>> a.append(333)
>>> a
[66.25, 333, -1, 333, 1, 1234.5, 333]
>>> a.remove(333)
>>> a
[66.25, -1, 333, 1, 1234.5, 333]
>>> a.reverse()
>>> a
[333, 1234.5, 1, 333, -1, 66.25]
>>> a.sort()
>>> a
[-1, 1, 66.25, 333, 333, 1234.5]
>>> squares = []
>>> for x in range(10):
... squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> squares = [x**2 for x in range(10)]
>>>
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
>>> combs = []
>>> for x in [1,2,3]:
... for y in [3,1,4]:
... if x != y:
... combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # Tuples may be nested:
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
>>> # Tuples are immutable:
... t[0] = 88888
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> # but they can contain mutable objects:
... v = ([1, 2, 3], [3, 2, 1])
>>> v
([1, 2, 3], [3, 2, 1])
List comprehension!
>>> import itertools
>>> import pprint
>>> pprint.pprint(list(itertools.permutations("spam")))
10. SETS
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> fruit = set(basket) # create a set without duplicates
>>> fruit
set(['orange', 'pear', 'apple', 'banana'])
>>> 'orange' in fruit # fast membership testing
True
>>> 'crabgrass' in fruit
False
>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
set(['a', 'r', 'b', 'c', 'd'])
>>> a - b # letters in a but not in b
set(['r', 'd', 'b'])
>>> a | b # letters in either a or b
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
>>> a & b # letters in both a and b
set(['a', 'c'])
>>> a ^ b # letters in a or b but not both
set(['r', 'd', 'b', 'm', 'z', 'l'])
>>> # Similarly to list comprehensions, set comprehensions are also supported:
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
set(['r', 'd'])
11. DICTIONARIES
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'guido': 4127, 'irv': 4127, 'jack': 4098}
>>> tel.keys()
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido': 4127}
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
• Everything in Python is built with dictionaries: class properties, methods,
imports...
• If order is important there is ordered dictionary: OrderedDict.
Dictionary
comprehension
12. LOOPINGTECHNIQUES
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print i, v
...
0 tic
1 tac
2 toe
>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
... print 'What is your {0}? It is {1}.'.format(q, a)
...
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
>>> for i in reversed(xrange(1,10,2)):
... print i,
...
9 7 5 3 1
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
... print f
...
apple
banana
orange
pear
13. GENERATORS
l = [1, 2, 3, 4, 5]
d = (str(x) for x in l if x % 2 == 0)
>>> <generator object <genexpr> at 0x106708410>
tuple(d)
>>> ('2', '4')
d
>>> <generator object <genexpr> at 0x106708410>
tuple(d)
>>>()
# Sum up the bytes transferred in an Apache server log using
# generator expressions
wwwlog = open("access-log")
bytecolumn = (line.rsplit(None,1)[1] for line in wwwlog)
bytes = (int(x) for x in bytecolumn if x != '-')
print "Total", sum(bytes)
def countdown(n):
print "Counting down from", n
while n > 0:
yield n
n -= 1
print "Done counting down"
for i in countdown(10):
print i
14. COROUTINES
def grep(pattern):
print "Looking for %s" % pattern
while True:
line = (yield)
if pattern in line:
print line,
g = grep("python")
g.next()
g.send("Yeah, but no, but yeah, but no")
g.send("A series of tubes")
g.send("python generators rock!")
15. NAMESPACES AND SCOPES
Namespace
Maps names to objects
Implemented as dictionaries
Examples
Built in names
Global names in a module
Local names in a function invocation
No relation between names in different
modules
Lifetime
Built in when Python starts (also called
__builtin__ module)
Global for a module when definition is read in
Local when the function is called, deleted
when function returns
Scope
Textual region of a Python program where a
namespace is directly accessible
Determined statically, used dynamically
What?
During execution, there are at least three
nested scopes:
Innermost scope, contains local names
Scopes of any enclosing functions
Current module's global names
Built in names
Assignments to names always go into the
innermost scope
What?
The global scope of a function defined in a
module is that module’s namespace, no
matter from where or by what alias the
function is called
Class definitions place yet another
namespace in the local scope.
#!/usr/bin/python
def multiply_b_f(value):
def multiply_by(x):
return x * value
return multiply_by
# Lexical scoping.
my_func = multiply_b_f(2)
value = 3
print my_func(10)
>>>
20
16. CLASSES
class Mapping:
def __init__(self, iterable):
self.items_list = []
self.__update(iterable)
def update(self, iterable):
for item in iterable:
self.items_list.append(item)
__update = update # Private copy of original update() method.
class MappingSubclass(Mapping):
def update(self, keys, values):
# provides new signature for update()
# but does not break __init__()
for item in zip(keys, values):
self.items_list.append(item)
class B:
pass
class C(B):
pass
class D(C):
pass
for c in [B, C, D]:
try:
raise c()
except D:
print "D"
except C:
print "C"
except B:
print "B"
>>> class Complex:
... def __init__(self, realpart, imagpart):
... self.r = realpart
... self.i = imagpart
...
>>> x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5)
• Data attributes override method attributes
with the same name.
• Passing an object is cheap since only a
pointer is passed by the implementation; and
if a function modifies an object passed as an
argument, the caller will see the change.
class Foo(object):
# Class variable.
DUMMY = 1
def bar(self):
return self.DUMMY + 1
def baz(self, new_value):
self.DUMMY = new_value
a = Foo()
b = Foo()
b.baz(2)
# Which one fails?
assert Foo.DUMMY == a.DUMMY
assert Foo.DUMMY == b.DUMMY
# A: self.__class__.DUMMY
17. GENERATORVS. ITERATOR
• Generators and iterators work the same.
• But not in multithreaded environment!
Think about counters:
• You cannot call a generator that is
already executing.
• You can lock protect iterator state and
call it many times concurrently.
def squares(start, stop):
"""Generator."""
for i in xrange(start, stop):
yield i * i
class Squares(object):
"""Iterator."""
def __init__(self, start, stop):
self.start = start
self.stop = stop
def __iter__(self):
return self
def next(self):
# Lock here.
if self.start >= self.stop:
raise StopIteration
current = self.start * self.start
self.start += 1
return current
for i in squares(1, 5):
print i,
# Inline generator:
for i in (i*i for i in xrange(1, 5)):
print i,
sq_range = Squares(1, 5)
for i in sq_range:
print i,
>>> 1 4 9 16
18. FUNCTION ARGUMENTS
• Never use keyword argument for a function that doesn't explicitly define
one. If you do that you’ve introduced a global variable!
• In your tests use the function call the same way you use it in production
code: it can catch these bugs.
def foo(x, y):
print x ** y
foo(2, 3)
foo(2, y=3)
foo(x=2, y=3)
def foo(base, exponent):
print base ** exponent
foo(x=2, y=3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() got an unexpected keyword argument 'x'
19. CONTEXT MANAGERS
import sys
from StringIO import StringIO
class redirect_stdout:
def __init__(self, target):
# Save stdout and target.
self.stdout = sys.stdout
self.target = target
# Do this before.
def __enter__(self):
# Replace stdout with target.
sys.stdout = self.target
# Do this after.
def __exit__(self, type, value, tb):
# Restore stdout.
sys.stdout = self.stdout
out = StringIO()
with redirect_stdout(out):
# Print goes to StringIO object now!
print 'Test'
# Verify:
>>> out.getvalue() == 'Testn'
True
f = open("hello.txt")
try:
for line in f:
print line,
finally:
f.close()
with open("hello.txt") as f:
for line in f:
print line,
• __enter__() defines what the context manager should do at
the beginning of the block created by the with statement. Note
that the return value of __enter__ is bound to the target of the
with statement, or the name after the as.
• __exit__(self, exception_type,
exception_value, traceback) defines what the context
manager should do after its block has been executed (or
terminates).
• __enter__ and __exit__ can be useful for specific classes
that have well-defined and common behavior for setup and
cleanup.
20. DECORATORS
• Decorator expressions are
evaluated when the function is
defined, in the scope that contains
the function definition.
• The result must be a callable, which
is invoked with the function object
as the only argument.
• The returned value is bound to the
function name instead of the
function object. Multiple decorators
are applied in nested fashion.
import time
def timeit(func):
"""Decorator for measuring function run time.
Args:
func: Function to be wrapped, passed implicitly
through "@..."
call.
Returns:
Wrapped function.
"""
def function_call_wrap(*args, **kwargs):
try:
start_time = time.time()
return func(*args, **kwargs)
finally:
logger_func("%s() took %fms.", func.func_name,
(time.time() - start_time) * 1000)
return function_call_wrap
def sleep1():
time.sleep(1)
@timeit
def sleep2():
time.sleep(2)
21. RUNVS. IMPORT
• Module imports trigger __init__.py execution. Imports are
actually running a code.
• Running a code from the same folder would not see it as a module
and __init__.py wouldn’t run! Read an explanation at
http://stackoverflow.com/a/465129.
• Stay on the safe side: know what you are initializing.
• from foo import bar — considered harmful.
22. MODULES AND EXCEPTIONS
• Modules or packages should define their own domain-specific base exception
class, which should be subclassed from the built-in Exception class.
• “Modules should have short, all-lowercase names.” (Though there are historical
exceptions: StringIO.)
• Module level exceptions enable catching all errors that can be raised by one
module only.Very useful for debugging and testing.
class Error(Exception):
"""Base class for exceptions in this module."""
class RedisLockError(Error):
"""Base class for lock exceptions."""
23. EXCEPTION CATCHING
• When catching exceptions, mention
specific exceptions whenever possible
instead of using a bare except: clause.
• If you want to catch all exceptions that
signal program errors, use except
Exception:(bare except is equivalent
to except BaseException:).
try:
do_something()
except:
# Diaper pattern.
print "Error"
24. def convert_to_named_tuple(original_class):
"""Replace class declaration with named tuple.
This decorator is to be used when one uses class for storing
constants.
Note: this will work only for classes with constants, not with any
other declared methods.
Example usage::
@convert_to_named_tuple
class important_constants(object):
PI = 3.141
e = 2.718
print important_constants.PI # Prints 3.141
important_constants.PI = 2 # Raises exception!
Args:
original_class: A class declaration.
Returns:
Named tuple object in place of the decorated class.
"""
@wraps(original_class)
def replace_class_with_named_tuple():
constant_value_dict = dict()
for attribute in original_class.__dict__:
if not attribute.startswith("__"):
constant_value_dict[attribute] = (
original_class.__dict__[attribute])
replacement_tuple = namedtuple(
original_class.__class__.__name__,
" ".join(constant_value_dict.iterkeys()))
args = constant_value_dict.values()
return replacement_tuple(*args)
return replace_class_with_named_tuple()
DOCUMENTATION
• PEP-257 talks about docstring
conventions.
• “Comments that contradict the code are
worse than no comments.Always make a
priority of keeping the comments up-to-
date when the code changes!”
• pydoc -p <port>: See all modules
in production. Use it as a local Python
library reference.
25. ARGPARSE
parser = argparse.ArgumentParser(
prog="smm",
description="Management")
parser.add_argument(
"--version",
action="version",
version="%(prog)s 0.1")
parser.add_argument(
"--log",
action="store",
choices=("debug", "info", "warning", "error", "critical"),
default="warning")
# Default arguments for each subparser: add/rm/list.
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument(
"-l", "--labels",
required=True,
type=labels.valid_label_pair,
nargs="+",
metavar=("label1=value1", "label2=value2"),
help="labels as 'key=value' pairs")
parent_parser.add_argument(
"-m", "--machines",
required=True,
type=machines.valid_machine_name,
nargs="+",
metavar=("machine_1", "machine_2"),
help="machine names")
parent_parser.add_argument(
"--log",
action="store",
choices=("debug", "info", "warning", "error", "critical"),
default="warning")
# Subparsers for add, rm, and list inherit the same
subparsers = parser.add_subparsers(
title="subcommands",
description="valid subcommands",
dest="subparser_name",
help="sub-commands")
parser_add = subparsers.add_parser(
"add",
parents=[parent_parser],
help="add labels to machines")
parser_add.add_argument(
"add",
help="add labels",
action="store_true")
parser_add.set_defaults(func=add_machines)
#...
def main():
args = parser.parse_args()
logger.initialize_logger(args.log)
logger.LOG.debug("Parsed command line and initialized logger.")
logger.LOG.debug("Command line parsed: %s", args)
logger.LOG.debug("Dispatching:")
args.func(args)
logger.LOG.debug("Done!")
Try not to use optparse
module, it is deprecated.
26. GFLAGS
• Google’s command line parsing library:
http://code.google.com/p/python-gflags/
• It has increased flexibility, including built-in support for Python
types, and the ability to define flags in the source file in which
they're used (major difference from OptParse).
FLAGS = gflags.FLAGS
gflags.DEFINE_integer(
"port",
9001,
"service port")
gflags.RegisterValidator(
"port",
lambda port: 1024 < port <= 65535,
message="must be in (1024, 65535] range")
def main(argv)
port = FLAGS.port
27. PEP8
• Python Style Checker: python.org/dev/peps/pep-0008/
• Read it, and then read it again. It will teach you to write better and
more reliable Python code.Add comments, be verbose, keep it clean.
• “Code should be written to minimize the time it would take for someone
else to understand it.” — “The Art of Readable Code”, Dustin Boswell,
Trevor Foucher.
• New code should (must) have test coverage. Use asserts.They will be
completely ignored when the code is run in optimized mode (python
-O).
28. PEP-8 ON IMPORTS
• Always use the absolute package path for all imports. Even now that PEP-328
(“Imports: Multi-Line and Absolute/Relative”) is fully implemented in Python
2.5, its style of explicit relative imports is actively discouraged; absolute
imports are more portable and usually more readable.
• Imports are always put at the top of the file, just after any module comments
and docstrings, and before module globals and constants. Imports should be
grouped in the following order:
1. Standard library imports
2. Related third party imports
3. Local application/library specific imports
• You should put a blank line between each group of imports.
29. “IS NONE”VS.“== NONE”
• PEP 8 says: Comparisons to singletons like None
should always be done with is or is not, never
the equality operators (==, !=).
• Beware of writing if x when you really mean if
x is not None — e.g. when testing whether a
variable or argument that defaults to None was set
to some other value.The other value might have a
type (such as a container) that could be false in a
boolean context! A class is free to implement
comparison any way it chooses, and it can choose
to make comparison against None mean something
• Use x is not y instead of not x is y.
Operator priority can be confusing and the second
statement can be read as (not x) is y.
class Zero():
"""A class that is zero."""
def __nonzero__(self):
return False
class Len0():
"""A class with zero length."""
def __len__(self):
return 0
class Equal():
"""A class that is equal to everything."""
def __eq__(self, other):
return True
stuff = [None, False, 0, 0L, 0.0, 0j,
(), [], {}, set(), '', float('NaN'), float('inf'),
Zero(), Len0(), Equal()]
for x in stuff:
if x is None:
print("{} is None ".format(x))
if x==None:
print("{} == None ".format(x))
>>>
None is None
None == None
<__main__.Equal instance at 0x84a80> == None
30. __DEL__ AND MEMORY
class SomeClass(object):
pass
class SomeNastyClass(object):
# Confuse garbage collection by adding __del__ method. If
# circular reference is created it wouldn't know which one to
# dispose of first and would let them stay in memory!
def __del__(self):
pass
def non_leaky_function():
"""Non leaky function."""
foo = SomeClass()
bar = SomeClass()
foo.other = bar
bar.other = foo
del foo
del bar
return
def leaky_function():
"""Leaky function."""
foo = SomeNastyClass()
bar = SomeNastyClass()
foo.other = bar
bar.other = foo
del foo
del bar
return
def log_memory_leaks(func, logger_func):
"""Decorator for detecting memory leaks.
Log what was not garbage collected after the function has returned.
Args:
func: Function to be wrapped, passed implicitly through "@..." call.
logger_func: Logging function to be called around the wrapped function.
Returns:
Wrapped function.
"""
@wraps(func)
def function_call_wrap(*args, **kwargs):
# Force garbage collection.
gc.collect()
# Different type instance counters before and after the function run.
before = Counter([type(i) for i in gc.get_objects()])
try:
return func(*args, **kwargs)
finally:
gc.collect()
# Count instances by type after the run. Ignore object "before"
# created in this decorator.
after = Counter(
[type(i) for i in gc.get_objects() if i is not before])
# Find instance types that have changed after the run.
instance_diff = {
i: after[i] - before[i] for i in after if after[i] != before[i]}
if instance_diff:
logger_func(
"Memory usage after %s(args=%s, kwargs=%s): %s",
func.func_name, args, kwargs, pprint.pformat(instance_diff))
return function_call_wrap
Usecontextmanager:“with
...
:”
31. WHYTEST
• No standard scoping: once a variable has come into existence it remains
until the enclosing function exits and not when the enclosing block
terminates.
• No concept of data privacy, only obfuscation.
• No concept of declaration leads to ambiguity when you have multiple
scopes. Instead of having one simple var keyword, Python has the global
and nonlocal keywords (the latter is only available in Python 3).
• More errors are detected at run time than is desirable. Basically you have
to make sure that all your code has been executed before you can say that
the program is even semantically correct.
• Your friend: https://nose.readthedocs.org/en/latest/
33. package main
import (
"fmt"
"runtime"
)
func summer(ch chan<- uint64, from uint64, to uint64) {
var sum uint64 = 0
for i := from; i <= to; i++ {
sum += i
}
// Send the result.
ch <- sum
}
func main() {
const upper uint64 = 1000000000
const workers uint64 = 8
var start_interval uint64 = 1
const step uint64 = upper / workers
// Make a channel that can buffer up to $workers numbers.
ch := make(chan uint64, workers)
// Use up to 8 CPUs. This should nicely use quad core CPU with
// hyperthreading.
runtime.GOMAXPROCS(8)
// Dispatch workers, each with a different number segment.
for i := uint64(0); i < workers; i++ {
go summer(ch, start_interval, start_interval+step-1)
start_interval += step
}
// Read out results as they keep arriving to the channel (we block on the
// channel until a value is ready).
var sum uint64 = 0
for i := uint64(0); i < workers; i++ {
sum += <-ch
}
fmt.Println(sum)
}
>
real 0m0.302s
user 0m2.165s
sys 0m0.004s
#!/usr/bin/python
print sum(xrange(1, 1000000001))
>
real 0m12.114s
user 0m12.087s
sys 0m0.012s
#!/usr/bin/perl
use integer; $sum = 0; $sum += $_ for (1 .. 1000000000); print $sum;
>
real 1m21.774s
user 1m21.656s
sys 0m0.061s
#include "stdio.h"
int main(int argc, char const *argv[]) {
long sum = 0;
for (long i = 1; i <= 1000000000L; sum+=i++)
;
printf("%ldn", sum);
return 0;
}
>
real 0m2.465s
user 0m2.461s
sys 0m0.002s
109
X
i=1
i = 500000000500000000
EXAMPLE: SUM
34. PARALLELIZE SUM!
#!/usr/bin/python
import multiprocessing
UPPER = 1000000000
WORKERS = 8
STEP = UPPER / WORKERS
pool = multiprocessing.Pool(processes=WORKERS)
ranges = (xrange(lo, hi + 1) for (lo, hi) in zip(xrange(1, UPPER, STEP),
xrange(STEP, UPPER + 1, STEP)))
print sum(pool.map(sum, ranges))
>
real 0m2.008s
user 0m13.991s
sys 0m0.051s
From 12 to 2 seconds.
35. FIBONACCI NUMBERS
f(n) =
8
><
>:
0 n = 0
1 n = 1
f(n 1) + f(n 2) otherwise
#!/usr/bin/python
from timeit import timeit
def fib(n):
assert n >= 0
if n == 0:
return 0
if n == 1:
return 1
return fib(n-1) + fib(n-2)
print(timeit(
stmt="fib(30)",
setup="from __main__ import fib",
number=1))
$ python3.3 fib.py
0.8095278141554445
#!/usr/bin/python
import time
def timeit(func):
def function_call_wrap(*args, **kwargs):
try:
start_time = time.time()
return func(*args, **kwargs)
finally:
print(time.time() - start_time)
return function_call_wrap
def fib(n):
assert n >= 0
if n == 0:
return 0
if n == 1:
return 1
return fib(n-1) + fib(n-2)
@timeit
def fib30():
fib(30)
fib30()
python3.3 fib.py
0.794215202331543
#!/usr/bin/python
from timeit import timeit
from functools import lru_cache
@lru_cache(maxsize=512)
def fib(n):
assert n >= 0
if n == 0:
return 0
if n == 1:
return 1
return fib(n-1) + fib(n-2)
print(timeit(
stmt="fib(30)",
setup="from __main__ import fib",
number=1))
$python3.3 fib.py
0.0003443881869316101
f(30) = 832040
37. CRITICISM
• Python is highly typed. Do you get function overloading based upon parameter type? No.
Can you stipulate the type of a parameter in a function declaration? No, this has to be
coded within the function.
• Mutable default arguments (def foo(a=”abc”, b=[])).
• Documentation is generally good, but quite often it doesn’t go into enough detail.
• It is deceptively easy to start with, but to write serious code you have to know hidden stuff.
• All function arguments are essentially global variables! If you rename them you can break
some code! Partially fixed in Python 3+.
• White space complicates refactoring.
• Anonymous or lambda functions are limited in their ability. However one can declare a
named function in an inner scope and use that instead.
38. GIL
• GIL, is a mutex that prevents multiple native threads from executing Python bytecodes at once.
This lock is necessary mainly because CPython's memory management is not thread-safe.
However, since the GIL exists, other features have grown to depend on the guarantees that it
enforces.
• It prevents multithreaded CPython programs from taking full advantage of multiprocessor systems.
39. 2.X OR 3.X
$ python
Python 2.7.2 (default, Oct 11 2012, 20:14:37)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 3/2
1
>>> ^D
$ python3.3
Python 3.3.1 (v3.3.1:d9893d13c628, Apr 6 2013, 11:07:11)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 3/2
1.5
>>> ^D
• Some libraries are still not ported to 3.X
• 2.7.X is the last 2.X version
• New features are added to 3.X, it is a better language.
• http://wiki.python.org/moin/Python2orPython3
40. GOODTO KNOW
• #!env python — it can mask the process name.You wouldn’t see
the name of the code running when listing processes on a machine.
• Unicode vs. normal strings: size difference exists for ASCII characters
as well. u“Aleksa” takes twice the size of “Aleksa” (or even four times!).
Differences in 2.X and 3.X.
• In all python projects you do not cd into a lower directory to run
things.You stay at the top and run everything from there so that all of
the system can access all the modules and files.
• http://www.aleksa.org/2013/03/python-resources.html