text
stringlengths
20
1.01M
url
stringlengths
14
1.25k
dump
stringlengths
9
15
lang
stringclasses
4 values
source
stringclasses
4 values
people = {} def add puts "Enter the name of the person you would like to add in the database." name = gets.chomp.to_s if people[name].nil? puts "What is #{name}'s age?" age = gets.chomp.to_i people[name] = age.to_i end puts "Would you like to add?" choice = gets.chomp if choice == "yes" add end end Global variables should be prefixed by $ in Ruby, so you need $people in place of people. Alternatively, you can pass in people to your add function.
https://codedump.io/share/WMlJC6QER3ua/1/how-do-i-call-a-variable-to-a-method-in-ruby-not-rails
CC-MAIN-2017-13
en
refinedweb
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. [V8] Need help to understand old api computed field Hi ! Here is an old api code from the sale_margin module: class sale_order(osv.osv): _inherit = "sale.order" def _product_margin(self, cr, uid, ids, field_name, arg, context=None): result = {} for sale in self.browse(cr, uid, ids, context=context): result[sale.id] = 0.0 for line in sale.order_line: if line.state == 'cancel': continue result[sale.id] += line.margin or 0.0 return result def _get_order(self, cr, uid, ids, context=None): result = {} for line in self.pool.get('sale.order.line').browse(cr, uid, ids, context=context): result[line.order_id.id] = True return result.keys() _columns = { 'margin': fields.function(_product_margin, string='Margin', help="It gives profitability by calculating the difference between the Unit Price and the cost price.", store={ 'sale.order.line': (_get_order, ['margin', 'purchase_price', 'order_id'], 20), 'sale.order': (lambda self, cr, uid, ids, c={}: ids, ['order_line'], 20), }, digits_compute= dp.get_precision('Product Price')), } I just can't understand what the code in bold means. Could someone explain what it does imply ? Is it just storing the computed field inside the db ? And why a store=True kwarg wouldn't be sufficient ? For various reasons, I need to override the margin computed field. How can I do it since it seems to be quite special case? Hello, The bold lines determines when the computes field will be recalculated, it is some how equivalent to @api.depends in the new API. 'sale.order.line': (_get_order, ['margin', 'purchase_price', 'order_id'], 20), Means: if the ids got by _get_order of 'sale.order.line' recorded changes in : 'margin', 'purchase_price', and 'order_id' Then recompute the field. 'sale.order': (lambda self, cr, uid, ids, c={}: ids, ['order_line'], 20) Means: if this sale order changed the 'order_line' then recompute this field. - and It uses like this to enhance the performance ... [if the store = false: it will always be recomputed when it visible, and if the store = True: it will computed just for the first time]. Hope this could helps a little bit ... Hi thanks for your answer, I understand a little bit more right now. But my problem is the fact that ovewriting the field in an other module produces a strange bug ('undefined get method'). I don't know how to do it properly. can you paste some of your code ? Dear Ahmed many thanks for your help. Thanks to this issue on Github, I could understand that what I wanted to achieve is properly impossible. I did it in another way, reimplementing my own margin. mistake in the issue URL : Dear Rivet, happy that you managed to resolve it :) About This Community Odoo Training Center Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now
https://www.odoo.com/forum/help-1/question/v8-need-help-to-understand-old-api-computed-field-105091
CC-MAIN-2017-13
en
refinedweb
- : BreakIterator The java.text.BreakIterator class is used to find character, word and sentence boundaries across different languages. Since different languages use different character, word and sentence boundaries, it is not enough just to search for space, comma, fullstop, semicolon, colon etc. You need a foolproof way to search for these boundaries in different languages. The BreakIterator class provides that. Creating a BreakIterator A single BreakIterator instance can only detect one of the following types of boundaries: - Character boundaries - Word boundaries - Sentence boundaries - Line boundaries You create an instance that can recognize one of the above boundaries using the corresponding factory method in the BreakIterator class. The factory methods are: BreakIterator.getCharacterInstance(); BreakIterator.getWordInstance(); BreakIterator.getSentenceInstance(); BreakIterator.getLineInstance(); Each of these methods take a Locale as parameter, and returns a BreakIterator instance. Here is a simple example: Locale locale = LocaleUK; BreakIterator breakIterator = BreakIterator.characterInstance(locale); Character Boundaries When searching for character boundaries it is necessary to make a distinction between user characters and unicode characters. A user character is the character a user would write if they use a pen. User characters are also typically what the user sees on the screen. It may require one or more unicode characters to represent a user character. Some user characters are represented by 2 or more unicode characters. A character instance of the BreakIterator class finds character boundaries for user characters, not unicode characters. Here is a simple example that finds character boundaries in a string: Locale locale = Locale.UK; BreakIterator breakIterator = BreakIterator.getCharacterInstance(locale); breakIterator.setText("Mary had a little Android device."); int boundaryIndex = breakIterator.first(); while(boundaryIndex != BreakIterator.DONE) { System.out.println(boundaryIndex) ; boundaryIndex = breakIterator.next(); } This example creates a BreakIterator targeted at the British language, and sets the text to find character breaks in using the setText() method. The method first() returns the first found break. The method finds all subsequent breaks. Both methods return the unicode character index of the found user character. Thus, if a user character takes up more than one unicode character, the character indexes will increase with the number of unicode characters the user takes. Word Boundaries When finding word boundaries you need to create a BreakIterator that is capable of finding word boundaries for the specific language needed. Here is how you do that: Locale locale = Locale.UK; BreakIterator breakIterator = BreakIterator.getWordInstance(locale); This code creates a BreakIterator instance that can find word boundaries in UK english texts. Here is an example that finds word boundaries in an english text: Locale locale = Locale.UK; BreakIterator breakIterator = BreakIterator.getWordInstance(locale); breakIterator.setText("Mary had a little Android device."); int boundaryIndex = breakIterator.first(); while(boundaryIndex != BreakIterator.DONE) { System.out.println(boundaryIndex) ; boundaryIndex = breakIterator.next(); } Again, here the first() and next() methods return the unicode index of the found word boundary. Counting Words in a Specific Language in Java Here is a Java code example that shows how to count the occurrences of the words in a given string, according to the rules of a specific Locale: public class WordCounter { public static class WordCount { protected String word = null; protected int count = 0; } public static Map<String, WordCount> countWords(String text, Locale locale) { Map<String, WordCount> wordCounts = new HashMap<String, WordCount>(); BreakIterator breakIterator = BreakIterator.getWordInstance(locale) ; breakIterator.setText(text); int wordBoundaryIndex = breakIterator.first(); int prevIndex = 0; while(wordBoundaryIndex != BreakIterator.DONE){ String word = text.substring(prevIndex, wordBoundaryIndex).toLowerCase(); if(isWord(word)) { WordCount wordCount = wordCounts.get(word); if(wordCount == null) { wordCount = new WordCount(); wordCount.word = word; } wordCount.count++; wordCounts.put(word, wordCount); } prevIndex = wordBoundaryIndex; wordBoundaryIndex = breakIterator.next(); } return wordCounts; } private static boolean isWord(String word) { if(word.length() == 1){ return Character.isLetterOrDigit(word.charAt(0)); } return !"".equals(word.trim()); } } The countWords() method takes a string and a Locale. The Locale represents the language of the string. Thus, when a BreakIterator is created, it can be created for that specific language. The method counts how many times each word occurs in the string, and returns that as a Map<String, WordCount>. The keys in the map are the individuals words in lowercase. The value for each key is a WordCount instance, which contains two variables: The word and the count of that word. If you want the total number of words in the text, you would have to sum the counts of all individual words. Notice how the isWord() method uses the Character.isLetterOrDigit() method to determine if a character is a letter or digit, or something else (like semicolon, quote etc.). The Character.isLetterOrDigit() checks according to the unicode characters if a character is a letter or digit - and thus not just in the english language, but also in other languages. This, and similar methods are described in more detail in the Characeter Methods text. Sentence Boundaries To locate sentence boundaries you need a BreakIterator instance that is capable of finding sentence boundaries. Here is how you do that: Locale locale = Locale.UK; BreakIterator breakIterator = BreakIterator.getSentenceInstance(locale); This code creates a BreakIterator targeted at the UK english language. Here is an example that finds the sentence boundaries in an english string: Locale locale = Locale.UK; BreakIterator breakIterator = BreakIterator.getSentenceInstance(locale); breakIterator.setText( "Mary had a little Android device. " + "It had small batteries too."); int boundaryIndex = breakIterator.first(); while(boundaryIndex != BreakIterator.DONE) { System.out.println(boundaryIndex) ; boundaryIndex = breakIterator.next(); } Line Boundaries You can find breaks in a string where a line of text could be broken onto a new line without disturbing the reading of the text. To do this you need a BreakIterator capable of detecting potential line breaks. Note, that it does not find actual line breaks in the text, but potential line breaks. Finding potential line breaks is useful in text editors that need to break text onto multiple lines when displaying it, even if the text contains no explicit line breaks. Here is how you create such a BreakIterator: Locale locale = Locale.UK; BreakIterator breakIterator = BreakIterator.getLineInstance(locale); This example creates a BreakIterator capable of finding potential line breaks in UK english text. Here is an example that finds potential line breaks in a string with english text: Locale locale = Locale.UK; BreakIterator breakIterator = BreakIterator.getLineInstance(locale); breakIterator.setText( "Mary had a little Android device.\n " + "It had small batteries too."); int boundaryIndex = breakIterator.first(); while(boundaryIndex != BreakIterator.DONE) { System.out.println(boundaryIndex) ; boundaryIndex = breakIterator.next(); }
http://tutorials.jenkov.com/java-internationalization/breakiterator.html
CC-MAIN-2017-13
en
refinedweb
[Date Index] [Thread Index] [Author Index] Re: factoring On Dec 30, 10:09 am, r_poetic <radford.scha... at mms.gov> wrote: > Hello, > an easy question: > > why does Factor[xy-xz+y^2-yz] fail to return (x+y)(y-z), and what > command would do that? > > Thanks! Hi you have to put a space between variables. x y means x times y, xy means a variable with a two letters name
http://forums.wolfram.com/mathgroup/archive/2010/Dec/msg00770.html
CC-MAIN-2017-13
en
refinedweb
Generic integer x, y vector. More... #include <math/gzmath.hh> Generic integer x, y vector. Constructor. Constructor. Copy constructor. Copy constructor for ignition math. Destructor. Return the cross product of this vector and _pt. Calc distance to the given point. Convert this vector to ignition::math::Vector2i. See if a point is finite (e.g., not nan) Normalize the vector length. Equality operators. Multiplication operator. Multiplication operator. Multiplication operators. Multiplication operator. Addition operator. Addition assignment operator. Subtraction operator. Subtraction operators. Division operator. Division operator. Division operator. Division operator. Assignment operator. Assignment operator for ignition math. Assignment operator. Equality operator. Array subscript operator. Set the contents of the vector. Stream insertion operator. Stream extraction operator. x data y data
http://gazebosim.org/api/dev/classgazebo_1_1math_1_1Vector2i.html
CC-MAIN-2018-34
en
refinedweb
accessible Skip over Site Identifier Skip over Generic Navigation Skip over Search Skip over Site Explorer Site ExplorerSite Explorer Posts: 19 Rating: (3) import from Process Automation User Connection, Talk to Other Process UsersRon Martinez posted on 10/18/06:I have heard that Siemen's is no longer obsoleting the APACS DCS system. Does that indicate that the APACS system will be further developedand that there could possibly be ACM's with more memory? import from Process Automation User Connection, Talk to Other Process UsersDear Mr. Martinez,Thank you for your question and your interest in Siemens Products. Product lifecycle planning is a continuous process and Siemens is actively managing the APACS/QUADLOG product line lifecycle.You are correct in that some earlier estimates of APACS maturity have been impacted by decisions made over the past few years. Those decisionshave effectively enabled us to extend the product's lifecycle. Furthermore, our management team has directed us to plan for product availability through 2010 and longer, if possible. When I use the term "availability" I am talking about full, unrestricted sale of the product. Beyond that, after declaration of maturity,Siemens policy calls for 1 year of last time buy opportunity and then 9 additionalyears of repair and support capability forhardware products and 4 years for PC based products and software.APACS is past the point in its lifecycle that can supportnew product development but considerable resources are being dedicated to sustaining engineering and the development of new products that simplify the extension of APACS into PCS7 and the Siemens TIA (Totally Integrated Automation) concept. One such product in the pipeline is the DPI/O Bus which will allow the family of PCS7 controllers to control APACS I/O. In this way, even though no APACS controllers are planned beyond the recently released 8 MEG ACMx, there will be a path to a family of powerful new controllers.I hope this addresses your concerns. As a reminder, please note that December 30, 2006 is the end of the "last time buy" period for ProcessSuite, the old APACS/QUADLOG HMI software. PCS7 OS for APACS is the replacement and is available now.Best Regards,Russell W. FussAPACS/QUADLOG Product Manager
https://support.industry.siemens.com/tf/ww/en/posts/acm-16-meg/5705?page=0&pageSize=10
CC-MAIN-2018-34
en
refinedweb
Record the location of an inclusion directive, such as an #include or #import statement. More... #include "clang/Lex/PreprocessingRecord.h" Record the location of an inclusion directive, such as an #include or #import statement. Definition at line 208 of file PreprocessingRecord.h. The kind of inclusion directives known to the preprocessor. Definition at line 212 of file PreprocessingRecord.h. Definition at line 43 of file PreprocessingRecord.cpp. References clang::PreprocessingRecord::Allocate(), and memcpy(). Definition at line 272 of file PreprocessingRecord.h. References clang::PreprocessedEntity::getKind(), and clang::PreprocessedEntity::InclusionDirectiveKind. Retrieve the file entry for the actual file that was included by this directive. Definition at line 269 of file PreprocessingRecord.h. Retrieve the included file name as it was written in the source. Definition at line 257 of file PreprocessingRecord.h. Determine what kind of inclusion directive this is. Definition at line 254 of file PreprocessingRecord.h. Determine whether the inclusion directive was automatically turned into a module import. Definition at line 265 of file PreprocessingRecord.h. Determine whether the included file name was written in quotes; otherwise, it was written in angle brackets. Definition at line 261 of file PreprocessingRecord.h.
http://clang.llvm.org/doxygen/classclang_1_1InclusionDirective.html
CC-MAIN-2018-34
en
refinedweb
Shows protein backbone structures in compact graphical form using Ramachandran numbers Project description Contents 1 Introduction This tool provides easily readable “pictures” of protein conformations, ensembles, and trajectories saved as either a combined protein databank (PDB) structure file, or a directory of such files, and produces graphs. BackMAP helps with the visualization of large amounts of structural (space-time) backbone data in a single graph. 2 Installation 2.1 PIP Installation Running the following at a command prompt (terminal) would get the job done (the ‘-I’ is not necessary, but ensures the latest sub-version is installed): $ pip install -I backmap 2.2 GIT Installation $ git clone $ cd backmap $ python setup.py install $ python setup.py test 2.3 Manual Installation From the git repository download the zip (). At a command prompt, unzip and change directory into the extracted directory (cd ./backmap/) and perform the following commands. $ python setup.py install $ python setup.py test 3 Usage 3.1 In-script usage import backmap as bm print bm.R(phi=0,psi=0) # Should print '0.5' For more information about in-script module usage, refer to the manuscript associated with this module. 3.2 Standalone usage After installation, the following commands produce a variety of graphs (exampled below). python -m backmap -pdb ./pdbs/ProteinDatabankStructureFilename.pdb python -m backmap -pdb /directory/containing/pdbs/ 4 Examples 4.1 Example 1: A stable protein (1xqq) The Panels (b) through (f) were created by running the following command within thin the downloaded directory (Panel (a) was created using VMD). python -m backmap -pdb ./tests/pdbs/1xqq.pdb As evident below, the graphs generated from the protein ensemble 1xqq describes a conformationally stable protein (each graph is detailed below). Each column in Panel (b) describes the histogram in Ramachandran number (R) space for a single model/timeframe. These histograms show the presence of both helices (at R ~ 0.34) and sheets (at R ~ 0.52). Additionally, Panels (c) and (d) describe the per-residue conformational plots (colored by two different metrics or CMAPs), which show that most of the protein backbone remains relatively stable (e.g., few fluctuations in state or ‘color’ are evident over the frame #). Finally, Panel (e) describes the extent towards which a single residue’s state has deviated from the first frame, and Panel (f) describes the extent towards which a single residue’s state has deviated from its state in the previous frame. Both these graphs, as expected from Panels (c) and (d), show that this protein is relatively conformationally stable. 4.2 Example 2: An intrinsically disordered protein (2fft) As compared to the conformationally stable protein above, an intrinsically disordered protein 2fft is much more flexible Panel (b) shows that the states accessed per model are diverse and dramatically fluctuate over the entire range of R (this is especially true when compared to a stable protein, see above). The diverse states occupied by each residue (Panels (c) and (d)) confirm this conformational variation within most residues (Panels (e) and (f) similarly show how most of the residues fluctuate dramatically). Yet, interestingly, Panels (c) through (f) also show an unusually stable region – residues 15 through 25 – which consistently display the same conformational (alpha-helical) state at R ~ 0.33 (interpreted as the color red in Panel (c)). This trend would be hard to recognize by simply looking at the structure (Panel (a)). 5 Publications The Ramachandran number concept is discussed in the following manuscripts (this tool is discussed in the first reference): 1. Mannige (2018) “The Backmap Python Module: How a Simpler Ramachandran Number Can Simplify the Life of a Protein Simulator” Manuscript Prepared. Preprint available the manuscript/manuscript subdirectory of this repo. 2. Mannige, Kundu, Whitelam (2016) “The Ramachandran Number: An Order Parameter for Protein Geometry” PLoS ONE 11(8): e0160023. Full Text: Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/backmap/0.2.6/
CC-MAIN-2018-34
en
refinedweb
Before call either previously defined auxiliary constructor or primary constructor in the first line of its body. Hence every auxiliary constructor invokes directly or indirectly to a primary constructor. we can call the primary constructor or other auxiliary constructor using this. Here is an example, See the above code, when we create an object using zero-argument auxiliary constructor then there is the first statement this(0,””,0.0) which will call to a primary constructor. Hence first Primary constructor body will be executed then after auxiliary constructor body. we can also call directly to the primary constructor. When you compile Employee.scala using scalac Employee.scala and after convert it into java code using javap Employee.class. see the below-generated java code. Compiled from "Employee.scala" public class Employee { public Employee(int, java.lang.String, double); //java parameterized constructor. public Employee(); // java default constructor. } Now create Scala class with a primary constructor and multiple auxiliary constructors see the above output when we create an instance with the help of zero arguments auxiliary constructor. Zero argument constructor call to One argument auxiliary constructor and One argument constructor to a Primary constructor. So the primary constructor body would execute first then after one argument constructor body then after zero arguments. Now, When you invoke more than one time this in the auxiliary constructor then it will invoke apply() in the class, If an apply method does not define in the class and call more than one times this in the auxiliary constructor then it will give compile time error. In Scala, We can also create a primary constructor with a default value. If you don’t provide value then it will take default value which is provided in the Primary constructor. Otherwise the value we provide when an instance created with the help of a parameter name of the class. Here is an example, If we provide a wrong parameter name of the class at the time of instance creation then it will give the compile-time error. Please comment, if you have any doubt or suggestion. thank you 🙂 1 thought on “Auxiliary constructor in Scala”
https://blog.knoldus.com/auxiliary-constructor-in-scala?shared=email&msg=fail
CC-MAIN-2018-34
en
refinedweb
It's not the same without you Join the community to find out what other Atlassian users are discussing, debating and creating. Hi I'm trying to automatically add Request Participants to Service Desk ticket on creation. I tried both SIL script and Groovy script in post function but nothing worked. The idea is I have 3 custom fields where customer may select up to 3 approvers for the ticket and I want to be able to add them to the ticket as Request Participants. Here is what I tried. SIL version: // Add approvers to request participants string approver1 = customfield_11600; string approver2 = customfield_11601; string approver3 = customfield_11602; string[] participants; //add approver1 if (!isNull(approver1)) { participants = arrayAddElement(participants, approver1); } //add approver2 if (!isNull(approver2)) { participants = arrayAddElement(participants,approver2); } //add approver3 if (!isNull(approver3)) { participants = arrayAddElement(participants,approver3); } //set request participants if (arraySize(participants) > 0) { customfield_12800 = participants; } Groovy version (I tried adding only 1 approver in groovy version): import com.atlassian.jira.issue.MutableIssue import com.atlassian.jira.issue.IssueManager import com.atlassian.jira.issue.index.IssueIndexManager def customFieldManager = ComponentAccessor.getCustomFieldManager() def requestParticipantsField = customFieldManager.getCustomFieldObject("customfield_12800") def approver1Field = customFieldManager.getCustomFieldObject("customfield_11600") ArrayList<ApplicationUser> applicationUsers = new ArrayList<ApplicationUser>() applicationUsers.add(issue.getCustomFieldValue(approver1Field)) issue.setCustomFieldValue(requestParticipantsField, applicationUsers) Please point what I am doing wrong here. Working code example is highly appreciated. What actually worked for me is the following groovy script ArrayList allApprovers = new ArrayList(); allApprovers.add(approver1User); allApprovers.add(approver2User); allApprovers.add(approver3User); def customFieldManager = ComponentAccessor.getCustomFieldManager(); def changeHolder = new DefaultIssueChangeHolder(); def requestParticipantsField = customFieldManager.getCustomFieldObjects(issue).find {it.name == 'Request participants'}; requestParticipantsField.updateValue(null, issue, new ModifiedValue(null, allApprovers), changeHolder); issue.store();.
https://community.atlassian.com/t5/Jira-questions/Automatically-add-request-participants-on-SD-ticket-creation/qaq-p/89008
CC-MAIN-2018-34
en
refinedweb
Down below is my code. It says that 9 returned True when it should've returned false. If I add an exception and say that if x == 9 return False, it goes until 15 and says the same thing. It returns True when it should've been False. I can't see how it's coming up with that. When it does 9%3 is it not getting 0?? It does this for 9, 15, 21, and 25 and most likely more if I kept going. def is_prime(x): r = range(1,(x+1)) if x == 0 or x == 1: return False if x == 2: return True else: for n in (r): while n > 1: if x%n == 0: return False else: return True
https://discuss.codecademy.com/t/6-is-prime/41389
CC-MAIN-2018-34
en
refinedweb
#include <deal.II/hp/mapping_collection.h> This class implements a collection of mapping objects in the same way as the hp::FECollection implements a collection of finite element classes. It implements the concepts stated in the hp Collections module described in the doxygen documentation. Although it is recommended to supply an appropriate mapping for each finite element kind used in a hp-computation, the MappingCollection class implements a conversion constructor from a single mapping. Therefore it is possible to offer only a single mapping to the hp::FEValues class instead of a hp::MappingCollection. This is for the convenience of the user, as many simple geometries do not require different mappings along the boundary to achieve optimal convergence rates. Hence providing a single mapping object will usually suffice. See the hp::FEValues class for the rules which mapping will be selected for a given cell. Definition at line 42 of file dof_tools.h. Default constructor. Leads to an empty collection that can later be filled using push_back(). Definition at line 27 of file mapping_collection.cc. Conversion constructor. This constructor creates a MappingCollection from a single mapping. More mappings can be added with push_back(), if desired, though it would probably be clearer to add all mappings the same way. Definition at line 34 of file mapping_collection.cc. Copy constructor. Definition at line 44 of file mapping_collection.cc. Adds a new mapping to the MappingCollection. Generally, you will want to use the same order for mappings as for the elements of the hp::FECollection object you use. However, the same considerations as discussed with the hp::QCollection::push_back() function also apply in the current context. This class creates a copy of the given mapping object, i.e., you can do things like push_back(MappingQ<dim>(3));. The internal copy is later destroyed by this object upon destruction of the entire collection. Definition at line 75 of file mapping_collection.cc. Return the mapping object which was specified by the user for the active_fe_index which is provided as a parameter to this method. indexmust be between zero and the number of elements of the collection. Definition at line 162 of file mapping_collection.h. Return the number of mapping objects stored in this container. Definition at line 152 of file mapping_collection.h. Determine an estimate for the memory consumption (in bytes) of this object. Definition at line 65 of file mapping_collection.cc. The real container, which stores pointers to the different Mapping objects. Definition at line 116 of file mapping_collection.h.
https://dealii.org/8.5.0/doxygen/deal.II/classhp_1_1MappingCollection.html
CC-MAIN-2018-34
en
refinedweb
: $ mkdir yourappsfolder $ touch yourappsfolder/__init__.py 2. Create a python module with the same 'app-label' as the Oscar app: Ex: Customising oscar.apps.catalogue app $ mkdir yourappsfolder/catalogue $ touch yourappsfolder/catalogue/__init__.py 3. If the Oscar app has a models.py, then you have to create a models.py file in your local app. # your custom models go here from oscar.apps.catalogue.models import * NOTE: To customise Oscar’s models, you must add your custom one before importing Oscar’s models. Then, your models file will have two models with the same name within an app, Django will only use the first one. Ex: To add a active field to the product model: # yourappsfolder/catalogue/models.py from django.db import models from oscar.apps.catalogue.abstract_models import AbstractProduct class Product(AbstractProduct): active = models.BooleanField(default=False) from oscar.apps.catalogue.models import * 4. Create an 'admin.py' file in your local app. # yourappsfolder/catalogue/admin.py from oscar.apps.catalogue.admin import * 5. Then copy the 'migrations' directory from oscar/apps/catalogue and put it into your new local catalogue app. 6. Added it as Django app by replacing Oscar’s app with your own in INSTALLED_APPS. # settings.py from oscar import get_core_apps INSTALLED_APPS = [ ..., # all your non-Oscar apps ] + get_core_apps(['yourappsfolder.catalogue']) NOTE: get_core_apps([]) will return a list of Oscar core apps or else if you give a list of your custom apps, they will replace the Oscar core apps. 7. Finally, create migrations using 'makemigrations' management command and apply the migrations by using 'migrate catalogue' management command. Then, you can see that a new column is been added to the product model. Steps for customizing URL's: 1. Follow the same above steps described in customizing an app. 2. In Oscar, each app will have its own URLs in the 'app.py' file and each app comes with an application instance with 'urls' property, which used to access the list of URL's of an app. * Modify 'yourproject/urls.py' file to include Oscar URL's. from django.conf.urls import include, url from yourproject.app import application urlpatterns = [ # Your other URLs url(r'', include(application.urls)), ] 3. To change the URL for the basket app from 'basket' to 'cart', you need to customize root app instance by creating a sub-class of it and overriding the 'get_urls' method. # yourproject/app.py from oscar import app class Shop(app.Shop): def get_urls(self): urlpatterns = [ url(r'^cart/', include(self.basket_app.urls)), # ... # Remianing urls here ] return urlpatterns application = Shop() Steps for customizing or adding views to an app: 1. Follow the same above steps described in customizing an app. 2. Create a new view class or create a sub-class of Oscar's view in views.py file: Ex: Add extra context to the home page. from oscar.apps.promotions.views import HomeView as CoreHomeView class HomeView(CoreHomeView): def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) context["latest_products"] = Product.objects.filter( parent=None).order_by('-date_created') return context...
https://micropyramid.com/blog/how-to-customize-django-oscar-models-views-and-urls/
CC-MAIN-2018-34
en
refinedweb
Important: Please read the Qt Code of Conduct - Apple Silicon The pyside2 code cannot run on Apple Silicon, the process exists, but no window will pop up.! alt text Code Like This: import sys from PyQt5.QtWidgets import QApplication, QWidget if name == 'main': app = QApplication(sys.argv) w = QWidget() w.setWindowTitle('Test') w.show() sys.exit(app.exec_()) @JerryMazeyu Your link is broken. Do you see any errors/warnings when starting from a terminal? Also, you are talking about PySide, but in the code you posted you're using PyQt. Both pyside and pyqt have the same result. When I run this code on latest MAC, this icon pop up but I cannot see any QT window. And my code does not report errors. I dont know why. @JerryMazeyu Please start your app from a terminal and check there whether there are any errors/warnings. @JerryMazeyu Is your python native ARM build or x86? This Python virtual environment is migrated from x86 Macbook. @JerryMazeyu But is the Python interpreter ARM or x86 build? @jsulm This python environment is built on x86, translated by Rosetta2 and run on the ARM architecture Mac. @JerryMazeyu You should check the Qt libs from PySide/PyQt you're using: whether those are also x86 (most probably they are). @JerryMazeyu On Linux file PATH_TO_A_LIB_FILE Should be same on MacOS. @JerryMazeyu Yes, so that is not the issue. You can try to run your script through the Python debugger. Well, I fix this bug... The problem seems to be in anaconda. I migrate my anaconda from old x86 MacBook. When I try to change the interpreter to my real system environment /usr/loacl/bin/python3.7, it works. Thx a lot!@jsulm
https://forum.qt.io/topic/121810/apple-silicon
CC-MAIN-2021-10
en
refinedweb
A bootloader on a microcontroller is a very useful thing. It allows me to update the firmware in the field if necessary. There are many ways to use and make a bootloader (see “Serial Bootloader for the Freedom Board with Processor Expert“). But such a bootloader needs some space in FLASH, plus it needs to be programmed first on a blank device, so a JTAG programmer is needed. That’s why vendors have started including a ROM bootloader into their devices: the microcontroller comes out of the factory with a bootloader in FLASH. So instead writing my bootloader, I can use the one in the ROM. And as with everything, there are pros and cons of that approach. Outline Several of the newer NXP Kinetis microcontroller include a ROM bootloader. I have selected the NXP FRDM-KL03Z board for my experiments because it is inexpensive (less than $20) and a tiny microcontroller useful for smaller applications. And that KL03Z is present on the Ultimate Hacking Keyboard which sparked my interest. In this article I’ll share my experience and journey to use the ROM bootloader on the KL03Z (ARM Cortex-M0+, 32 KByte of FLASH. 2 KB SRAM in a 24QFN Package): The source code used in this article can be found on GitHub (see Links section at the end). Bootloader? Bootloader(s)! The NXP Kinetis bootloader (KBOOT software) is available in version v2 (at the time of this article) on. NXP provides three different variants: - Flashloader: that bootloader is a ‘one-time-bootloader’ and resides in FLASH, either factory or user programmed. The bootloader area will be overwritten by the application, so the full FLASH memory is available to the application. But it is only possible to update the application one time, unless the application itself includes a bootloader. The Flashloader is interesting for programming devices without the need for a JTAG programmer. The KBOOT package comes with several example applications. - Flash-Resident Bootloader: This bootloader is a ‘traditional’ bootloader which resides in FLASH memory. Source code is provided and I can fully configure it, but I need initially a JTAG programmer to program the device. The KBOOT package includes several example for different boards. - ROM Bootloader: This bootloader is present on all Kinetis devices with a boot ROM, including the KL03Z. Basically it is a special version of the Flash-Resident Bootloader programmed into the ROM of the device. But no source files or any other information apart of the information in the reference manual is provided. There are different ways how to communicate with the bootloader (I²C, SPI, UART, USB HID, USB MSD, CAN). The bootloader uses a special communication protocol, and the KBOOT software includes GUI and command line utilities to communicate with the device. ROM Bootloader The ROM Bootloader resides in the ROM starting at 0x1c00200 and uses some part of the RAM while the bootloader is running: 💡 It would be useful to have the sources and memory map of the ROM bootloader available. That way, it would be possible to re-use some of the bootloader functions from the application to save FLASH space. The bootloader could be called by the application with the following piece of code: static void RunRomBootloader(void) { uint32_t runBootloaderAddress; void (*runBootloader)(void *arg); /* Read the function address from the ROM API tree. */ runBootloaderAddress = **(uint32_t **)(0x1c00001c); runBootloader = (void (*)(void * arg))runBootloaderAddress; /* Start the bootloader. */ runBootloader(NULL); } With the above code the application can enter the bootloader any time. Booting During POR (Power on Reset) or a normal reset it can be configured if the microcontroller enters the ROM bootloader or directly boots from the normal FLASH. This is controlled by several things: - FORCEROM: two bits used to always enter the ROM bootloader. If the bits are not zero, it always enters the ROM bootloader. - BOOTPIN_OPT: Part of the FOPT register. If this bit is zero, it enables checking an optional bootloader enable pin (NMI in the case of the KL03Z): if that pin is pulled low, it enters the ROM bootloader. - BOOTCFG0 pin: This is the pin enabled by the BOOTPIN_OPT setting (NMI pin in case for the KL03Z). - BOOTSRC_SEL: Part of the FOPT register. If set to 10 or 11, then it enters the ROM bootloader: Below is the diagram of the boot process: Entering Bootloader So the ROM bootloader is entered if - FORCEROM is set non-zero - Or: A bootloader pin is configured with BOOTPIN_OPT and that pin is asserted (NMI) - Or: BOOTSRC_SEL is set to 10 or 11 The NMI pin is on pin 19 of the KL03Z32VFK4: On the FRDM-KL03Z the NMI pin is routed to the SW3 push button: The button is present on the FRDM-KL03Z board here: Bootloader Pin Muxing As outlined above, the NMI pin can be used to enter the bootloader. On which pins the bootloader can communicate is documented in the reference manual. The KL03Z can communicate over UART, SPI and I²C: The UART (PTB1, PTB2) is routed to the OpenSDA USB CDC of the K20, and the the I2C (PTB3, PTB4) are available on the J2 header: Bootloader Configuration Area (BCA) The bootloader is configured by a structure located at 0x3C0 in FLASH (after the vector table starting at address 0x0: BCA and Linker File To configure the bootloader and the BCA, I use the following implementation: 💡 Note that the bootloader will select the first ‘working’ communication channel! I had an issue that on the I2C bus another device was sending data during bootloader boot-up, causing the bootloader listening to the I2C bus instead to the UART. I recommend only to enable the needed communication channels in the BCA settings. /* bootloader_config.c * KBOOT ROM Bootloader configuration for FRDM-KL03Z Board */ #include <stdint.h> #define ENABLE_BCA (1) /*!< 1: define Bootloader Configuration Area mit magic number to use it from ROM bootloader; 0: use default setting (no BCA) */ typedef struct BootloaderConfiguration { uint32_t tag; //!< [00:03] Magic number to verify bootloader configuration is //! valid. Must be set to 'kcfg'. uint32_t crcStartAddress; //!< [04:07] Start address for application image CRC //! check. If the bits are all set then Kinetis //! bootloader by default will not perform any CRC //! check. uint32_t crcByteCount; //!< [08:0b] Byte count for application image CRC //! check. If the bits are all set then Kinetis //! bootloader by default will not prform any CRC check. uint32_t crcExpectedValue; //!< [0c:0f] Expected CRC value for application CRC //! check. If the bits are all set then Kinetis //! bootloader by default will not perform any CRC //! check. uint8_t enabledPeripherals; //!< [10:10] Bitfield of peripherals to enable. //! bit 0 - LPUART, bit 1 - I2C, bit 2 - SPI, //! bit 3 - CAN, bit 4 - USB //! Kinetis bootloader will enable the peripheral if //! corresponding bit is set to 1. uint8_t i2cSlaveAddress; //!< [11:11] If not 0xFF, used as the 7-bit I2C slave //! address. If 0xFF, defaults to 0x10 //! for I2C slave address. uint16_t peripheralDetectionTimeoutMs; //!< [12:13] Timeout in milliseconds //! for active peripheral detection. If //! 0xFFFF, defaults to 5 seconds. uint16_t usbVid; //!< [14:15] Sets the USB Vendor ID reported by the device //! during enumeration. If 0xFFFF, it defaults to 0x15A2. uint16_t usbPid; //!< [16:17] Sets the USB Product ID reported by the device //! during enumeration. uint32_t usbStringsPointer; //!< [18:1b] Sets the USB Strings reported by the //! device during enumeration. uint8_t clockFlags; //!< [1c:1c] The flags in the clockFlags configuration //! field are enabled if the corresponding bit is cleared (0). //! bit 0 - HighSpeed Enable high speed mode (i.e., 48 MHz). uint8_t clockDivider; //!< [1d:1d] Inverted value of the divider to use for //! core and bus clocks when in high speed mode. } bootloader_config_t; /* bits for enabledPeripherals */ #define ENABLE_PERIPHERAL_UART (1<<0) #define ENABLE_PERIPHERAL_I2C (1<<1) #define ENABLE_PERIPHERAL_SPI (1<<2) #define ENABLE_PERIPHERAL_CAN (1<<3) /* not supported for KL03! */ #define ENABLE_PERIPHERAL_USB_HID (1<<4) /* not supported for KL03! */ #define ENABLE_PERIPHERAL_USB_MSC (1<<7) /* not supported for KL03! */ /* Bootloader configuration area, needs to be at address 0x3C0! */ __attribute__((section(".BootloaderConfig"))) const bootloader_config_t BootloaderConfig = { #if ENABLE_BCA .tag = 0x6766636B, //!< Magic Number #else .tag = 0xFFFFFFFF, //!< No Magic Number #endif .crcStartAddress = 0xFFFFFFFF, //!< Disable CRC check .crcByteCount = 0xFFFFFFFF, //!< Disable CRC check .crcExpectedValue = 0xFFFFFFFF, //!< Disable CRC check .enabledPeripherals = ENABLE_PERIPHERAL_UART, //ENABLE_PERIPHERAL_UART|ENABLE_PERIPHERAL_I2C|ENABLE_PERIPHERAL_SPI|ENABLE_PERIPHERAL_CAN|ENABLE_PERIPHERAL_USB_HID|ENABLE_PERIPHERAL_USB_MSC, //!< Enabled Peripheral: UART I2C SPI CAN USB-HID .i2cSlaveAddress = 0x10, //!< Use default I2C address(0x10) .peripheralDetectionTimeoutMs = 5000, //!< Use user-defined timeout(ms) .usbVid = 0xFFFF, //!< Use default Vendor ID(0x15A2) .usbPid = 0xFFFF, //!< Use default Product ID(0x0073) .usbStringsPointer = 0xFFFFFFFF, //!< Use default USB String .clockFlags = 0xFF, //!< 0 bit cleared: Enable High speed mode. NOTE: Enabling high speed mode makes UART connection worse or requires pull-up on Rx line! .clockDivider = 0xff, //!< Use clock divider(0) }; /* 16 bytes at address 0x400 */ __attribute__((used, section(".FlashConfig"))) const uint32_t FOPTConfig[4] = { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, // 0xFFFF3DFE // boot from FLASH 0xFFFFBDFE // boot from ROM, means this will kick in the bootloader by default }; 💡 Be careful with the FlashConfig (FOPT) configuration! If not done right, you might brick your part! See “How (not) to Secure my Microcontroller“ Using the macro #define ENABLE_BCA (1) /*!< 1: define Bootloader Configuration Area mit magic number to use it from ROM bootloader; 0: use default setting (no BCA) */ I can turn on/off the BCA. If turned off (set to 0), the BCA signature will not be used, and the bootloader ignores the BCA. The BootloaderConfig variable needs to be allocated in FLASH at address 0x3C0. For this I have allocated a MEMORY area m_bootloader_config (RX) : ORIGIN = 0x000003C0, LENGTH = 0x20 /* ROM Bootloader configuration */ with the corresponding placement in the linker file (see “Defining Variables at Absolute Addresses with gcc“): /* placing my named section at given address: */ .myBootloaderConfigBlock : { KEEP(*(.BootloaderConfig)) /* keep my variable even if not referenced */ } > m_bootloader_config Same for the Flash Configuration (FOPT): declared a memory area: m_flash_config (RX) : ORIGIN = 0x00000400, LENGTH = 0x00000010 /* Flash configuration options (FOPT) */ and placed it in the linker section like this: .flash_config : { . = ALIGN(4); KEEP(*(.FlashConfig)) /* Flash Configuration Field (FCF) */ . = ALIGN(4); } > m_flash_config Erasing BCA and FLASH If that configuration area is not properly set up, then running the bootloader might fail. I highly recommend to erase the KL03Z flash starting playing with the FRDM-KL03Z board, as the preloaded demo application seems to confuse the bootloader. To erase the FLASH, I’m using the SEGGER OpenSDA firmware and the SEGGER J-Link J-Flash Lite program which is free of charge for non-production purposes: Select the device: Then erase the chip: With this, the BCA is erased and set to default 0xFF memory pattern. Connecting to Bootloader over UART To make an initial connection to the ROM bootloader after erased the FLASH, connect a USB cable to the OpenSDA USB port: Determine the virtual COM port (e.g. using the Windows Device Manager): If using the P&E OpenSDA Debug connection, then the serial port will show up as ‘OpenSDA – CDC Serial Port’: Then do a Reset while the SW3/NMI pin pulled LOW: - Press and hold the Reset button - Press and hold the SW3 button - Release the Reset button while still holding the SW3 button - Release the SW3 button There is no visual sign at all to show that the microcontroller is in bootloader mode now. NOTE: There are several issues with the ROM bootloader, see the following errata: Because of this, I only was able to connect with 19200 baud (and not always!). So make sure you are using 19200 baud! To connect to the board use the KinetisFlashTool (GUI) or blhost (command line tool). 💡 Both the used communication channel (I2C, UART, SPI) and the speed (baud) is selected at the first communication attempt. To change the communication speed or communication channel, the KL03Z has to be reset first! The KinetisFlashTool (for Windows) is located in <KBOOT Installation path>\NXP_Kinetis_Bootloader_2_0_0\bin\Tools\KinetisFlashTool\win The blhost tool is located in <KBOOT Installation path>\NXP_Kinetis_Bootloader_2_0_0\bin\Tools\blhost Then press ‘Connect’, and hopefully it connects (otherwise retry): With the blhost command line tool, use blhost --port COM9,19200 -d -- get-property 1 💡 Make sure that the COM port is not already used (close the KinetisFlashTool). The -d option produces some debug output, and with get-property 1 I ask for the bootloader version information. The first command after power-on might lost (yet another entry in the errata): In that case, cancel the command with CTRL-C: blhost --port COM9,19200 -d -- get-property 1 Warning: Operation canceled! - The target device must be reset before sending any further commands. ^C Then try it again, the second time it usually works: blhost --port COM9,19200 -d -- get-property 1 [5a a6] <5a> Ping responded in 1 attempt(s) <a7> <00 00 01 50 00 00 29 ae> Framing protocol version = 0x50010000, options = 0x0 Inject command 'get-property' [5a a4 0c 00 4b 33 07 00 00 02 01 00 00 00 00 00 00 00] <5a> <a1> <5a> <a4> <0c 00> <07 7a> <a7 00 00 02 00 00 00 00 00 00 01 4b> Successful response to command 'get-property(current-version)' - took 0.009 seconds [5a a1] Response status = 0 (0x0) Success. Response word 1 = 1258356736 (0x4b010000) Current Version = K1.0.0 Success! We are able to talk with the bootloader! I was further able to improve above situation after considering the e8086 in the errata: So I added a 10K pullup to the LPUART Rx pin: Enabling Higher Baud for UART Connection With lots of trial-and-error, I managed to get a stable bootloader UART connection. Here is what I did: - Added 10k Pull-Up resistor to LPUART Rx Pin - Setting BCA clock flags to 0xFE: .clockFlags = 0xFE - Setting BCA cock divider to 0xFF: .clockDivider = 0xff - Reset and enter bootloader with above settings That way I have been able to use for example 57600 🙂 : blhost --port COM9,57600 -d -- get-property 0x2 [5a a6] <5a> Ping responded in 1 attempt(s) <a7> <00 00 01 50 00 00 29 ae> Framing protocol version = 0x50010000, options = 0x0 Inject command 'get-property' [5a a4 0c 00 3e fb 07 00 00 02 02 00 00 00 00 00 00 00] <5a> <a1> <5a> <a4> <0c 00> <2d c6> <a7 00 00 02 00 00 00 00 01 00 00 00> Successful response to command 'get-property(available-peripherals)' - took 0.013 seconds [5a a1] Response status = 0 (0x0) Success. Response word 1 = 1 (0x1) Available Peripherals = UART I have put on GitHub three blinky programs you can use to test the bootloader: If using the Flash tool, browse for the image file and use the Update button: The same with the blhost command line utility looks like this: blhost --port COM9,57600 write-memory 0 "FRDM-KL03Z_LED_blue.bin" If using S19/S-Record files, there is the ‘flash-image’ command: blhost --port COM9,57600 flash-image "FRDM-KL03Z_LED_blue.srec" However, I had bad luck with these, they returned an error: kStatus_FlashCommandFailure blhost --port COM9,57600 write-memory 0 "c:\tmp\FRDM-KL03Z_LED_blue.bin" Ping responded in 1 attempt(s) Inject command 'write-memory' Preparing to send 14784 (0x39c0) bytes to the target. Successful generic response to command 'write-memory' (1/1)24%Data phase write aborted by status 0x2712 kStatus_AbortDataPhase Response status = 105 (0x69) kStatus_FlashCommandFailure Wrote 3616 of 14784 bytes. Only until by trial-and-error I have found out that if I do an flash-erase-all first it succeeds: blhost --port COM9,57600 -d -- flash-erase-all [5a a6] <5a> Ping responded in 1 attempt(s) <a7> <00 00 01 50 00 00 29 ae> Framing protocol version = 0x50010000, options = 0x0 Inject command 'flash-erase-all' [5a a4 08 00 0c 22 01 00 00 01 00 00 00 00] <5a> <a1> <5a> <a4> <0c 00> <2d 84> <a0 00 08 02 00 00 00 00 01 00 00 00> Successful generic response to command 'flash-erase-all' - took 0.034 seconds [5a a1] Response status = 0 (0x0) Success. Then do the programming: blhost --port COM9,57600 write-memory 0 "c:\tmp\FRDM-KL03Z_LED.bin" Ping responded in 1 attempt(s) Inject command 'write-memory' Preparing to send 17544 (0x4488) bytes to the target. Successful generic response to command 'write-memory' (1/1)100% Completed! Successful generic response to command 'write-memory' Response status = 0 (0x0) Success. Wrote 17544 of 17544 bytes. I have no explanation, as nothing in my flash was protected or secured. At least I have found a way to get it working 🙂 Summary A ROM bootloader is a nice thing: I don’t need to reserve FLASH space for the bootloader. Instead the bootloader is burned into the ROM and I can communicate to it with I²C, UART and SPI on the NXP KL03Z. Be aware of the errata, and with the right steps and connection settings it should hopefully work.The KL03Z device errata affects several parts of the ROM bootloader, requiring some workarounds. What’s next? I’m currently exploring and using the BusPal technology: this part is really interesting, as it allows to use a microcontroller to interface with the bootloader of another microcontroller. That way, one device can update another. The NXP provided projects are for IAR and Keil, but I have managed to port BusPal to the FRDM-KL25Z using free and open GNU tools. So this could be the topic of a next article? I hope this article is useful for you to get started with the bootloader on the FRDM-KL03Z or any other board. And don’t forget to always check the errata of your device ;-). Happy Bootloading 🙂 Links - Kinetis Bootloader and Tools download page: - Source code used in this article on GitHub: - NXP Freedom boards: - FRDM-KL03Z board: - FRDM-KL03Z errata: - Ultimate Hacking Keyboard: - Serial Bootloader: Serial Bootloader for the Freedom Board with Processor Expert - Terminal program for bootloaders: Swiss Army Knife of Terminal Program for Serial Bootloaders Hi Eric, Thank you for this article. It is very good, concise and summarizes well the challenges one might have in getting to run the KBOOT from ROM (Also it compresses the reading of all the documentation from NXP in one nice article.). Well done! I’ve been looking at KBOOT from ROM for the KL82. I agree with your note that “It would be useful to have the sources and memory map of the ROM bootloader available.” . I have asked already NXP for this: . Seems that they are not willing to share this info. Pity, because, as you said, one could save code space. Looking forward for the next article, about BusPal. Best wishes, Radu Hi Radu, thanks :-). As for the memory map of the ROM bootloader: I can step through the assembly code, and it very much looks the same as the Flash bootloader. So with some reverse engineering, it would be possible to get the entry points of the functions used. But that would be specific for each ROM bootloader, so has to be done for each implementation. Erich What purpose does it serve NXP to make this information hard to get? In one case they actually threatened a lawyer attack as an answer to a question about getting GUI source code. Knowing what RAM the bootloader may trash is sometimes required if want to preserve variables across resets. Obviously I cannot answer the first question. But what RAM is used be bootloader is documented in the KL03 reference manual (yes, it was not easy for me to find it): pate 109 of KL03P24M48SF0RM.pdf, Figure 11-1 Kinetis Bootloader ROM/RAM Memory Maps. According to this, the bootloader uses the RAM from 0x1fff’fe00 to 0x2000’020E. I hope this helps, Erich Huge thanks in the name of the whole UHK team, Erich! I’m so glad that you’re exploring this territory and sharing your findings. I’ve written about BusPal in a recent UHK blog update. Hope you find it interesting. Cheers! Anyone been using the KBoot HID? I’ve run into to three significant problems with it. A) “blhost -u$(VID),$(PID) reset” does not work. The ‘reset’ commands put KBoot in to a loop of incomplete enumeration cycles requiring a physical reset or power down. B) The default time to wait for the bootloader is to short for Windows to install the actual HID device driver. It says “Device Unplugged” during the install process. I’ve see Windows take well over a minute to complete this driver install process, even when not searching Windows Updates that can add even more minutes. A longer default time could be set in the BCA, yet who wants to wait minutes for their embedded device to boot? Any way to speed up Windows install process? Only real difference between this device and any other installed generic HID is the VID/PID. Would seem there should be a way to copy and existing one in the registry. C) The KBootGUI does not work on all computers. About 50% of the computers I’ve tried to run the KBootGUI on do nothing. That is the icon is clicked to start the program and it acts exactly like the icon was never clicked. No program, no errors, nothing at all happens. Any ideas why? blhost has worked on every computer. The KL03Z does not have USB, so does not have the HID bootloader feature. I tried it (to less extend) on the FRDM-K22F, but that’s a Flash resident bootloader and not the ROM bootloader, and I have not seen the issue there you describe. Which device did you use? The Windows install process only seemed to happen one time for me, and was faster the second time. Anyway I believe any bootloader which uses something more fancy than a UART might run into problems, especially anything with USB: there are simply too many traps with USB bootloaders in my view, so I prefer UART over anything else. What I did is porting the BusPal to the FRDM-KL25Z, so it can act as an ‘intelligent’ loader. I’m thinking that I could add a SD card to it and use it as a loader from SD card over UART to the device. About KBootGUI: I did not had issues on my machine (Windows 10). I’m aware of at least one issue with blhost on Mac (which I don’t use): I hope this helps, Erich It is the KL27 that I’m using which is also based on KBoot. A USB connector is already on the device for other reasons which is why did not go with serial. Regarding B), I’ve experienced the issue, but did not try to reproduce it again. According to my knowledge, the maximum KBOOT timeout is about a minute which might not be enough for Windows in some cases. Maybe the best way is to run an application that looks for the device and pings KBOOT. That way, it’d run indefinitely. The question is whether this is possible until the device driver is installed. In my opinion, that timeout feature is something which probably should not be used. First it delays starting up the application, and as pointed out, there is a limit of the amoung of milliseconds (16bit variable, so indeed only a little bit more than one minute to wait). The always better approach is to check for some trigger (push button pressed/etc) in the application main() after reset and then enter the bootloader mode if triggered. This requires a way to trigger (e.g. push button or jumper), but thats something worthwile to spend. I totally agree with the trigger feature. I meant that a long timeout may be useful once the bootloader is triggered, but maybe it’s a better approach to stay in the bootloader forever once is triggered. This may depend on the application. What I always provide is a way (usually jumper or push button) to enter the bootloader and a push button for reset. If two buttons/pins are available, that is the ideal solution. In some designs I’m using the reset button both for reset and entering the bootloader: after power on, the reset pin is configured as reset pin (as usual). Then in main(), after a delay of 1 or 2 seconds the reset pin get muxed as GPIO input pin. That delay is necessary to allow a debugger to assert the reset line to connect to the application after reset. After that delay, the application muxes the pin as input pin: if it is asserted say up to 5 seconds after reset, it enters the bootloader. After that 5 seconds delay, the pin is muxed back to the reset function. That way only one pin is needed and allows a flexible handling of bootloader and application entry. Thanks Erich! I like the two button approach for dev boards, but the one button implementation is easier from a user standpoint for consumer electronics products. Pingback: Further steps towards mass production – Ultimate Hacking Keyboard Micro-typo: In the example code block following the sentence “Same for the Flash Configuration (FOPT): declared a memory area:”, it appears that you have a small copy/paste error: Where it says “m_bootloader_config (RX) : ORIGIN = 0x000003C0, LENGTH = 0x20 /* ROM Bootloader configuration */”, I think that should be “m_flash_config (RX) : ORIGIN = 0x00000400, LENGTH = 0x10” One question: is it possible to do math expressions, such as “LENGTH = 0x8000 – 0x410”? I could swear I’ve seen that done somewhere, but not sure if it applies to .ld files. Thanks for finding that copy-paste bug! Fixed now :-). And yes: you can use some basic math in linker script files. For example I have used it in Super-helpful post! For reasons unknown, I found that simply declaring the .bca section “KEEP” in the .ld file was not sufficient to prevent the linker from pruning the BootloaderConfig table. Instead, I also had to invoke the GNU-specific “used” attribute when instantiating the table: __attribute__((section(“.BootloaderConfig”))) __attribute__((used)) const bootloader_config_t BootloaderConfig = {…} For more history and details, see I’m not sure why it worked for me, but it did. But I know that these kind of things might depend on the toolchain/gcc version used. Indeed, it might be the best if both KEEP and (used) are used together. I always check the map file. One thing that has bedeviled me (see and comments in) is how to generate the proper CRC32 to insert in the .crcExpectedValue field of the Bootloader Configuration Area. (Our app *really* needs CRC validation since its only communication with the outside world is a serial port: no JTAG, no reset button…) It turns out you CAN coerce srec_cat into producing the correct CRC32 for the Kinetis Bootloader 2.0 protocol as follows: $ srec_cat test.srec -Bit_Reverse -CRC32LE 0x1000 -Bit_Reverse -XOR 0xff -crop 0x1000 0x1004 If you’ve read Erich’s nifty article on srecord, you’ll know what all those command line arguments mean! 🙂 Thank you so much for posting the solution! I’m sure I will need that one very soon, as one of my next projects is supposed to use the Kinetis Bootloader too. Pingback: Flash-Resident USB-HID Bootloader with the NXP Kinetis K22 Microcontroller | MCU on Eclipse Pingback: Tutorial: CRC32 Checksum with the KBOOT Bootloader | MCU on Eclipse Hi Erich, I’ve got a project that uses the KL27 as a host processor, with the KL03 as a slave. I’d like to start using the ROM bootloader so the host can update the slave firmware – ie, using a microprocessor instead of the KBOOT program on a PC. In getting this bootloader working for your purposes, have you come across any resources for getting this to work – example host code, app notes etc? As you mentioned, the TRM is pretty thin on detail… thanks! Iain Hi Iain, I have worked on the Ultimate Hacking Keyboard which uses a K22 as host and a KL03Z as a slave. Have a look at I hope this helps, Erich excellent, thanks Erich! Pingback: Regaining Debug Access of NXP i.MX RT1064-EVK executing WFI | MCU on Eclipse Hi Erich, first of all thanks you for your post! I’m trying to use the ROM Bootloader of KE18F but hard faults make me cry… I found where the problem is, but idk what is it. When I try to config BCA the initial value to configuration is Magic Number and it’s configured correctly with a value of 0x3C0, but in the next code line (it does not matter which) the program enter on a Hard Fault. I hope you have understood me, because my english is so basic. Anyway I put the code that I used for config BCA: /* Bootloader configuration area, needs to be at address 0x3C0! */ #define BOOTCONFIG_BASE (0x000003C0) #define BOOTCONFIG ((bootloader_config_t*)BOOTCONFIG_BASE) void bootloaderconfig_ (void) { #if ENABLE_BCA BOOTCONFIG->tag = 0x6766636B; #else BOOTCONFIG->tag = 0xFFFFFFFF, //!crcStartAddress = 0xFFFFFFFF; BOOTCONFIG->crcByteCount = 0xFFFFFFFF; BOOTCONFIG->crcExpectedValue = 0xFFFFFFFF; BOOTCONFIG->enabledPeripherals = ENABLE_PERIPHERAL_UART; BOOTCONFIG->peripheralDetectionTimeoutMs = 1000; BOOTCONFIG->clockFlags = 0x01; BOOTCONFIG->clockDivider = 0xFF; } int main(void) { /* Init board hardware. */ BOARD_InitBootPins(); BOARD_InitBootClocks(); BOARD_InitBootPeripherals(); /* Init FSL debug console. */ BOARD_InitDebugConsole(); pin_Yellow_INIT(GPIO_configOutputH); pin_Green_INIT(GPIO_configOutputH); pin_SW2_INIT(GPIO_configInput); PORT_SetPinInterruptConfig(BOARD_INITPINS_SW2_PORT, BOARD_INITPINS_SW2_PIN,kPORT_InterruptFallingEdge); EnableIRQ(PORTD_IRQn); NVIC_SetPriority(PORTD_IRQn, 5); bootloaderconfig_(); /* Force the counter to be placed into memory. */ volatile static int i = 0 ; /* Enter an infinite loop, just incrementing a counter. */ while(1) { i=2371603; while(i) i--; pin_Yellow_TOGGLE(); } return 0 ; } Hi Jan, I probably would need such a KE18F board, but… I see you are calling bootloaderconfig_()? The bootloader configuration is a constant structure in FLASH, and you cannot write to that at runtime (well, without proper flash programming). So it is for sure not working, and a hard fault is what I expect for something like this (you try to write to read-only memory!). Have a look at my KL03Z application and source code in this article: I have a constant structure placed in flash to configure the bootloader, that’s the way it is supposed to work. I hope this helps, Erich Pingback: Linking Bootloader Applications with Eclipse and FreeMarker Scripts | MCU on Eclipse
https://mcuoneclipse.com/2017/07/12/getting-started-rom-bootloader-on-the-nxp-frdm-kl03z-board/
CC-MAIN-2021-10
en
refinedweb
Relay.RootContainer is a React component that attempts to fulfill the data required in order to render an instance of Component for a given route. Props ComponentRelay container that defines fragments and the view to render. routeRoute that defines the query roots. forceFetchWhether to send a server request regardless of data available on the client. renderLoadingCalled to render when data requirements are being fulfilled. renderFetchedCalled to render when data requirements are fulfilled. renderFailureCalled to render when data failed to be fulfilled. onReadyStateChange Component: RelayContainer Must be a valid RelayContainer. Relay will attempt to fulfill its data requirements before rendering it. See also: Root Container > Component and Route route: RelayRoute Either an instance of Relay.Route or an object with the name, queries, and optionally the params properties. See also: Root Container > Component and Route forceFetch: boolean If supplied and set to true, a request for data will always be made to the server regardless of whether data on the client is available to immediately fulfill the data requirements. See also: Root Container > Force Fetching renderLoading(): ?ReactElement When data requirements have yet to be fulfilled, renderLoading is called to render the view. If this returns undefined, the previously rendered view (or nothing if there is no previous view) is rendered. <Relay.RootContainer Component={ProfilePicture} route={profileRoute} renderLoading={function() { return <div>Loading...</div>; }} /> See also: Root Container > renderLoading renderFetched( data: {[propName: string]: $RelayData}, readyState: {stale: boolean} ): ?ReactElement When all data requirements are fulfilled, renderFetched is called to render the view. This callback is expected to spread data into the supplied Container when rendering it. <Relay.RootContainer Component={ProfilePicture} route={profileRoute} renderFetched={function(data) { return ( <ScrollView> <ProfilePicture {...data} /> </ScrollView> ); }} /> See also: Root Container > renderFetched renderFailure(error: Error, retry: Function): ?ReactElement When data requirements failed to be fulfilled, renderFailure is called to render the view. <Relay.RootContainer Component={ProfilePicture} route={profileRoute} renderFailure={function(error, retry) { return ( <div> <p>{error.message}</p> <p><button onClick={retry}>Retry?</button></p> </div> ); }} /> See also: Root Container > renderFailure onReadyStateChange( readyState: { aborted: boolean; done: boolean; error: ?Error; events: Array<ReadyStateEvent>; ready: boolean; stale: boolean; } ): void This callback prop is called as the various events of data resolution occurs. See also: Ready State © 2013–present Facebook Inc. Licensed under the BSD License.
https://docs.w3cub.com/relay/api-reference-relay-root-container
CC-MAIN-2021-10
en
refinedweb
You are browsing the documentation for Symfony 3.4 which is not maintained anymore. Consider upgrading your projects to Symfony 5.2. The and Observer design patterns EventDispatcher features as an independent component in any PHP application. Read the Events and Event Listeners article to learn about how to use it in Symfony applications. Events¶ When an event is dispatched, it’s identified by a unique name (e.g. kernel.response), which any number of listeners might be listening to. An Symfony\Component\EventDispatcher. See also Read “The Generic Event Object” for more information about this base event Symfony\Component\HttpKernel\Event', [.: use Symfony\Component\EventDispatcher\Event; $dispatcher->addListener('acme.foo.action', function (Event $event) { // will be executed when the acme.foo.action event is dispatched }); Once a listener is registered with the dispatcher, it waits until the event is notified. In the above example, when the acme.foo.action event is dispatched, the dispatcher calls the AcmeListener::onFooAction() method and passes the Event object as the single argument: use Symfony\Component\EventDispatcher\Event; class AcmeListener { // ... public function onFooAction(Event $event) { // ... do something } }: namespace Acme\Store\Event; use Acme\Store\Order; use Symfony\Component\EventDispatcher\Event; /** *\Event\OrderPlacedEvent; use Acme\Store\Order; // the order is somehow created or retrieved $order = new Order(); // ... // creates the OrderPlacedEvent and dispatches it $event = new OrderPlacedEvent($order); $dispatcher->dispatch(OrderPlacedEvent::NAME, Symfony\Component\EventDispatcher\EventSubscriberInterface interface, which requires a single static method called getSubscribedEvents(). Take the following example of a subscriber that subscribes to the kernel.response and order.placed events: namespace Acme\Store\Event; use Acme\Store\Event\OrderPlacedEvent; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpKernel\Event\FilterResponseEvent; use Symfony\Component\HttpKernel\KernelEvents;\Event\StoreSubscriber; // ... $subscriber = new StoreSubscriber(); $dispatcher->addSubscriber($subscriber); (a positive or negative integer that defaults to 0). The example above shows how to register several listener methods for the same event in subscriber and also shows how to pass the priority of each listener method. The higher the number,: use Acme\Store\Event\OrderPlacedEvent; public function onStoreOrder(OrderPlacedEvent $event) { // ... $event->stopPropagation(); } Now, any listeners to order.placed that have not yet been called will not be called. It is possible to detect if an event was stopped by using the isPropagationStopped() method which returns a boolean value: // ... $dispatcher->dispatch('foo.event', $event); if ($event->isPropagationStopped()) { // ... } Symfony\Component\EventDispatcher..
https://symfony.com/doc/3.4/components/event_dispatcher.html
CC-MAIN-2021-10
en
refinedweb
Handle Thomson Reuters Web of Science™ export files Project description wosfile wosfile is a Python package designed to read and handle data exported from Thomson Reuters Web of Science™. It supports both tab-delimited files and so-called ‘plain text’ files. The point of wosfile is to read export files from WoS and give you a simple data structure—essentially a dict—that can be further analyzed with tools available in standard Python or with third-party packages. If you're looking for a ‘one-size-fits-all’ solution, this is probably not it. Pros: - It has no requirements beyond Python 3.6+ and the standard library. - Completely iterator-based, so useful for working with large datasets. At no point should we ever have more than one single record in memory. - Simple API: usually one needs just one function wosfile.records_from(). Cons: - Pure Python, so might be slow. - At the moment, wosfile does little more than reading WoS files and generating Record objects for each record. While it does some niceties like parsing address fields, it does not have any analysis functionality. Examples These examples use a dataset exported from Web of Science in multiple separate files(the maximum number of exported records per file is 500). Subject categories in our data import glob import wosfile from collections import Counter subject_cats = Counter() # Create a list of all relevant files. Our folder may contain multiple export files. files = glob.glob("data/savedrecs*.txt") # wosfile will read each file in the list in turn and yield each record # for further handling for rec in wosfile.records_from(files): # Records are very thin wrappers around a standard Python dict, # whose keys are the WoS field tags. # Here we look at the SC field (subject categories) and update our counter # with the categories in each record. subject_cats.update(rec.get("SC")) # Show the five most common subject categories in the data and their number. print(subject_cats.most_common(5)) Citation network For this example you will need the NetworkX package. The data must be exported as ‘Full Record and Cited References’. import networkx as nx import wosfile # Create a directed network (empty at this point). G = nx.DiGraph() nodes_in_data = set() for rec in wosfile.records_from(files): # Each record has a record_id, a standard string uniquely identifying the reference. nodes_in_data.add(rec.record_id) # The CR field is a list of cited references. Each reference is formatted the same # as a record_id. This means that we can add citation links by connecting the record_id # to the reference. for reference in rec.get("CR", []): G.add_edge(rec.record_id, reference) # At this point, our network also contains all references that were not in the original data. # The line below ensures that we only retain publications from the original data set. G.remove_nodes_from(set(G) - nodes_in_data) # Show some basic statistics and save as Pajek file for visualization and/or further analysis. print(nx.info(G)) nx.write_pajek(G, 'network.net') Other Python packages The following packages also read WoS files (+ sometimes much more): Other packages query WoS directly through the API and/or by scraping the web interface: - pywos (elsewhere called wos-statistics) - wos - wosclient Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/wosfile/
CC-MAIN-2021-10
en
refinedweb
[WARNING: this post has no business value whatsoever, and that is by design. Please do not take any of this post as something you’d do in your applications. I got a new toy and I am just goofing around with it :-)] If you’ve been reading this blog through the years, you know I am a big fan of gadgets and in general anything I can tinker with. Last August I read about Blink(1), a very promising project on Kickstarter for an über USB status light, which would allow you to translate any event you want to keep an eye on in blinks of arbitrary color/intensity/frequency. I instantly wanted in! I proudly joined the ranks of the project backers, and hoped that it would actually become reality. Today, almost 4 months later, I found in the mailbox a nice padded mailer containing a cute box with the blinker: beautifully made, and a perfect match with the original vision. Isn’t the epoch we live in absolutely amazing? 🙂 Anyway, the enthusiasm for the little toy was soon tempered by the somewhat shaky support for using Blink(1) from .NET. That wasn’t enough to deter me from messing with it anyway and from finding a way of concocting something claims-related. And now that you know the overall story, without further ado… Unboxing Blink(1) Here, savor with me the pleasure of unboxing a new gadget. After the various updates from the project creators, I knew I was going to get Blink(1) this week. When I dug out this white bubble-wrap envelope from the daily pile of magazines (the magic of magformiles and having held a travelling job for few years) I *knew* that it was it 🙂 In a very Japanese turn of events the envelope contained another mailer, also bubble-lined. Those guys really made sure that the goods arrived in good shape. And finally, the product box! It’s really tiny: the drawing on the top is a 1:1 representation. Notable detail, the lid snaps to the box body via a magnet. Very classy 🙂 Before opening it, let’s take a look on the bottom side: there you’ll find enough info to grok what the product is about and to get you started using it. …and finally, ta-dah! Here’s Blink(1), hugged by its foam bed. It’s exactly as advertised: a small translucent enclosure of white plastic with a gently chamfered aluminum top, all fitting together in perfect alignment. Here there’s another view, to get you a feeling of the dongle size before plugging it in. …and in it goes. The Blink(1) gets recognized immediately by Windows: it flashes once, then it goes quiet waiting for your commands. More about that in the next section. Above you can see a shot of Blink(1) plugged in my Lenovo X230 Tablet, shining a nice shade of green. How did I get it to do that? Read on… Goofing Around with Blink(1) and Claims The main appeal Blink(1) has for me is its potential to manifest in meatspace events that would normally require you to watch a screen and interpret it. It might not have the directness of acquiring a brand-new new sense, but it can certainly contribute to confer an intuitive dimension to events that one would normally only understand by cognition. That sounds all nice and dandy, but how to make all of that concrete? I wanted to get my hands dirty with some code, and obviously doing something identity-related came to mind. I thought about which aspects of claims-based identity could be made intuitive by a multi-colored blinking light. I won’t bore you with a long digression about the process that led me to choose what I picked, and will go straight to my conclusions: I decided to give a color to the identity providers. Say that you have a Web application, and that you outsourced authentication to the Windows Azure Access Control Service. Let’s also say that you accept identities from the following sources: - One or more Windows Azure Active Directory tenants - Yahoo! - Microsoft Accounts (formerly Windows Live ID) If you keep a log you can determine how often your users come from one provider or another, however wouldn’t it be nice to also get an intuitive idea of the mix of users signing in at any given moment? What if, for example, every time you’d walk by your PC you could see a light indicator shining of a different color every time a user from a given identity provider signs in? That would not be very useful to draw conclusions and projections, you need the quantitative data in your logs for that, but for an anxious control freak like me it would be nice to keep an eye on the pulse of the application. With that idea in mind, I headed to the Git repository for Blink(1) to find out how to drive my unit as described. During the various updates about the project it looked like .NET was going to be one of the platform better supported, but something must have shifted during development. The Windows application, which I believe is required for processing the Blink(1) JSON API, does not even build in my system, apparently due to a dependency to a library that does not work on x64 systems (I think I am x64-only since 2007, and so are most of the devs I know). All of the pre-built applications failed to run, complaining that they could not find javaw. I installed JRE; they still complained about the same. I added a JAVA_HOME environment variable with the path: sometime it helps, but still nothing. Finally, I added it to the PATH system variable: the apps stopped complaining about javaw, however they still didn’t work at all. The even log showed nothing. Luckily, there was an exception to all this: the Blink(1) command line tool, which worked great from the very beginning. The command line tool finally allowed me to get some satisfaction from my Blink(1). I experimented with different colors and update times, and I was not disappointed. Also, despite the exposure to rapid flashing I didn’t experience any enhancement in my alpha abilities, which I suspect means I have none… 😉 If anything, it left me with an even greater thirst for playing with the thing. Undeterred, I decided that if the command line was the only thing that worked, then I would have wrapped it and used it as API. After all, it’s not like if I had to do anything that would even go in production. First thing, I fired VS2012 and created an MVC4 application. Then I added a brute-force wrap of the command line tool, exposing only a function which changes the color of Blink(1). I didn’t even bother to copy the exe from its original download location 🙂 public class BlinkCmdWrapper { public static void Fade(Color color) { Process serverSideProcess = new Process(); serverSideProcess.StartInfo.FileName = @"C:\Users\vittorio\Downloads\blink1-tool-win\blink1-tool.exe"; serverSideProcess.StartInfo.Arguments = "--rgb " + color.R.ToString() + "," + color.G.ToString() + "," + color.B.ToString(); serverSideProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; serverSideProcess.Start(); } } Not much to explain there, really. The “rgb” command fades the current color into the specified RGB triplet; the method calls the tool with the necessary parameters in a hidden window. Horribly inefficient, yes; but for seeing some lights blink on my laptop within the next 5 mins, it will do. Then I configured the MVC app to use WIF to outsource authentication to ACS. Thanks to the fact that I already had a dev namespace configured with all the identity providers I needed, and the VS2012 Identity and Access tool, that took about 5 seconds :-). All that was left was to add the logic that switches color according to the original identity provider of incoming tokens. WIF offers a nice collection of events which fire at various stages of the authentication pipeline: a good candidate for this functionality would be the SignedIn event. Discovering the identity of the original IP is pretty trivial for tokens issued by ACS, given that the STS graciously adds a claim () meant to convey exactly that information. In the end, the thing that resulted most difficult was to choose a color for every provider 🙂 In short, I added the following to the global.asax: void WSFederationAuthenticationModule_SignedIn(object sender, EventArgs e) { // retrieve the identity provider claim Claim idpClaim = ClaimsPrincipal.Current.FindFirst(""); // no IP claim, but signin succeeded; it might be a custom provider if (idpClaim == null) { BlinkCmdWrapper.Fade(Color.White); } else switch (idpClaim.Value) { case "uri:WindowsLiveID": BlinkCmdWrapper.Fade(Color.Pink); break; case "Yahoo!": BlinkCmdWrapper.Fade(Color.Green); break; case "Google": BlinkCmdWrapper.Fade(Color.Yellow); break; default: if(idpClaim.Value.StartsWith("Facebook")) BlinkCmdWrapper.Fade(Color.Blue); else if(idpClaim.Value.StartsWith("")) BlinkCmdWrapper.Fade(Color.Azure); else BlinkCmdWrapper.Fade(Color.Red); break; } } Once again, very straightforward. The method looks up the IP claim. If it isn’t there, the provider might not have a rule to add it, or the application might be trusting another STS instead of ACS; either ways the SignedIn succeeded, hence we need to signal something: I picked white as the most neutral behavior. If there is an IP claim: in the case of tokens from Microsoft Accounts, Yahoo! or Google the expected value is fixed (hence the switch statement). In the case of Facebook or Windows Azure Active Directory what is known is how the string begins, hence the cascading ifs in the default clause. Well, that’s pretty much all that is required to achieve the effect we want. Let’s hit F5 and see what happens. On the left side you can see an app screenshot, on the right the status of the Blink(1). At first launch you get the classic HRD page from ACS. The Blink(1) is still off, no sing in took place yet. Let’s hit Try Research 2, a Windows Azure Active Directory tenant, and authenticate. …aand – it’s a kind of magic – the Blink(1) comes alive and shows an appropriate azure glow! Want to see that changing? Sure. Copy the address of the app (localhost+port) and open an in-private instance of IE (or an instance of Firefox). Paste the address in, and this time sign in with Facebook: Yes, the picture does not show a striking difference, but I can assure you that the indicator is now of a much deeper blue. Want to see more difference? Close the extra browser, re-open it and repeat the above but choosing Windows Account: Nice and pink! Repeat the above for Yahoo: and it’s green! You get the idea. The above is a good proof of concept of the original idea. Is it a good solution, though? Well, no. Apart from the ugly workaround of spawning a process for wrapping the command line tool, there are multiple shortcomings to deal with: - The default fade values are too long, rapid events would not be displayed without some adjustments (pretty easy) - Subsequent, adjacent sign-ins of users from the same provider would not be displayed. Blink(1) should probably blink rather than fade - The token validation would take place in the cloud or in some remote HW. The events would have to be transported down to the machine where the Blink(1) is plugged, possibly via some kind of queue. ServiceBus seems a good solution here But you know what? My goal here was to play with my new Blink(1), and that I did 🙂 Yes, it’s 3:17am and I am a happy tinkerer: I can call it a night. Thanks to the ThingM guys for having created a really nice item. The Kickstarter process is obviously over at this point, but ThingM now offers Blink(1) in their regular store, at exactly the same price. Looking forward to more hacking when the .NET support will catch up! .
https://blogs.msdn.microsoft.com/vbertocci/2012/12/09/fun-with-blink1-and-claims-unboxing-and-identity-providers-synesthesia/
CC-MAIN-2017-22
en
refinedweb
CodePlexProject Hosting for Open Source Software Hi I'm writing a module that needs to know the list of available roles. At the moment I reference the Orchard.Roles\bin\Orchard.Roles.dll in my project so that I can access IRepository<RoleRecord> in the driver and then package the roles up into the view model. Is it a bad idea to reference a module dll from another module? What's the alternative? Thanks Gareth That should be fine if you also declare the dependency in the module.txt file but you might want to use interfaces instead of concrete types as much as possible when bringing in dependencies. Thanks. When you say "use interfaces instead of concrete types" are you referring to IRepository<RoleRecord> or are you speaking in general terms? I can't see a way of using RoleRecord as an interface (other than object!). Here is the code that uses the repository : public class ContentViewPermissionDriver : ContentPartDriver<ContentViewPermissionPart> { private readonly IRepository<RoleRecord> _rolesRepository; public ContentViewPermissionDriver( IRepository<RoleRecord> rolesRepository) { _rolesRepository = rolesRepository; } protected override DriverResult Display(ContentViewPermissionPart part, string displayType) { return base.Display(part, displayType); } protected override DriverResult Editor( ContentViewPermissionPart part) { // Load the full list of roles so we can present at the front end var oAllRoles = _rolesRepository.Table.ToList(); if( part.RoleId == 0) { // Default to the Anonymous role, fair assumption that it will be called "anonymous"? Can't see T("Anonymous") anywhere important // Also, is it a fair assumption that the anonymous role will exist? part.RoleId = (from role in oAllRoles where role.Name.ToLower() == "anonymous" select role.Id).SingleOrDefault(); } var oRoles = from role in oAllRoles orderby role.Name ascending select new SelectListItem() { Selected = (role.Id == part.RoleId), Text = role.Name, Value = role.Id.ToString() }; ContentViewPermissionViewModel oViewModel = new ContentViewPermissionViewModel() { Roles = oRoles.ToList(), PermissionPart = part }; return ContentPartTemplate( oViewModel, "ContentViewPermissions.Fields").Location("primary", "3"); } protected override DriverResult Editor(ContentViewPermissionPart part, IUpdateModel updater) { updater.TryUpdateModel(part, Prefix, null, null); return Editor(part); } } ps: Disregard the fact that I'm using SelectListItem, I'm changing that to be check boxes so you can select multiple roles In general. One thing to understand about roles is that it is not a given that all Orchard sites will use them. So depending on the universality your module aims at, you may want to make your dependency to roles more or less rigid. It seems like what you are building is designed on top of the idea of roles in a very fundamental way, so the hard dependency seems fine to me. Ah I see. I can make different parts then; one for roles, one for users and perhaps even one for an ip address white list which might be useful Yes, you could, although the role-based one seems the most useful? Certainly yes, roles are more useful and easier to work with, I'm just thinking ahead somebody not using roles might want to limit a content item/s to a specific user/s (one day in 2018, in error). Perhaps I think ahead too much and I should reread the Good Enough Is Fine section in REWORK! Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
https://orchard.codeplex.com/discussions/229193
CC-MAIN-2017-22
en
refinedweb
;20 21 import java.util.Comparator ;22 23 /**24 *25 * @author Martin Matula26 */27 public class AnonClassTestClass {28 public void test() {29 Object comparator = new Comparator () {30 public int compare(Object o1, Object o2) {31 return 0;32 }33 34 public boolean equals(Object o) {35 return o == this;36 }37 38 public int hashCode() {39 return super.hashCode();40 }41 };42 }43 }44 Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ |
http://kickjava.com/src/org/netbeans/test/codegen/AnonClassTestClass.java.htm
CC-MAIN-2017-22
en
refinedweb
CENTRAL INTELLIGENCE AGENCY washingTon 2b. o. c. OFFICE OF THEECTOK (VNTELUGENCEt f'OH: Deputy Under Secretary of State for Economic Affairs Hbtes on US-Polish Trade Talks The Polish import require- for the perion enrougn Juneas: lA million metric tons to cover domestic consumption deficit illion metric tons to mee^ their stockpile"to reduce" or "eliminate" (both terms used by Poles) compulsoryrain illion metric tons of grain. The above grain import requirement for domestic contuj.ptionillion metric tons seems inflated if it represents ar; annual Itercent over recent annual ^rain ir.ports and exceeds planned grain imports6 Thus, wc may assume that the total grain import requirementill-on tone is on the high side. 2. Poland has already conirac-ed for deliveryillion tons of grain by The present proposal toons of grain in. loan package would place Polandosition to eliminate compulsory deliveries, if it chose, on the basis of the stated requirements and the present level of import contracts. 3> Etolish grain imports for recent years haveonsistent levelillion metric tons annually. We anticipate that this level "rf.ll be maintained ; -DATE: 4 rain* 1 (Approx. ^ * Polandet exporter of grain Should thedministration find that the peasants deliver the state's urban requirements for grain promptlyree delivery or reduced ccanpuJ3ory delivery system,illion ton stockpile may be partially dravn down. To the extent tbat Poland is capable of providing -jatlcfactory productiono peasants and of providing animal feed concentrates (high protein feeds to supplementt should be possible to Increaseroduct exports enough to defray the cost of grain imports. V. Polish domestic procurement of grainhannel;;; l) compulsory delivery at fixed prices,eliverieseasantsegotiated higher price, andreerices approximately equal to average prices on contr ct deliveries. The absolute level of compulsory delivery of grain and the share total state procurement of grain obtained from compu sory deliveries isin the table below: Compulsory GrQln Deliveries infa-57 Percent of State PurchasesMetricForm of Coriipulsory Deliveries 5- Although the Poles claim that an announcement on compulsory delivery levelsust be made by June of this year, past experiencea more flexible deadline is possible. Compulsory delivery quotas for 1 crop year (and to continueere announced In No oubeequent announcement of compulsory delivery levies was made until5 at which time it was indicated that* levies would be continued throughrop year. Announcement fore.'ison was not made until This announcenent wnu delayed becouue of the uncertainty generated by the chmfledministration tn the autumn and early winter ftisont production plane would almost certainly not be crystallized before July or August because the Polish gruin crop consists of winter rye and vheat which it seeded in late eumticr and early autumn and harvested the following late spring and early summer. KUHBKrOriginal document. Comment about this article or add new information about this topic:
http://www.faqs.org/cia/docs/101/0001111298/TECHNICAL-NOTES-ON-US-POLISH-TRADE-TALKS.html
CC-MAIN-2017-22
en
refinedweb
Today as the first day of the 21 year of my life! I wanted to show you how to connect Arduino to sensors, fetch data and show 'em on 16x2 LCD - as an example you can get your room's temperature and light density and view them on lcd. Step 1: What You Need? 1. Smile :-) 2. Arduino Board (here I used UNO but feel free to choose your own) 3. LM35 Temperature Sensor 4. LDR 5. 2.2 K ohm Resistor (x1) 6. 10 K ohm Potentiometer 7. 16x2 Line LCD Display 7. Bread Board --------------------------------- Softwares ---------------------------------------------- 1. Arduino IDE Step 2: Wiring Potentiometer: One of the ends to +5 Volts and the other to the Ground (GND), Connect LCD VO middle pin of the potentiometer. LM35: Connect Arduino 5 Volt to Pin 1 (Based on the Picture), Connect Pin 2 to A1 (Analog In) Arduino Board, Connect Pin 3 to GND. Connect LDR and 2.2k Resistor in series. Connect LDR pin to 5 Volt, Common Pin (between LDR and 2.2k Resistor) to Arduino A0 Pin and Connect 2.2k Resistor float pin to GND. Step 3: Arduino Code Copy the code below to new arduino document. Select your Board and Port, then see the results. #include <LiquidCrystal.h> LiquidCrystal lcd(12, 11, 5, 4, 3, 2); void setup() { lcd.begin(16, 2); } void loop() { double a = analogRead(A0); a = (a / 1023)*100; String str; str=String(a); lcd.setCursor(0, 0); lcd.print(" "); //SIMPLE WAY TO CLEAR LCD lcd.setCursor(0, 0); lcd.print("LUX: " + str + "%"); a = analogRead(A1); str=String(a); lcd.setCursor(0, 1); lcd.print(" "); lcd.setCursor(0, 1); lcd.print("TEMP: " + str); delay(1000); } Step 4: Ready, Set, Done Now you're all set. Give it a go. Here you can use other analog sensors too. Make your own and publish it. Wish you good luck.
http://www.instructables.com/id/Arduino-Room-Status/
CC-MAIN-2017-22
en
refinedweb
IBM Announcements on Chip Design/Nanocommunications 111 mr was one of the folks who wrote about some IBM scientists who have discovered a way to transport information on the atomic scale that uses the wave nature of electrons instead of conventional wiring. The new phenomenon, called the "quantum mirage" effect, may enable data transfer within future nanoscale electronic circuits too small to use wires. Big Blue also unveiled some new chip technology, called "Interlocked Pipelined CMOS" that starts at 1 GHz, and will be able to deliver between 3.3 - 4.5 Ghz. "Interlocked Pipelined CMOS" (Score:1) Advantages of 128 bit word length (Score:1) For the small portion of the population who don't regularly calculate cross products of 7-D vectors, the main advantage is that "128 bit computer" sounds better than "64 bit computer". Re:(OT)Where are the damned DeCSS Source T-Shirts? (Score:1) eBay has a whole section for terminals. (Score:1) - A.P. -- "One World, one Web, one Program" - Microsoft promotional ad Wanna know why? (Score:2) ISO-9K is a great way to turn any company into a shithole. - A.P. -- "One World, one Web, one Program" - Microsoft promotional ad Next revolution (Score:2) Ethernet (Score:1) Seriously though, all this new tech just plain rules. I can't wait to see what things are like when I'm 90! --- Don Rude - AKA - RudeDude Re:Ready Set Go... (Score:1) The guy you're flaming was complaining that the technology moves too fast for the user to keep up, or be able to safely upgrade. And I, for one, agree with him. I tend to upgrade every two years or so, but if I upgraded componentwise, I'd want a motherboard that lasted. And you made a lot of assumptions about that guy, alright? Think about it. If I had a few computers lying around (I do), and I bought a new one, I might want to build a better second one out of the remaining components. I tend to reuse old hard drives, because there are standards that allow this. What about chips? Regular pentium-style ZIFF sockets were standard for a long time. Now we have all kinds of weird proprietary cards, buses, RAM, whatever. I know enough not to mix random RAM, but the complexity has definitely gotten out of hand for all but the up-to-date hardware hacker, and that isn't me. --- pb Reply or e-mail; don't vaguely moderate [152.7.41.11]. Re:Ready Set Go... (Score:1) Actually, I haven't messed with it, I went from a P133 to a K6/300, and my next purchase will be... well, whatever has the best price/performance ratio in x86-land by mid-summer, probably. But like I said, hardware hacking has gotten complicated enough for me to stay out of it, because I haven't been keeping up. It used to be, you didn't miss much by not keeping up, like I said. IDE and SCSI, ATAPI cdrom drives, floppy controllers, ISA and PCI, Serial and Paralell Ports... and now they have to mess it all up with a bunch of proprietary, non-standard technologies. If there were an open spec, I know I wouldn't have to wait this long for decent support under Linux. But no, we've got incompatible video cards, incompatible processor extensions, incompatible media, incompatible I/O... Obviously there's an advantage to standardizing the hardware platforms and the software interfaces. I'd be happy with maybe two, well-documented, competing standards in each separate domain. But no... --- pb Reply or e-mail; don't vaguely moderate [152.7.41.11]. Re:Wanna know why? (Score:2) Hmmm... I tend to disagree. ISO-900x is just a means of proving you have documented all your processes. All it really does is show that the company is a shithole earlier on by pointing out through documentation where they are headed. Six sigma... now <b>there</B> is a tedious thing to go through. Re:Makes sense (Score:1) I know this reply is too late to catch the moderators eye, but I hope Mr. Hard_Code at least notices it. Most commodity CPUs (and many other chips) are actually pipelined. They do some amount of work on the first clock tick, and send the results to another part of the chip, next tick they do the same amount of work on the new data, and another part of the chip works on the results of the the last cycle. A "modern" x86 CPU does that 8 to 18 times to handle each instruction. There are other wrinkles to it too. When you design a CPU (in my case a "play" CPU much like the really old PDP-8) you use software that does a layout and tells you the critical path (most any VHDL synt tool will do). That's the slowest part which forces the rest of the circut to be clocked slower. When you find it there are three choices: I don't know if the 68000 was pipelined. The 68010 was, I think it had three pipe stages (and no cache, although the loop-mode was a lot like a 3 instruction I-cache). Some RISC CPUs have pretty long pipelines, but the moderen Intels tend to be longer, in part because decode takes as many as three pipe stages (it does on the K7, not sure if the PII/PIII does it in two or three). A RISC decode is only one pipe-stage, and frequently other crap is thrown in too (like branch prediciton forwarding logic). By way of contrast the IBM PowerAS (a PowerPC like CPU) has a very short pipeline, I think about 6 stages (and thanks to the branch forwarding logic, branch mis-predict penalitys are something like only 2 to 4 cycles). P.S. I'm not a hardware guy. I'm a software guy, and a harware wannabe. Re:"Interlocked PipelinedCMOS" (Score:2) It's got to be more then that. The TI SuperSPARC did that in '95 or so. Most of the CPU ran at (I think) 50Mhz, but the register file at 100Mhz. In that case (and all similar cases I know of) all the clocks are multiples of each other (no relitavly prime clock rates). More over if the decode unit runs faster then the dispatch unit there is no useful gain. The dispatch unit has to be fed decoded instructions. The same is true for many (but not all) other parts of the CPU. I think (with no proof, and no help from that watered-down article) that most of the parts in this chip run at the same speed (say 1Ghz). They each have their own 1Ghz clock distribution net, and they are not sync'ed with each other (so the ALU could see start of clock while the decoder is half way through a clock, and the renamer has just seen the end of a clock pulse). The boundry between each clocked unit must have a small async buffer. That would trade the pain of clock distribution for the pain of having a bunch of async buffering all over the place adding to latency. Given how painful clock distrubution is in really big chips this is probbably a positave tradeoff. At least for latency intolerent workloads. Re:Electron waveguides. (Score:1) WRT tunneling, you're correct that electrons spend a good deal of time in the "mirage" position - it's not a mirage at all, any more than any de Broglie wave is. For instance you could call the peak of the interference pattern in the classic two-slit experiment a "mirage" too since it has an high electron density. The speed of the electrons between foci is definitely sub-light speed. The de Broglie waves themselves may travel FTL (the same old non-locality that gets everybody excited) but as in all of these situations it's not much use. It seems to me if they used a pair of parabolic reflectors similar to microwave dishes, they could get current to flow between foci over relatively large distances, with no hardware needed in between (except for the copper substrate, which is already a conductor - oops). I believe that different beams could cross as well, with little interference. That would be a useful feature, since it could replace circuit traces. It's doubtful whether this arrangement would be very efficient, due to leakage, diffraction, etc., but it's though-provoking. Re:A Question About IBM (Score:2) OTOH, IBM has been noted for their research programs. About 20 yrs ago, there was the big three in terms of corporate research. They were AT&T, IBM, and Exxon. Well Exxon has greatly reduced their research efforts (as had the other major oil companies), AT&T has been split up and then again split up again (Bell Labs is part of Lucent), while IBM has redirected their researchers to perform more applied research. But IBM research is still very impressive. Low temperature super-conductivity was an IBM product that came out their Zurich research facility. Off topic, but Thomas Watson many years ago had the now-famous Think posters put up. I used to have a cartoon in my office that showed the Think poster with a guy saying, "I'll like to, but I have too much work to do." Ross Perot founded EDS (after being an IBM salesman) to provide software for IBM mainframes. Back then, IBM philosophy was to sell hardware, software was just an afterthought. Hmmm, I wonder if anybody else got rich for selling software that ran on IBM hardware. Yup, I'm just rambling. IBM is a "friend" of linux at this moment. They have been very good for the time being. However, as a person who has witnessed the might of IBM in the past, I'm scared of what IBM could potentially do to screw things up. Remember, the enemy (linux) of my enemy (MS) is my friend. Of course, we all live by the ancient Chinese saying/curse, "May you live interesting times." And it still will *just* be fast enough (Score:2) Great. w/clocks newer than w/o clocks (Score:1) Re:Interesting... (Score:2) My question is are the clocks phase locked to a master timing source or are they free running? Re:Fast (Score:2) Quite Exciting!! (Score:1) Nothing like real innovation, is there? It excits me to see technology like this being announced.-Brent How does this help us make smaller circuits? (Score:1) Someone help me make the intellectual leap so that I understand how this can be used to help us build better circuits. Is the idea that we replace wires with really long, eliptical corals? Re:Fast (Score:1) I'm running a Pentium Pro 233.. and it certainly doesn't *feel* outdated. Now, if only I had a fast internet connection to match... A Question About IBM (Score:3) Is it just me, or has IBM made a real turnaround in the last 5+ years? It seems they understand the whole open source movement, they've pretty much ditched they're sorry aptivas, and they seem to be a leader in new technologies. On top of that they've changed the way people percieve them. I remember hearing stories about how they had to wear knee-high black socks to match their black suits long ago, and now I go to an interview with them, and the guy is wearing jeans and a Polo shirt! Honestly, this is one large corporation I have respect for. And there aren't too many of those left now and days. Re:How does this help us make smaller circuits? (Score:1) Disclaimer: I got a C+ in physics -B Re:slashdot (Score:2) Hmmmm... 1: It's the "obscure university" that Alan Turing was a professor at. 2: It's the "obscure university" that built the world's first stored-program computer (the Manchester Mark I/"Baby") 3: It's either very similar or identical technology. 4: They've built the chips. They have prototypes. 5: Funny how everyone jumps up and down in defence of IBM, when they quite happily quote unrelated tech after unrelated tech to prove that Microsoft doesn't innovate... Simon Re:Interesting... (Score:3) It's even less conceptually brilliant, when you see what people elsewhere have been working on - namely wavepipelined architectures. Funny... people just keep on reinventing the wheel... fire... and then they patent it to hell. IIRC, the guys at Manchester University [man.ac.uk] were working on this back in 1989/1990 (or at least they were when I went on a tour of the place...). Back then, it was just called the "wave pipelined RISC chip" - these days, it's the "Amulet". Check it out. It's based on ye olde ARM [arm.com] processor architecture - but the implementation is completely asynchronous -- that is, each individual logic element is clocked separately. Sure, it's still experimental... sure, it's slower than other chips - but it also predates IBM's announcement by about 11 years. Just goes to show - academia ain't entirely useless Links Architectural Overview at Berkeley [berkeley.edu] The Amulet Asynchronous Logic Group at Manchester University [man.ac.uk] Who needs clocks? Bah! Simon Err - quantum EFFECTS (Score:1) #include "disclaim.h" "All the best people in life seem to like LINUX." - Steve Wozniak Quantum efrfects used to ENABLE nanotech (Score:2) #include "disclaim.h" "All the best people in life seem to like LINUX." - Steve Wozniak Re:Fast (Score:1) But for now, IBM.. stick to... (Score:1) ----- Linux user: if (nt == unstable) { switchTo.linux() } Interesting... (Score:3) This was probably quite difficult to implement, but isn't exactly conceptually brilliant. Modern computers already run at different clock rates internally. Your disk I/O bus runs at one speed, your video processor runs at another speed and the CPU still spends a lot of time waiting for stuff to come down the system bus from memory. As far as I can see, IBM have scaled this down to a single chip, which will increase overall throughput considerably. Difficult to do, very worthwhile, but conceptually all they have done is to get the latency issues into a smaller space. OTOH, this could lead to an architecture with considerably lower power consumtion, which is definitely worth doing. The bit about 'quantum mirages' has already been discussed on 7-dimensional cross-product (WAY off-topic) (Score:1) Remember how to get the cross-product manually? You make a matrix like this: | i. j. k. | | x1 y1 z1 | | x2 y2 z2 | ...and take the determinant. To get a similar matrix with 7-dimensional vectors, you'd need six of them. But I don't know how much use that would be. -- Patrick Doyle That doesn't make any sense (Score:1) What do you mean by a transaction? And what does word size have to do with how many of them you can do per second? -- Patrick Doyle Doubling word size is not necessarily best (Score:1) However, 64-bit is definitely worthwhile over 32-bit because 32 bits can only address 4GB. Under Linux, for instance, you only get 3GB of those because the last GB is reserved for the system. This places a hard limit on the size of things you can map into your address space. 64 bits can address 16EB (that's Exabytes), which should stave off Moore's law for another 50 years or so. -- Patrick Doyle When... (Score:1) I suspect scientists are working on it. 'Cause eventually, we're going to have to start using quantuum states and tweeking the fundamental nature of the universe to build processors fast enough keep up with the computational requirements of Windows 2020... Re:Makes sense (Score:1) With multiple clocks, everything is working asynchronously at the limit of its own circuit. For simple circuits this will be very fast. Jazilla.org - the Java Mozilla [sourceforge.net] Makes sense (Score:2) Jazilla.org - the Java Mozilla [sourceforge.net] Re:Wanna know why? (Score:1) Hmmm... you know, maybe that's what the Justice Department could do to penalize Microsoft. Require them to implement the Six Sigma program there, and get all their products compliant. Considering the current state of their software, it would either destroy them when they couldn't do it, or at least slow and bog their releases so much that other companies can somewhat catch up. As it is now, they're, what, point-six sigma? --- Re:Ready Set Go... (Score:1) That's ridiculous. Why do you want the fastest CPU on the market? Why do you honestly need it? What's that? You don't need it? You just want to brag to your other 13 year old friends that your computer is faster than theirs? Oh, tough luck to you. Other people, people who are trying to get REAL WORK DONE, are actually happy that technology is moving quickly. Maybe if you can't handle it, you should go buy a Apple Macintosh. I hear they don't innovate very often. You can have a top-of-the-line computer for years and years. Geez... I have a dual cpu Pentium III 450 MHz system, and according to my research, there isn't anything out there much more than 50% faster than it (say, a 733 MHz Coppermine in an i820 motherboard). When dual and quad CPU Coppermine systems become available, I *might* upgrade to one of those. If I *need* the speed increase, that is. Why upgrade when all I could get is a 50% speed increase, though? It'd cost me hundreds of dollars. All you need to do is buy a decent computer (Dual or quad CPUs, Ultra2 SCSI, Asus motherboard), and you'll be set for *years*. No need to upgrade every month. It might cost more in the short run, but it'll last a hell of a lot longer than that Celeron/EIDE based computer you bought for $100. Re:Fast (Score:1) I'd rather see a 64 bit, 66 MHz PCI bus in consumer motherboards. There are increasingly more peripherals that exceed the bandwidth of the 32 bit, 33 MHz PCI bus. And they're getting cheaper every week. Adaptec Ultra 160 SCSI adapters are only ~$250. I'd buy one if I could actually handle the bandwidth... Re:Ready Set Go... (Score:1) Oh, come on. It's not that hard to keep up to date with new stuff. Slot 1 CPUs go in... slot 1! Slot 1 has been around for years now. Do you know why Socket 7 was around for so long? Because AMD used it for so long. Intel abandoned it a loooong time ago for their proprietary Slot 1 architecture. AMD couldn't make Slot 1 CPUs. But all you needed to do was buy any old Slot 1 CPU (from 233 MHz to 600 MHz), and it would work in virtually any Slot 1 motherboard. Is that so bad? No, it is not. Which Slot 1 CPUs don't work in Slot 1 motherboards? The new Coppermine CPUs, if you're unlucky. The Coppermind CPUs will work in many (but not all) Slot 1 motherboards! For years now, you could have used the same Slot 1 motherboard, just upgrading CPUs. What are you complaining about? That your 486 doesn't work in a Pentium II motherboard? Oh well.... time goes on. Re:A Question About IBM (Score:2) Electron waveguides. (Score:2) I wonder if the "mirage" could be interpreted as the electrons of the cobalt atom tunneling to the image location and spending a fraction of their time there? That less-than-half strength might be because the nucleus is still at the other location and makes the electron density "prefer" that region because it is lower energy, due to the attraction of the positive charge. I also wonder what is the speed of propagation of the effect? Switch a gate's output by dropping an electon into an electron trap at one end of the waveguide, and it appears (at, say, 50% density) at the other end, and affects the logic there. How long does it take to happen? Does it exceed the speed of signals in a wire? (That's a very small fraction of lightspeed on a chip, where the wire resistance and stray capacatance form a delay line.) Does it approach that of light in vacuum? Does it EXCEED that of light in vacuum? (Even if the total system can't send signals faster than light in emptyness, which is a very slight improvement on light in quantum vacuum.) Whatever it is, my bet is that it will happen at tunneling speed. Re:School computers (Score:1) but the apple II e's that were in my highschool's computer lab might not be state of the are anymore Re:Fast (Score:1) Perhaps I'm not seeing something, but I can think of very few situations in which 128-bits is a definite advantage over 64. Bits != total computational power, people. Re:Slashdot has it (Score:1) appears again... but perhaps what is scarier is: slashdot + (anti)slashdot -> geocities +14.3 KeV Here's another.... (Score:1) --- But.. (Score:1) --- Re:i think this is bigger than its made out to be (Score:2) I'd much rather have a cluster of P3 or Athlons. Re:Fast (Score:2) Maybe if AMD... (Score:1) Sigh. Esperandi Re:Ready Set Go... (Score:1) -lol- You obviously haven't been keeping up with the news. Apple's G4s are among the fastest things out there. Kean some more references: (Score:3) Ok the reference for this work is: H. C. Manoharan, C. P. Lutz & D. M. Eigler, Nature403, 512-515(2000). In this experiment a few Cobalt atoms were deposited on a Copper surface. Using a scanning tunneling microscope the Co atoms were gently dragged into an elliptic(coral) structure, and one Co atom was placed at the focus of the ellipse. (The images of this stuff are gorgeous and more cool STM images of atoms and atomic maniputation can be found at the STM Image Gallery [ibm.com]). Due to the magnetic nature of the Co atom electrons near the atom tend to align their spins with the Co magnetic field screening the magnetic moment. This local phenomina can be imaged by the STM, the surprising result is that another mirage image appears at the second focus of the ellipse. This suggests some sort of long range electon ordering. These experiments are being done with a low temperature ultra-high vacuum stm (this stuff is damn hard) and to reproduce these same results in a next generation processor as a means to transport data is unlikely in the near future. Nevertheless, these results will have a great effect in our understanding of macroscopic quantum systems and ordering. Re:Ready Set Go... (Score:1) Re:Fast (Score:1) Slashdot has it (Score:4) Re:(OT)Where are the damned DeCSS Source T-Shirts? (Score:1) Nick Messick nick@trendwhore.com Re:How does this help us make smaller circuits? (Score:1) Re:Is this actually a Big Deal(tm) (Score:1) slashdot (Score:1) If you will excuse me, I have a computer lab to attend to. Fast (Score:2) This stuff is kinda of cool though, maybe we'll get to see some nice VR stuff and better speech recognition. Eventually the hardware will be fast enough to run windows. I would have liked to have seen intel go to a 128 bit architecture instead of 64 it would have lasted longer. Re:Interesting... (Score:1) ex-employee btw Re:Quantum efrfects used to ENABLE nanotech (Score:1) The IBM engineers are really ENGINEERS. They are thinking about solutions and how to address the problem *using* the boundaries that nature has given us rather than attempting to find ways around them. also I didn't realise that K.E.D. did physics as well as write books. you'd get a moderation if I hadn't already posted to this story. Re:slashdot (Score:1) btw presumably you are at Umist/manchester. Top place. Re:A Question About IBM (Score:2) all he did was make the technology and engineers they always had the focus Re:School computers (Score:1) Let me know if they plan on getting rid of them... I'm looking for a couple of text terminals to hook up to my linux box. I'm looking for something that can emulate a DEC vt100... but I can't find any in my area (north Jersey). q Re:eBay has a whole section for terminals. (Score:1) q Asynchronous processors (Score:1) (Place where the first computer was built 51 years ago) Really cool stuff Amulet Processors [man.ac.uk] Re:Asynchronous processors (Score:1) at approximately the same time as me. The Re:Asynchronous processors (Score:1) Also the work is still continuing with other students and lecturers. Just because some of the original peole left doesn't mean the work will stop. Quantum mirage story, again? (Score:1) Re:Fast (Score:1) 64-bit numbers in parallel, or perhaps 4 32-bit numbers Where have you been, altivec does just that (at least for the 4x32bit stuff). Re:Fast (Score:1) It has always been the case that once the computer's competency is there, the applications arrive... Way back in the mid-60's my father took me to an open house at IBM, and proudly demonstrated that the computer could add 2+2 lightning-fast. I asked why that was necessary, since I could do the same thing (ok, I was young once, too!).... If you want to know what the new processors will be used for (in series, no less!), keep up with math! Learn about the complexities of modeling visual information (animation on a G4!), exploring "chaotic" (or "complex") domains, etc. It's the new stuff we'll be able to DO that make new processors (and etc.) so exciting! Re:Advantages of 128 bit word length (Score:1) However, cross products of 2 vectors are only defined on 3 dimensions, how can you uniquely have something perpendicular to 2 vectors in 7 dimensions?!! Re:If my computer... (Score:1) Not only that, if it crashes and you lose data, can you go into the other universe and get the data back? If so, how do you get into the other universe to do so ;-) Re:Is this actually a Big Deal(tm) (Score:1) <sigh> Look, Moore's law is an observed phenomenon, not a fundamental rule, and it is observed in the industry as a whole, not necessarily within individual companies. If Intel doesn't come up with technologies allowing them ot go to 3.2 GHz within 3 years, then no, they won't have a 3.2 GHz then. It's by no means inevitable that they will come up with such technologies. Here's a thought on this 'multi-clock' CPU of IBM's: What clock will they advertise it at? Presumably the clock of the fastest part. Still - maybe, just maybe, we'll start seeing marketing move away from clock speed as a meaningful measurement of chip performance. We can always hope. Is this actually a Big Deal(tm) (Score:1) Re:Is this actually a Big Deal(tm) (Score:1) 800 * 2 = 1600 in 18 months, then 1600 * 2 = 3200 in another 18 months. 18 + 18 = 36 = 3 years. Re:Is this actually a Big Deal(tm) (Score:1) Re:A Question About IBM (Score:2) On the other hand, they still are a giant business. They do flexibility and open source because they think flexibility and open source work-- it's a business model and not a philosophy. Companies this big don't have philosophies, no matter how many True Believers they have on staff. Re: Flaimbait? I think not. (Score:1) If my computer... (Score:3) I can see the error messages for Win2010 now: "Error - user32.exe performed an illegal operation in this universe - please continue in another universe or restart..." smarter than me (Score:1) Big Blue? (Score:1) [badassmofo.com] Re: Flaimbait? I think not. (Score:1) [badassmofo.com] Re:Ready Set Go... (Score:1) Behold the power of ONE Re:School computers (Score:1) Ready Set Go... (Score:2) School computers (Score:3) i think this is bigger than its made out to be (Score:1) Re:How does this help us make smaller circuits? (Score:1)
https://slashdot.org/story/00/02/06/2052259/ibm-announcements-on-chip-designnanocommunications
CC-MAIN-2017-22
en
refinedweb
Defining a new extension point Just as Hudson core defines a set of extension points, your plugin can define new extension points so that other plugins can contribute implementations. This page shows how to do that. First, you define your contract in terms of an abstract class (you can do this in interfaces, too, but then you'll have hard time adding new methods in later versions of your plugin.) This class should implement the marker hudson.ExtensionPoint interface, to designate that it is an extension point. You also need to define the static "all" method (the method name doesn't really matter, but that's the convention.) The returned ExtensionList allows you discover all the implementations at runtime. The following code shows this in a concrete example: /** * Extension point that defines different kinds of animals */ public abstract class Animal implements ExtensionPoint { ... /** * All registered {@link Animal}s. */ public static ExtensionList<Animal> all() { return Hudson.getInstance().getExtensionList(Animal.class); } } In addition to these basic ingredients, your extension point can implement additional interfaces, extend from another base class, define all sorts of methods, fields, constructors, and etc. Also, this convention is only necessary when you need to discover the implementations at runtime. So if your extension point consists of a group of several classes and interfaces, normally only the top-level one needs to follow this convention (such an example can be seen in hudson.scm.ChangeLogParser in the core — ChangeLogParser implementations are always created by hudson.scmSCM implementations, so ChangeLogParser doesn't have the all method while SCM has it. Enumerating implementations at runtime The following code shows how you can list up all the Animal implementations contributed by other plugins. for (Animal a : Animal.all()) { System.out.println(a); } There are other convenience methods to find a particular instance, and so on. See hudson.ExtensionList for more details. Implementing extension points Implementing an extension point defined in a plugin is no different from implementing an extension point defined in the core. See hudson.Extension for more details. @Extension public class Lion extends Animal { ... } Doing Describable/Descriptor pattern If you are going to define a new extension point that follows the hudson.model.Describable/hudson.model.Descriptor pattern, the convention is bit different. You need to do this (instead of the simple extension point like Animal above) if: - you want to leverage the form handling - you need to define class-level operations, not just instance-level operations For this, first you define your Describable subtype and Descriptor subtype. The all method is implemented slightly differently, and you provide the default getDescriptor implementation. public abstract class Food implements Describable<Food>, ExtensionPoint { ... public FoodDescriptor getDescriptor() { return (FoodDescriptor)Hudson.getInstance().getDescriptor(getClass()); } public static DescriptorExtensionList<Food,FoodDescriptor> all() { return Hudson.getInstance().<Animal,AnimalDescriptor>getDescriptorList(Food.class); } } public abstract class FoodDescriptor extends Descriptor<Food> { // define additional constructor parameters if you want protected FoodDescriptor(Class<? extends Food> clazz) { super(clazz); } protected FoodDescriptor() { } ... }
http://wiki.eclipse.org/index.php?title=Defining_a_new_extension_point&oldid=343494
CC-MAIN-2017-22
en
refinedweb
Today, two more subtly incorrect myths about C#. As you probably know, C# requires all local variables to be explicitly assigned before they are read, but assumes that all class instance field variables are initially assigned to default values. An explanation of why that is that I sometimes hear is “the compiler can easily prove that a local variable is not assigned, but it is much harder to prove that an instance field is not assigned. And since the class’s default constructor automatically assigns all instance fields to default values, you don’t need to do the analysis for fields.” Both statements are subtly incorrect. The first statement is incorrect because the compiler in fact cannot and does not prove that a local variable is not assigned. Proving that is (1) impossible, and (2) does not give us any useful information we can act upon. It’s impossible because proving that a given variable is assigned a value is equivalent to solving the Halting Problem: int x; if (/*condition requiring solution of the halting problem here*/) x = 10; print(x); int x; If what we wanted to do was prove that x was unassigned then we would have to at compile time prove that the condition was false. Our compiler is not that sophisticated! But the deeper point here is that we’re not interested in proving for certain that x is unassigned. We’re interested in proving for certain that x is assigned! If we can prove that for certain, then x is “definitely assigned”. If we cannot prove that for certain then x is “not definitely assigned”. We’re only interested in “definitely unassigned” insofar as “definitely unassigned” is a stronger version of “not definitely assigned”. If x is read from when it is “not definitely assigned”, that’s a bug. That is, we’re attempting to prove that x is assigned, and our failure to prove that at every point where it is read is what motivates the error. That failure could be because of a bona fide bug in your program, or it could be because our flow analyzer is extremely conservative. For example: int x, y = 0; if (0 * y == 0) x = 10; print(x); int x, y = 0; You and I know that x is definitely assigned, but in C# 3 the compiler is deliberately not smart enough to prove that. (Interestingly enough, it was smart enough in C# 2. I broke that to bring the compiler into line with the spec; being smarter but in violation of the spec is not necessarily a good thing.) This example again shows that we do not prove that x is unassigned; if we did prove that, then clearly our prover would contain an error, since you and I both know that x is definitely assigned. Rather, we fail to prove that x is assigned. This is an interesting twist on the believers vs skeptics argument that goes like this: the skeptic says “there’s no reliable evidence that bigfoot exists, therefore, bigfoot does not exist”. The believer says “absence of reliable evidence is not itself evidence of absence; and yes, bigfoot does exist”. In both cases, reasoning from a position of lacking reliable evidence is seldom good reasoning! But in our case, it is precisely because we lack reliable evidence that we are coming to the conclusion that we do not know enough to allow you to read from x. (The relevant principle for tentatively concluding that bigfoot is mythical based on a lack of reliable evidence is “extraordinary claims require extraordinary evidence”. It is reasonable to assume that an extraordinary claim is false until reliable evidence is produced. When overwhelmingly reliable evidence is produced of an extraordinary claim — say, the extraordinary claim that time itself slows down when you move faster — then it makes sense to believe the extraordinary claim. Overwhelming evidence has been provided for the theory of relativity, but not for the theory of bigfoot.) The second myth is that the default constructor of a class initializes the fields to their default values. This can be shown to be false by several arguments. First, a class need not have a default constructor, and yet its fields are always observed to be initially assigned. If there is no default constructor, then something else must be initializing the fields. Second, even if a class does have a default constructor, there’s no guarantee that it will be called. Some other constructor could be called. Third, the field initializers of a class run before any constructor body runs, therefore it cannot be the constructor body that does the initialization; that would be wiping out the results of the field initializers. Fourth, constructors can call other constructors; if each of those constructors was initializing the fields to zero, then that would be wasteful; we’d be unneccessarily re-initializing already-wiped-out fields. What actually happens is that the CLI memory allocator guarantees that the memory allocated for a given class instance will be initialized to all zeros before the constructor is called. By the time the constructors run the object is already freshly zeroed out and ready to go. Fifth, local variables are also always initialized by the CLI to default values, so nothing in particular follows from the statement “since the [something] automatically assigns all instance fields to default values”. I seem to recall that the local initialization behaviour is configurable; you can turn it off if you don’t want the perf hit. — Eric @Random832 I’ve always wondered: when you write .locals init in MSIL, CLI guarantees the locals to have been initialized upon method entry, so why does C# still mandate users to definitely assign a value to the locals? More often than not, you might want to omit writing the initialization because the default values are exactly what you want. @raven I seem to recall reading that this was a decision made because the use of an uninitialized local variable is most often associated with a logic error, rather than a desire to use the default value. I wonder though if that means the same case can be made about fields in a class? I think so, Greg. But field initialization is much more complicated, that I’m not sure it would be reasonably possible for the compiler to determine that a field is definitely assigned in all of the common usage cases. The most common cases of local variable initialization are understood by the compiler, but fields are assigned by field initializers and constructors, and the constructors may call other constructors in the same class or in other classes. It’s way simpler just to rely on the CLR requirement that heap memory is zeroed before use. @Eric: > I seem to recall that the local initialization behaviour is configurable; you can turn it off if you don’t want the perf hit If you drop "init" from ".locals init", then locals won’t be initialized, but then the resulting code will be non-verifiable (or at least ECMA CLI spec says so – I’m not sure if .NET will actually treat it as such, since it relaxes a few other overly stringent ECMA rules when it comes to verification). Now, that’s interesting: the following fragment prints out 0, but… namespace SomeProgram { enum TEST { One = 1, Two = 2, Three = 3 }; class Program { static TEST test; static void Main(string[] args) { Console.WriteLine(test); } } } …but 0 is an invalid value for the enum TEST, because each of its member is assigned a value: 1, 2, and 3. Obviously, some behind-the-scene conversion to int is taking place to facilitate the zeroing out of the class member variables mentioned in the post… Would it not be possible to initialize the enum member to one of its valid values here, say, to the minimal one? Every enum is, in turn, an instance of the Enum class: isn’t it possible to modify its default constructor to either make a decision based on the integer equivalent of the values, or to throw an exception and/or generate a compiler-time errror when no default value is defined? And, qiute apart from that, there is another point to explain why constructors are not the primary member initializers: what about the static members? They may be accessed before any instance of the class is created, so something other than the class’ constructor(s) must be used to initialize them. @Denis: See e.g. "It is possible to assign any arbitrary integer value to meetingDay. For example, this line of code does not produce an error: meetingDay = (Days) 42. However, you should not do this because the implicit expectation is that an enum variable will only hold one of the values defined by the enum. To assign an arbitrary value to a variable of an enumeration type is to introduce a high risk for errors." @Denis – additionally, zero is *always* a valid enum value: `TEST t =0;` – compiles fine without any cast. Re the ctor topic – additionally (although it is outside of the language) it is possible for *no* constructor to be invoked, for example via `FormatterServices.GetUninitializedObject` (which is used by `DataContractSerializer` in WCF, among other things). @Eric > I seem to recall that the local initialization behaviour is configurable; you can turn it off if you don’t want the perf hit. But currently the C# compiler always produces ".locals init" doesn’t it? I couldn’t find any switch in csc to configure the behavior for ignoring init. It won’t cause much of any overhead to init the locals anyway, because CLR’s JIT would treat zeroing out a local as dead code if the local is assigned with a new value before its first use; the new definition "kills" the old one. Dead code gets eliminated. > Re the ctor topic – additionally (although it is outside of the language) it is possible for *no* constructor to be invoked, for example via `FormatterServices.GetUninitializedObject` (which is used by `DataContractSerializer` in WCF, among other things). Not to forget about structs, which do not have a default constructor at all (at least ones defined in C#), and for which no ctor is called when you do "new Foo()" or "default(Foo)". Combine the C tradition of declaring locals at the top of the function with outrageously long functions and blocks of code being moved around and you’re asking for (and will receive) bugs. Either the conditional assignment gets moved so that it follows a read (yippee! Especially when it’s a float) or code gets moved in between the declaration and the first assignment that prevents execution of the first assignment. I guess sometimes you’ve gotta make things dumber (e.g., the C# compiler) to prevent undue cleverness from wreaking havoc. The code that evaluated the condition must have been quite a branch? Would int y; if ( StaticFuncThatAlwaysReturnsTrue() ) y = 0; have compiled? Time to crack open another scratch project to see… Personally, I care much more for the behavior to be well-defined; otherwise it may be as complex or as simple as is reasonable (which is of course a matter for discussion, but that’s another discussion). The reason is obvious: if I write some code, I want to be able to validate it against the spec and know that it compiles on any C# compiler out there. When the compiler is allowed to be arbitrarily clever with no restrictions nor a definite spec, you run into a situation where the only code that’s guaranteed to compile everywhere is the one that assumes that compiler is as dumb as possible (in our example, it would be requiring all local variables to be initialized, period). Which is quite useless. Just a small point but "absence of evidence is not evidence of absence" is usually the claim the believer gives to the skeptic! skeptics make the point that absence of evidence _IS_ a form of evidence of absence….at least when active attempts to find evidence have occurred. Your argument as used is correct but thats not exactly what the phrase is usually used to mean. usually the believer is arguing ‘well just because we don’t have evidence doesn’t mean we are wrong’ at which the response is of course ‘well of course not….but it does mean you are more likely to be wrong!’ sorry about being picky there. What I am wondering is why local variables are not initialized automatically with their default value, once the compiler determines that they are not definitely assigned. Would there be a performance penalty for such automatic assignment? The reason we require definite assignment is because failure to definitely assign a local is probably a bug. We do not want to detect and then silently ignore your bug! We tell you so that you can fix it. — Eric
https://blogs.msdn.microsoft.com/ericlippert/2009/10/12/absence-of-evidence-is-not-evidence-of-absence/
CC-MAIN-2017-22
en
refinedweb
view raw I was making a function that returns the longest string value from a list. My code works when there is only one string with the most characters. I tried to make it print all of the longest strings if there were more than one, and I do not want them to be repeated. When I run this, it only returns 'hello', while I want it to return 'ohman' and 'yoloo' also. I feel like the problem is in the line if item not list: list = ['hi', 'hello', 'hey','ohman', 'yoloo', 'hello'] def length(lists): a = 0 answer = '' for item in lists: x = len(item) if x > a: a = x answer = item elif x == a: if item not in list: answer = answer + ' ' + item return answer print length(list) First, we can find the maximum length of any string in the list: stringlist = ['hi', 'hello', 'hey','ohman', 'yoloo', 'hello'] #maxlength = max([len(s) for s in stringlist]) maxlength = max(len(s) for s in stringlist) # omitting the brackets causes max # to operate on an iterable, instead # of first constructing a full list # in memory, which is more efficient A little explanation. This is called a list comprehension, which allows you to comprehend one list as another list. The code [len(s) for s in stringlist] means "generate a list-like object, by taking stringlist, and for every s in that list, give me instead, len(s) (the length of that string). So now we have a list [2, 5, 3, 5, 5, 5]. Then we call the built-in max() function on that, which will return 5. Now that you have the max length, you can filter the original list: longest_strings = [s for s in stringlist if len(s) == maxlength] This does just as it reads in english: "For each string s in stringlist, give me that string s, if len(s) is equal to maxlength." Finally, if you want to make the result unique, you can use the set() constuctor to generate a unique set: unique_longest_strings = list(set(longest_strings)) (We are calling list() to turn it back into a list after removing the duplicates.) This boils down to: ml = max(len(s) for s in stringlist) result = list(set(s for s in stringlist if len(s) == ml)) Note: Don't use a variable named list, as it overrides the meaning of the name for the list type.
https://codedump.io/share/RqOZcv4dT2Pk/1/longest-strings-from-list
CC-MAIN-2017-22
en
refinedweb
Previous page: TableFixture Next page: SummaryFixture Parent page: Basic FIT fixtures ImportImport fixture can be used to tell FitNesse where to look for fixture classes. After you import a namespace or package you do not have to write fully-qualified fixture class names any more, making the tables more readable. Table FormatThe first row of the table should just be Import . All following rows list namespaces or packages to import — one cell per row. |Import| |info.fitnesse.fixturegallery| NotesTUse the Import fixture to make your test pages easier to read. You will typically want to put this table into the SetUp pages for test suites. Previous page: TableFixture Next page: Summary
http://fitnesse.org/FitNesse.FullReferenceGuide.UserGuide.FixtureGallery.BasicFitFixtures.ImportFixture
CC-MAIN-2017-22
en
refinedweb
TULSA, Okla.--(BUSINESS WIRE)--Unit Corporation (NYSE: UNT) today reported results for the fourth quarter of 2012. Those results included a previously announced non-cash ceiling test write down of $167.7 million ($104.5 million after tax, or $2.17 per diluted share). Because of the ceiling test write down, Unit incurred a net loss of $56.5 million, or $1.18 per diluted share, for the fourth quarter of 2012, compared to net income of $51.7 million, or $1.08 per diluted share for the fourth quarter of 2011. The ceiling test write down, which reduced the carrying value of the company’s oil and natural gas properties, resulted from significantly lower commodity prices during the fourth quarter of 2012. Without the ceiling test write down, net income for the fourth quarter of 2012 would have been $47.9 million, or $0.99 per diluted share (see Non-GAAP Financial Measures below). Total revenues for the fourth quarter of 2012 were $331.6 million (50% oil and natural gas, 33% contract drilling, and 17% mid-stream), compared to $347.3 million (41% oil and natural gas, 41% contract drilling, and 18% mid-stream) for the fourth quarter of 2011. For 2012, Unit reported net income of $23.2 million, or $0.48 per diluted share. For 2011, net income was $195.9 million, or $4.08 per diluted share. Included in the 2012 results were ceiling test write downs totaling $283.6 million ($176.6 million after tax, or $3.67 per diluted share). Excluding these ceiling test write downs, net income for 2012 would have been $199.8 million, or $4.15 per diluted share, a 2% increase over 2011 (see Non-GAAP Financial Measures below). Total revenues for 2012 were $1,315.1 million (43% oil and natural gas, 40% contract drilling, and 17% mid-stream), compared to $1,207.5 million (43% oil and natural gas, 40% contract drilling, and 17% mid-stream) for 2011. OIL AND NATURAL GAS SEGMENT INFORMATION - During 2012, Unit’s oil and natural gas liquids (NGLs) reserves increased 9% and 59%, respectively. - Replaced 337% of 2012 production with new reserve additions. - Total production for 2012 was 14.2 MMBoe, an increase of 18% over 2011, and included an increase in oil and NGLs production of 28%. - Production guidance for 2013 is 16.0 to 16.5 MMBoe, an increase of 13% to 16% over 2012. The fourth quarter of 2012 marks the 12th consecutive quarter that liquids (oil and NGLs) production has increased. Unit’s strategy of drilling oil or NGLs rich wells is evident in its production results. Liquids production represented 41% of total equivalent production during the fourth quarter of 2012. Fourth quarter of 2012 total equivalent production increased 26% over the fourth quarter of 2011 to 4.1 MMBoe, while total liquids production for the fourth quarter of 2012 increased 25% over the comparable quarter of 2011. Liquids production for the fourth quarter of 2012 has increased 130% since the first quarter of 2009 when Unit began focusing almost entirely on increasing its liquids production. Fourth quarter 2012 oil production was 912,000 barrels, in comparison to 744,000 barrels for the same period of 2011, an increase of 23%. NGLs production during the fourth quarter of 2012 was 782,000 barrels, an increase of 27% when compared to 616,000 barrels for the same period of 2011. Fourth quarter 2012 natural gas production increased 28% to 14.5 billion cubic feet (Bcf) compared to 11.4 Bcf for the comparable quarter of 2011. Total production for all of 2012 was 14.2 MMBoe, an increase of 18% over the 12.1 MMBoe produced during 2011. Unit’s average natural gas price for the fourth quarter of 2012 decreased 11% to $3.63 per thousand cubic feet (Mcf) as compared to $4.09 per Mcf for the fourth quarter of 2011. Unit’s average oil price for the fourth quarter of 2012 increased 4% to $91.67 per barrel compared to $88.06 per barrel for the fourth quarter of 2011. Unit’s average NGLs price for the fourth quarter of 2012 was $33.85 per barrel compared to $43.47 per barrel for the fourth quarter of 2011, a decrease of 22%. For 2012, Unit’s average natural gas price decreased 21% to $3.37 per Mcf as compared to $4.26 per Mcf for 2011. Unit’s average oil price for 2012 was $92.60 per barrel compared to $87.18 per barrel during 2011, a 6% increase. Unit’s average NGLs price for 2012 was $31.58 per barrel compared to $43.64 per barrel during 2011, a 28% decrease. All prices reflected in this paragraph include the effects of hedges. For 2013, Unit has hedged 8,330 Bbls per day of its oil production and 100,000 MMBtu per day of natural gas production. The oil production is hedged under swap contracts at an average price of $97.94 per barrel. Of the natural gas production, 80,000 MMBtu per day is hedged with swaps and 20,000 MMBtu per day is hedged with a collar. The swap transactions were done at a comparable average NYMEX price of $3.65. The collar transaction was done at a comparable average NYMEX floor price of $3.25 and ceiling price of $3.72. The following table illustrates Unit’s production and certain results for the periods indicated: (1) Realized price includes oil, natural gas liquids, natural gas and associated hedges. Unit recently acquired approximately 105,000 net acres located primarily in south central Kansas in the developing Mississippian play. Unit drilled its first horizontal well in Reno County, Kansas in the second quarter 2012 to a total measured depth of 8,115 feet including 3,850 feet of lateral. First production occurred in May 2012 with an average peak 30 day rate of 352 Boe per day consisting of 315 barrels of oil per day, 12 barrels of NGLs per day, and 150 Mcf of natural gas per day. The production components were approximately 89% oil, 3% NGLs, and 8% natural gas. Based on the production profile of this well, the reserve range estimate for a well in Unit’s Kansas Mississippian play would range somewhere between 125 MBoe to 180 MBoe. Using this estimated range and a completed well cost of $3.0 million along with flat pricing of $90 oil, $30 NGLs, and $3.25 natural gas, the typical Mississippian well would have a calculated rate of return (ROR) of approximately 30% to 66%. In addition to the initial well, Unit drilled three more horizontal Mississippian wells during 2012. Two of the wells had first sales in late December 2012, and the third is waiting on pipeline connection. In the first quarter of 2013, Unit plans to drill three additional wells before suspending drilling until pipeline infrastructure can be installed, which is scheduled for mid-year 2013. The estimated completion date for the pipeline is June 2013. Current plans are to move one Unit drilling rig back in the Mississippian play starting in July 2013 and possibly adding a second Unit drilling rig in September 2013. For 2013, Unit anticipates having first sales on approximately 13 gross wells and spending approximately $40 million for drilling and completion in its Mississippian play. During 2012, Unit drilled 32 gross wells with an average working interest of 84% in its Marmaton horizontal oil play, located in Beaver County, Oklahoma. Thirty of the wells were short laterals with approximately 4,500 feet of lateral length and two of the wells were extended laterals with approximately 9,700 feet of lateral length. The net production from Unit’s Marmaton play for the fourth quarter of 2012 averaged 3,424 barrels of oil per day, 528 barrels of NGLs per day, and 1,775 Mcf of natural gas per day, an increase of 15% over the third quarter 2012 and a 61% year-over-year increase between 2012 and 2011. Included in the year end reserve calculation are adjustments taken for wellbore communication that some of the wells have experienced. The company has adjusted its drilling program to address this issue. For 2013, Unit anticipates running a two drilling rig program in this play that should result in approximately 40 gross wells at an approximate net cost of $90 million. Due to current well spacing limitations associated with drilling extended lateral wells, the majority of 2013 wells are anticipated to be drilled as short lateral wells. Unit currently has leases on approximately 112,000 net acres in this play with about 44% of the leasehold held by production. In its Granite Wash (GW) play located in the Texas Panhandle, Unit drilled and operated 29 gross horizontal wells during 2012 with an average working interest of 87%. The net production from Unit’s GW play for the fourth quarter of 2012 averaged 1,822 barrels of oil per day, 4,988 barrels of NGLs per day and 46.2 MMcf of natural gas per day, or an equivalent rate of 87.0 MMcfe per day, an increase of 43% over the third quarter 2012 and a 41% year-over-year increase between 2012 and 2011. Unit expects to work four to six Unit drilling rigs drilling horizontal wells in both the newly acquired Noble leasehold and Unit’s existing leasehold in 2013, which equates to approximately 37 operated gross GW wells at an approximate net cost of $150 million. Unit currently owns leases on approximately 46,000 net acres with about 80% of the leasehold held by production. In Unit’s Wilcox play, located primarily in Polk, Tyler, and Hardin Counties, Texas, Unit operated and completed 11 gross wells in 2012 with an average working interest of 88% and a success rate of 82%. Three of the 11 wells were completed in Unit’s “Gilly” Lower Wilcox field bringing the total number of wells completed in that field to five at year end 2012. Approximately 18% or 30 net Bcfe of the anticipated 168 net Bcfe (242 gross Bcfe) potential reserves are booked as proved producing or proved behind pipe at year end 2012. For 2013, Unit plans to run one Unit rig which should drill approximately 12 gross wells at an approximate net cost of $60 million. Seven of the 12 wells are planned to be drilled in the “Gilly” Lower Wilcox Field and the remaining five wells will be drilled on other Wilcox prospects. On September 17, 2012, Unit closed its purchase of certain oil and natural gas assets from Noble Energy, Inc., with an effective date of April 1, 2012. The acquisition included various producing oil and gas properties and approximately 83,000 net acres primarily in the Granite Wash, Cleveland, and various other plays in western Oklahoma and the Texas Panhandle. The adjusted purchase price was $592.6 million. The acquisition adds approximately 24,000 net acres to Unit’s Granite Wash core area in the Texas Panhandle with significant potential, including approximately 600 possible horizontal drilling locations. The total non-Granite Wash acreage acquired in the Texas Panhandle and western Oklahoma is approximately 59,000 net acres of which 95% is held by production and is characterized by high working interest and operatorship. Unit also received four gathering systems as part of the transaction and other miscellaneous assets. Also in September 2012, Unit sold its interest in certain Bakken properties (representing approximately 35% of its total acreage in the Bakken play). The proceeds, net of related expenses were $226.6 million. In addition, Unit sold certain oil and natural gas assets in Brazos and Madison Counties, Texas for approximately $44.1 million. Larry Pinkston, Unit’s Chief Executive Officer and President, said: “We are pleased with the results from our exploration operations, and we are excited about the acquisition from Noble and the growth opportunities that it provides. This acquisition more than doubled our acreage in our Granite Wash Texas Panhandle core area. It also provides us with additional inventory of drilling opportunities that will allow us to significantly grow our oil and liquids-rich gas production in the Anadarko Basin. Our recent divestiture of some non-core properties was a strategic move to enhance our overall liquidity for future growth opportunities. Unit’s annual production guidance for 2013 is approximately 16.0 to 16.5 MMBoe, an increase of 13% to 16% over 2012.” CONTRACT DRILLING SEGMENT INFORMATION The average number of drilling rigs used in the fourth quarter of 2012 was 64.0, a decrease of 22% from the fourth quarter of 2011, and a decrease of 13% from the third quarter of 2012. Per day drilling rig rates for the fourth quarter of 2012 averaged $19,828, an increase of 3%, or $498, from the fourth quarter of 2011, and a 1% decrease, or $161, from the third quarter of 2012. Average per day operating margin for the fourth quarter of 2012 was $7,838 (before elimination of intercompany drilling rig profit of $2.6 million). This compares to $9,037 (before elimination of intercompany drilling rig profit and bad debt expense of $4.9 million) for the fourth quarter of 2011, a decrease of 13%, or $1,199. As compared to the third quarter of 2012 ($9,672 before elimination of intercompany drilling rig profit of $4.0 million), fourth quarter 2012 operating margin decreased 19% or $1,834 (in each case regarding the elimination of intercompany drilling rig profit see Non-GAAP Financial Measures below). Approximately $1,007 per day of the third quarter 2012 average operating margin resulted from early termination fees resulting from the cancellation of certain long-term contracts. For all of 2012, Unit averaged 73.9 drilling rigs working, a decrease of 3% from 76.1 drilling rigs working during 2011. Average per day operating margin for all of 2012 was $9,578 (before elimination of intercompany drilling rig profit of $15.6 million) as compared to $8,496 (before elimination of intercompany drilling rig profit and bad debt expense totaling $19.9 million) for 2011, an increase of 13% (in each case regarding the elimination of intercompany drilling rig profit see Non-GAAP Financial Measures below). Approximately $847 per day of the 2012 average operating margin resulted from early termination fees resulting from the cancellation of certain long-term contracts. Larry Pinkston said: “Industry demand for drilling rigs softened throughout the year and more so during the latter part of the year as operators reduced their drilling efforts in order to stay within their 2012 budgets. Drilling activity should gradually improve as operators start with their new budgets for 2013, and as they get more comfortable with the outlook for NGLs prices. Approximately 99% of our drilling rigs working today are drilling for oil or NGLs. Currently, we have 127 drilling rigs in our fleet, of which 69 are under contract. Long-term contracts (contracts with original terms ranging from six months to two years in length) are in place for 29 of those 69 drilling rigs. Of these contracts, six are up for renewal during the first quarter of 2013, five during the second quarter of 2013, eight during the third quarter of 2013, two during the fourth quarter of 2013, and eight in 2014 and beyond.” The following table illustrates Unit’s drilling rig count at the end of each period and average utilization rate during the period: MID-STREAM SEGMENT INFORMATION - Increased fourth quarter of 2012 processed volumes per day and gathered volumes per day by 4% and 26%, respectively, over the fourth quarter of 2011. - A new gas gathering system and processing plant in Noble and Kay Counties, Oklahoma, known as the Bellmon system, is completed and operating. Extensions are underway to connect additional third party producers, and an additional capacity expansion is anticipated to be completed in the first quarter of 2013. Fourth quarter of 2012 per day processed volumes were 163,173 MMBtu while per day gathered volumes were 325,231 MMBtu, an increase of 4% and 26%, respectively, over the fourth quarter of 2011. Fourth quarter 2012 liquids sold volumes were 441,973 gallons per day, a decrease of 14% from the fourth quarter of 2011 and a decrease of 23% from third quarter 2012 primarily due to operating in ethane rejection mode in late fourth quarter of 2012. Operating profit (as defined in the Selected Financial and Operational Highlights) for the fourth quarter was $6.4 million, a decrease of 16% from the fourth quarter of 2011 and a decrease of 4% from the third quarter of 2012. The decrease from the fourth quarter 2011 was primarily due to lower liquids volumes recovered and lower prices. The decrease from the third quarter of 2012 was primarily due to lower liquids volumes recovered but somewhat offset by higher prices. For 2012, processing volumes of 165,511 MMBtu per day, gathering volumes of 288,799 MMBtu per day, and liquids sold volumes of 542,578 gallons per day increased 43%, 34% and 32%, respectively, over 2011. The following table illustrates certain results from this segment’s operations for the periods indicated: Larry Pinkston said: “During the second quarter of 2012, we completed the installation of our fifth processing plant at our Hemphill County, Texas facility. We now can process 160 MMcf per day of our own and third party Granite Wash natural gas production. Late in the second quarter, we completed and began operating our Bellmon system, a new gas gathering system and processing plant in Noble and Kay Counties in the Mississippian play of north central Oklahoma. This system consists of approximately 83 miles of pipe with a 20 MMcf per day gas processing plant. An additional 30 MMcf per day gas processing plant is scheduled to be installed at this facility in the first quarter of 2013. We have also connected our existing Remington gathering system to the new Bellmon system which required installing approximately 26 miles of pipeline and related compression services. Besides these projects, we also completed the installation of a natural gas liquids line from our Bellmon plant to Medford, Oklahoma. This project consists of approximately 20 miles of 6” pipe which was completed in the fourth quarter of 2012.” “We are continuing to expand operations in the Appalachian region. Construction was completed on the first phase of our gathering facility in Allegheny and Butler counties, Pennsylvania, known as the Pittsburgh Mills system. The first phase of this project comprises approximately seven miles of gathering pipeline to which we have nine wells connected. The current gathered volume from these wells is approximately 28 MMcf per day. Construction activity to expand this gathering system continues as the producer is maintaining its drilling activity.” FINANCIAL INFORMATION Unit ended the year with long-term debt of $716.4 million, and a debt to capitalization ratio of 27%. On July 24, 2012, Unit completed a private offering to eligible purchasers of $400 million aggregate principal amount of senior subordinated notes due 2021, with an interest rate of 6.625% per year. The notes were sold at 98.75% of par plus accrued interest from May 15, 2012. Unit used the net proceeds to partially finance the acquisition from Noble. The notes have since been registered and exchanged and are now treated as a single series of debt securities with Unit’s previously issued $250 million senior subordinated notes. Unit now has $645.3 million outstanding under its senior subordinated notes due 2021. Also with the acquisition, Unit increased commitments under its existing credit facility from $250 million ($600 million borrowing base) to $500 million ($800 million borrowing base). MANAGEMENT COMMENT Larry Pinkston said: “Weaker commodity prices created headwinds for all business segments in 2012. In spite of this, we experienced robust growth in reserves and production. The Noble acquisition will be an important growth step for Unit going forward. We plan to accelerate the drilling activity in the acquired properties and our other Granite Wash acreage over the next 12 to 18 months using up to six rigs from our contract drilling segment, and we plan to operate the acquired gathering systems and replace existing third party processing contracts beginning in 2015. We anticipate this acquisition will immediately be accretive to cash flow and to earnings beginning in 2013. We are optimistic about the outlook for 2013. We are well positioned, especially given the recent financing arrangements and property divestitures we have completed, to take advantage of growth opportunities that may arise for our business segments.” WEBCAST Unit will webcast its fourth quarter and year-end earnings conference call live over the Internet on February 19, 2013 at 10:00 a.m. Central Time (11:00 a.m. Eastern). To listen to the live call, please go to at least fifteen minutes prior to. Several, and its exploration segment, development, operational, implementation and opportunity risks, possible delays caused by limited availability of third party services needed in its operations, possibility of future growth opportunities, and other factors described from time to time in the company’s publicly available SEC reports. The company assumes no obligation to update publicly such forward-looking statements, whether because of new information, future events or otherwise. Non-GAAP Financial Measures We report our financial results in accordance with generally accepted accounting principles (“GAAP”). We believe certain non-GAAP performance measures provide users of our financial information and our management additional meaningful information to evaluate the performance of our company. This press release includes net income excluding the effect of the impairment of our oil and natural gas properties, diluted earnings per share excluding the effect of the impairment of our oil and natural gas properties, cash flow from operations before changes in operating assets and liabilities and our drilling segment’s average daily operating margin before elimination of intercompany drilling rig profit. Below is a reconciliation of GAAP financial measures to non-GAAP financial measures for the three and twleve months ended December 31, 2012 and 2011. Non-GAAP financial measures should not be considered by themselves or a substitute for our results reported in accordance with GAAP. We have included the net income excluding impairment of oil and natural gas properties and diluted earnings per share excluding impairment of oil and natural gas properties because: - We use the adjusted net income to evaluate the operational performance of the company. - The adjusted net income is more comparable to earnings estimates provided by securities analyst. - The impairment of oil and natural gas properties does not occur on a recurring basis and the amount and timing of impairments cannot be reasonably estimated for budgeting purposes and is therefore typically not included for forecasting operating results. Non-GAAP Financial Measures (continued) We have included the cash flow from operations before changes in operating assets and liabilities because: - It is an accepted financial indicator used by our management and companies in our industry to measure the company’s ability to generate cash which is used to internally fund our business activities. - It is used by investors and financial analysts to evaluate the performance of our company. We have included the average daily operating margin before elimination of intercompany rig profit and bad debt expense because: - Our management uses the measurement to evaluate the cash flow performance of our contract drilling segment and to evaluate the performance of contract drilling management. - It is used by investors and financial analysts to evaluate the performance of our company.
http://www.businesswire.com/news/home/20130219005804/en/Unit-Corporation-Reports-2012-Fourth-Quarter-Year
CC-MAIN-2017-22
en
refinedweb
Daniel Robertson At Yammer we run a full suite of tests against our Android application dozens—sometimes hundreds—of times per day. Our goal is to have a feedback loop so fast that our developers are made aware of any breaking changes they’ve made near instantaneously. Third party libraries that rely on static function calls in an application can be undesirable for testing. They can be a source of slowness, depending on the weight of the given library, or they can pollute analytics. Often times, specific debug-only libraries will provide a no-op version which can be specified in Gradle to avoid execution during tests. One such library is LeakCanary by Square. But it’s rare among libraries designed to run in both debug and production versions of an app. This article will detail how we removed our dependency on Microsoft’s Application Insights analytics library. Espresso + Dagger We utilize Espresso and Dagger to accomplish this. Dagger — a fast dependency injector provided by Square which we use extensively throughout our app. Espresso — a testing framework provided by Google which we’ve used to create almost 600 tests. Unfortunately for us, all of the testing code for Espresso runs after Application has already been created. So how did we address this? Simple — we wrote our own TestRunner and extended Application to allow us to specify Dagger modules prior to injection. The TestRunner is responsible for the creation, monitoring, and execution of the application under test. The below illustration shows how it works. Now Wrap It Next, we use Dagger to help us inject an easily mockable wrapper. The new wrapper should look like this: public class ApplicationInsightsWrapper { private Application application; @Inject public ApplicationInsightsWrapper(Application application) { this.application = application; } public void setup() { ApplicationInsights.setup(application.getApplicationContext() , application); ApplicationInsights.start(); } } Now we’ve got something we can mock! Next, we need to override this object in our tests using Dagger. We’ll do that by creating a new module and using Mockito to return a mock object. @Module( injects = { TestExampleApplication.class }, complete = false, library = true, overrides = true) public class ApplicationInsightsWrapperOverrideModule { @Provides ApplicationInsightsWrapper provideApplicationInsightsWrapper() { return mock(ApplicationInsightsWrapper.class); } } The Conclusion Take control of Application by using Dagger to help inject its dependencies. By using this pattern, we improved our Espresso testing speed and reliability. The conscious tradeoff that must be made, however, is the decision as to whether or not that behavior should be tested in the first place. While expensive network calls and analytics can conveniently be removed from Espresso tests, it’s still important to maintain some form of end-to-end testing to ensure all production code gets tested. Otherwise, mock away! To see how this works in a complete project, view our sample application at GitHub.
http://engineeringjobs4u.co.uk/mock-away-android-application-dependencies-yammer-engineering-medium
CC-MAIN-2018-51
en
refinedweb
Opened 11 years ago Last modified 8 years ago #1913 new Feature Requests Null deleter for shared_ptr Description As raised in this () message on the boost-users mailing list, it would be very nice if the smart pointer library contained a null deleter object so it could be used for stack/static objects. To save the user having to define their own. Attachments (1) Change History (5) comment:1 Changed 10 years ago by comment:2 Changed 10 years ago by comment:3 Changed 8 years ago by comment:4 Changed 8 years ago by Changed 6 years ago by makes null_deleter available from boost/smart_ptr/null_deleter.hpp, minimal docs & test case Note: See TracTickets for help on using tickets. This ticket is raised against version 1.35.0 At least in 1.42 there is one hidden away in boost::serialization. It is difficult to know though why it is there: #include <boost/serialization/shared_ptr.hpp> class Foo { }; Foo foo; boost::shared_ptr<Foo> sharedfoo( &foo, boost::serialization::null_deleter() );
https://svn.boost.org/trac10/ticket/1913
CC-MAIN-2018-51
en
refinedweb
Enable/disable use of epsv #include <curl/curl.h> CURLcode curl_easy_setopt(CURL *handle, CURLOPT_FTP_USE_EPSV, long epsv); Pass epsv as a long. If the value is 1, it tells curl to use the EPSV command when doing passive FTP downloads (which it. 1 FTP TODO Along with FTP Returns CURLE_OK if FTP is supported, and CURLE_UNKNOWN_OPTION if not.
https://www.carta.tech/man-pages/man3/CURLOPT_FTP_USE_EPSV.3.html
CC-MAIN-2018-51
en
refinedweb
Migrating to Pulumi from Terraform HashiCorp Terraform provides a custom DSL called Hashicorp Configuration Language (HCL) to describe and provision infrastructure resources on Terraform providers. Pulumi enables you to describe the same infrastructure resources as real code, providing huge productivity gains, and has deep support for cloud native technologies such as Kubernetes and serverless programming. Need help converting your Terraform templates into Pulumi code? Drop us a line. Benefits of Pulumi Real Code Pulumi is infrastructure as real code. This means you get all the benefits of your favorite language and tool for provisioning infrastructure: code completion, error checking, versioning, IDE support, etc. - without the need to manage limited DSL syntax. Familiar Constructs Real languages means you get familiar constructs like for loops, functions, and classes - cutting boilerplate and enforcing best practices. Pulumi lets you leverage existing package management tools and techniques. Ephemeral Infrastructure Pulumi has deep support for cloud native technologies, like Kubernetes, and supports advanced deployment scenarios that cannot be expressed with Terraform. Pulumi is a proud member of the Cloud Native Computing Foundation (CNCF). TF Provider Integration Pulumi is able to adapt any Terraform Provider for use with Pulumi, enabling management of any infrastructure supported by the Terraform Providers ecosystem using Pulumi programs. Find out more here. Take advantage of real coding features with Pulumi Pulumi provides a more expressive and efficient way to define cloud resources: - Use variable loops, not copy/paste - Use any Node libaries (or Python/Go) - On-the-fly error checking - Freeform code instead of complex interpolations Find many other examples here. import * as aws from "@pulumi/aws"; import { readFileSync, readdirSync } from "fs"; import { join as pathjoin } from "path"; const bucket = new aws.s3.Bucket("mybucket"); const folder = "./files"; let files = readdirSync(folder); for (let file of files) { const object = new aws.s3.BucketObject(file, { bucket: bucket, content: readFileSync(pathjoin(folder, file)).toString("utf8") }); } export const bucketname = bucket.id; resource "aws_s3_bucket" "mybucket" { bucket_prefix = "mybucket" } resource "aws_s3_bucket_object" "data_txt" { key = "data.txt" bucket = "${aws_s3_bucket.mybucket.id}" source = "./files/data.txt" } resource "aws_s3_bucket_object" "index_html" { key = "index.html" bucket = "${aws_s3_bucket.mybucket.id}" source = "./files/index.html" } resource "aws_s3_bucket_object" "index_js" { key = "index.js" bucket = "${aws_s3_bucket.mybucket.id}" source = "./files/index.js" } resource "aws_s3_bucket_object" "main.css" { key = "main.css" bucket = "${aws_s3_bucket.mybucket.id}" source = "./files/main.css" } resource "aws_s3_bucket_object" "favicon.ico" { key = "favicon.ico" bucket = "${aws_s3_bucket.mybucket.id}" source = "./files/favicon.ico" } output "bucketname" { value = "${aws_s3_bucket.mybucket.id}" } Productive cloud native programming Pulumi is designed with cloud native computing in mind - from containers to serverless, providing a productive model for quickly building and deploying apps: - Rich, built in support for event handlers - Easy-to-use in-line Lambdas for simple functions - Use JavaScript for both infrastructure and Lambda callbacks - Avoid the need for significant boiler plate code Find many other examples here. import * as aws from "@pulumi/aws"; // Create an S3 Bucket const bucket = new aws.s3.Bucket("mybucket"); // Register a Lambda to handle Bucket Notification bucket.onObjectCreated("newObj", async (ev, ctx) => { // Write code inline, or use a Zip console.log(JSON.stringify(ev)); }); // Export the bucket name for easy scripting export const bucketName = bucket.id; resource "aws_s3_bucket" "mybucket" { bucket_prefix = "mybucket" } data "archive_file" "lambda_zip" { type = "zip" output_path = "lambda.zip" source { filename = "index.js" content = < { console.log(JSON.stringify(ev)) } EOF } } data "aws_iam_policy_document" "lambda-assume-role-policy" { statement { actions = ["sts:AssumeRole"] principals { type = "Service" identifiers = ["lambda.amazonaws.com"] } } } resource "aws_iam_role" "lambda" { assume_role_policy = "${data.aws_iam_policy_document.lambda-assume-role-policy.json}" } resource "aws_lambda_function" "my_lambda" { filename = "${data.archive_file.lambda_zip.output_path}" source_code_hash = "${data.archive_file.lambda_zip.output_base64sha256}" function_name = "my_lambda" role = "${aws_iam_role.lambda.arn}" handler = "index.handler" runtime = "nodejs8.10" } resource "aws_lambda_permission" "allow_bucket" { statement_id = "AllowExecutionFromS3Bucket" action = "lambda:InvokeFunction" function_name = "${aws_lambda_function.my_lambda.arn}" principal = "s3.amazonaws.com" source_arn = "${aws_s3_bucket.mybucket.arn}" } resource "aws_s3_bucket_notification" "bucket_notification" { bucket = "${aws_s3_bucket.mybucket.id}" lambda_function { lambda_function_arn = "${aws_lambda_function.my_lambda.arn}" events = ["s3:ObjectCreated:*"] } } output "bucket_name" { value = "${aws_s3_bucket.mybucket.id}" } How Pulumi Works Let Pulumi assist with your cloud infrastructure Need help converting your Terraform templates into Pulumi code? Drop us a line.
https://www.pulumi.com/terraform/
CC-MAIN-2018-51
en
refinedweb
NE W ! Learn how to program the easy and fun way LEARN HOW TO… WorldMags.net WorldMags.net WorldMags.net Learn how to program the easy and fun way WorldMags.net uk Phone +44 ( 0 )1225 442244 Fax +44 ( 0 )1225 732275 All contents copyright © 2016 Future Publishing Limited or published under licence. Online enquiries: www. 'VUVSF1VCMJTIJOH-JNJUFE DPNQBOZOVNCFS JTSFHJTUFSFEJO&OHMBOEBOE8BMFT3FHJTUFSFEPGmDF3FHJTUFSFEPGmDF2VBZ)PVTF 5IF"NCVSZ #BUI #"6" All information contained in this publication is for information only and is. Bath. Future 4UPDL&YDIBOHF Managing director.co. Phone: 020 7429 4000 Future Publishing Limited Quay House. neither Future nor its employees. Future plc is a public Chief executive .uk 2 East Poultry Avenue. No part of this magazine may be reproduced. BA1 1UA. UK www. ART EDITOR Mike Saunders. Future Photo Studio MANAGEMENT MARKETING CIRCULATION MARKETING MANAGER TRADE MARKETING MANAGER EDITORIAL DIRECTOR Richard Stephens Juliette Winyard Paul Newman Phone +44(0)7551 150984 GROUP ART DIRECTOR Steve Gotobed PRINT & PRODUCTION LICENSING PRODUCTION MANAGER SENIOR LICENSING & Mark Constance SYNDICATION MANAGER Matt Ellis PRODUCTION CONTROLLER matt. correct at the time of going to press. Jonni Bidwell Efrain Hernandez-Mendoza EDITOR-IN-CHIEF Graham Barlow IMAGES ThinkStock. You are advised to contact manufacturers and retailers directly with regard to the price and other details of products or services referred to in this publication.myfavouritemagazines. The Ambury.futureplc. you automatically grant Future a licence to publish your submission in whole or in part in all editions of the magazine. London EC1A 9PT.net EDITORIAL TEAM CONTRIBUTORS EDITOR Les Pounder.JMMBI#ZOH5IPSOF We are committed to using only magazine paper company quoted Non-executive chairman Peter Allen XIJDI JT EFSJWFE GSPN XFMM NBOBHFE DFSUJmFE on the London &KLHIÀQDQFLDORIÀFHU1FOOZ-BELJO#SBOE forestry and chlorine-free manufacture. Mayank Sharma. although every care is taken.futureplc.com 5FM.com Vivienne Calvert Phone +44(0)1225 442244 SUBSCRIPTIONS PRINTED IN THE UK BY UK reader order line & enquiries: 0844 848 2852 William Gibbons on behalf of Future. on tablet recycling site. All rights reserved. WorldMags. Ben Everard.myfavouritemagazines. Future cannot accept any responsibility for errors or inaccuracies in such information. Any material you submit is sent at your risk and. stored. Magazines Joe McEvoy TZNCPM'653 Publishing and its paper suppliers have been. Apps and websites mentioned in this publication are not under our control. If you submit unsolicited material to us. as far as we are aware. transmitted or used in any way without the prior written permission of the publisher. & smartphone and in print. We are not responsible for their contents or any changes or updates to them. either through group and leading digital business.com www. We encourage you to recycle Future is an award-winning international media this magazine. Neil Mohr Graham Morrison.co. including licensed editions worldwide and in any physical or digital format throughout the world. agents or subcontractors shall be liable for loss or damage. Overseas reader order line & enquiries: +44 (0)1604 251045 Distributed in the UK by Seymour Distribution Ltd. We reach more than 57 million international consumers a month your usual household recyclable and create world-class content and advertising waste collection service or at solutions for passionate consumers online. net . JOEFQFOEFOUMZ DFSUJmFE JO BDDPSEBODF XJUI UIF SVMFTPGUIFø'4$ 'PSFTU4UFXBSETIJQ$PVODJM WorldMags. the gatekeepers to we all can access operating systems. move on to more than Cool Britannia – jump forward to advanced topics. coders the ideal guide to start coding. We’ll Back then. Thanks to have suddenly become a new generation of open free software. Combine the huge development tools. then access steam the world hasn’t seen since the everything you need freely online. cool devices. pushing coding to the fore of education. exciting and fun. So Brit invented the web. apps and tools. newbie looking to take your first steps into business start-ups and the coding world. smartphone software with confidence and really the learning journey as enjoyable as or laptop – see page 146 for more get to know how to use it possible for you details on this offer How are we doing? Email techbookseditor@futurenet. Editor Made Simple books are designed Break instructions down into Teach you new skills you can take to get you up and running quickly easy-to-follow steps so you won’t with you through your life and apply with a new piece of hardware or be left scratching your head over at home or even in the workplace software. a Brit designed what are you waiting for? Get coding! the Raspberry Pi. It’s an exciting journey! Coding is the new cool. We’ll show you how to get up and running and you’ve got a head of technological with a Linux system. these new realms. With the internet So no matter if you’re looking to relive driving a new world of those heady ’80s coding days or are a information exchange. A exciting and easy-to-follow projects. coding craze of the early 1980s.com and let us know if we’ve lived up to our promises! WorldMags. explain how you can use today. and Britain is firmly Neil Mohr. you hold in your hands online gaming. We won’t bombard you what to do next with jargon or gloss over basic Make it easy for you to take our principles. it was more Code Britannia explain the basics.net Coding Made Simple | 5 . but we will… Help you discover exciting new advice everywhere with you by things to do and try – exploring giving you a free digital edition of Explain everything in plain English new technology should be fun and this book you can download and take so you can tackle your new device or our guides are designed to make with you on your tablet. such as the Raspberry Pi. Coding is easy. and Britain is again firmly at the the Raspberry Pi.net Welcome! Learning to code will change the way you think about the world. and provide you with heart of a web and coding revolution. compilers and the interest in learning how to create and programming languages needed to create control these worlds with the surge of professional programs. WorldMags. ................................................................................................................................................................................................................. 10 Get coding in Linux Mint .......................................... 48 Using loops ................................................................................................................. 52 Common mistakes ................................................................................................................... 16 Join the Coding Academy .................................................. 54 6 | Coding Made Simple WorldMags............... 40 Recursion ...........................................32 Functions and objects ............................................................................... 50 Compilers ......................................................................................................................................................... 36 Variables ............................................................ 34 Conditionals ........ 46 Integers ...............................................................................................................................net ........... 38 Program structure .......................................net Contents Get coding Get started with Linux .............................................................................................................................................................................................................................................................................................................................................................................................................................................................. 44 Sorting algorithms ................................................................................................................. WorldMags................................................................................................................................................................................... 19 How to use an IDE ............... 28 Coding basics Lists ...................................................................................................... .................................... Raspberry Pi Getting started 82 .........64 UNIX programs part 1 ....................................................................................... WorldMags.........................................net Further coding Data types 58 ................................................................................. 134 Twitter scanner ................ More data types .......................................................... 128 Sound filters ..................................................................... 110 2048 in Minecraft ........................................................................................0 primer ...................................................................................................................................... 108 Image walls in Minecraft ............................................66 UNIX programs part 2 .............................................................................. Python 3................... Starting Scratch 84 .......................................................................................................................................................................................................................... 124 Image filters ........................... Using files ............................................................................................................................... Persistence 76 ......................................................................................................................................................................................................................................................................................................................................................................................................................... 102 Hacking Minecraft .................................................................................................................................... 138 Build a GUI ........ 114 Coding projects Python 3................. Further Scratch 88 ............................................ Coding with IDLE 92 ................................. Modules 74 ...............................................................................................................................................................................................................................................................................................60 Abstraction 62 .......................................................... Advanced sorting .........................................................................................................................................................................................................................................................................................................................................................................net Coding Made Simple | 7 ............ Databases 78 ..................................68 UNIX programs part 3 70 ...0 on the Pi 98 ............................. 142 WorldMags............................................................................................................................................................................................................................................................ 120 Build a Gimp plug-in ................................................................................................................................................................................................................................................................................................................................................................................................ Python on the Pi 94 .......................................... WorldMags.net .net WorldMags. ..........net Get coding! Everything you need to start coding today Get started with Linux ......................net Coding Made Simple | 9 ... 19 How to use an IDE...................................... 28 WorldMags.................................... 10 Get coding in Linux Mint ...................WorldMags.................. 16 Join the Coding Academy ...... We recommend that walkthrough shows you how to create a live desktop. 10 | Coding Made Simple WorldMags. You don’t have to – the code works you use a version (known as a distro) called image that you can boot and run from either a on Windows or Mac OS X – but Linux comes Linux Mint. There’s a That’s the beauty of Linux – it’s built by don’t want to. you’re used to its slightly different interface how to run Mint within VirtualBox on top of All the coding projects in this bookazine are and way of working. notice that most of the screens dodgy sites. you’ll from a central server.net GET STARTED WITH LINUX It runs on most desktop and laptop PCs. it won’t damage PC dual-booting with Windows. you don’t even have to install anything if you Windows or Apple Mac OS X. The walkthrough opposite explains by thousands of coders around the world. there are three options: run Linux in there are different car VirtualBox. while the next based on someone running Linux on their really is to get along with. you’ll find how easy it Windows (or Mac OS X). No scouting round running on your PC. WorldMags. it’s free and you don’t even need to install it. just run a command or fire up a It’s not scary. run it off a DVD or manufacturers or makes of USB drive.” likely to cause any damage. It’s just your PC and you don’t even We’re only going to look at the first two as they’re the least that Linux happens to be free because it’s developed have to install anything. or install it on your TV. Just as geeks for geeks to do geeky things. If you currently have a Windows good reason for that: they’re not.net . operating system that can run your PC or Mac. Let’s look at Linux! A s you read through this Coding with many languages built in or ready to install you can get hold of Mint and then get it up and Made Simple bookazine. it won’t damage your PC and don’t look like Microsoft software centre to get what you need. and we’re going to look at the ways DVD or a USB flash drive. there’s more than one “It’s not scary. Once PC. we recommend 2048. you’re free to try you’ll need around 20GB of spare drive space have an 8GB PC. start VirtualBox. because core servers to websites. we think you’ll developers. Once dynamic hard drive size.org and download Choose Ubuntu and the bits should match the A prompt asks for a disc. that. and there are literally hundreds out after all. not all maintained. 4096 is best. It had it also comes from GNU. you should enable 3D acceleration choose Linux and call it ‘Mint’. in the virtual machine’s settings under installed. there’s the Software Center. I f you’ve never tried Linux. As long as In the Linux world.net VirtualBox 1 Get VirtualBox 2 Create a machine 3 Start virtual Mint Head to www. commands.linuxmint. It is not only the too cumbersome. contribute back to the community. You should also know that Linux designed and created by developers. Locate the Mint ISO Virtual Box 5 for your operating system. The upshot of this history is that there’s a Linux is free software. anyone can take it and 97% of the world’s supercomputers. click New Machine. the key weakness of be surprised at how easy it is to use. programs in /bin and /usr/bin that come from WorldMags. click Start to get going. which is less here. you’re willing to seek out help yourself and short. Under file you downloaded and click Start. So just about any time created most of the basic tools needed by a you do anything on your computer – every time computer of the early 1980s – compilers. when it’s Top tip makes. the key way of getting new tools and all the programming development tools you The GNU of GNU/Linux The GNU project (GNU stands for ‘GNU’s Not GNU. getting programs by downloading them from This is one of the reasons why Linux has opt for the MATE edition. but we suggest 32GB just in case. he had a kernel without the tools to run GNU aspect. once loaded.com. and much more – but did not have No wonder the GNU die-hards get upset a usable kernel (some would say its kernel. which A big reason why Linux makes such a good viruses and malware. but No matter which tutorial you follow. It is worth mentioning Torvalds started tinkering with his small project that no one really denies the importance of the in 1991. the remained so secure (it’s not infallible) but graphically demanding. You also need the all the rest as default settings. apart from the Mint to the virtual machine. in the past you’ve been used to maintained by the distro’s creators. GNU when we refer to our operating system as Hurd. you’ll a very welcoming and rich development hundreds nonetheless. introduction of the Windows Store has at least people downloading dodgy software is a key centralised where software comes from and way that machines become infected. and allocate 16MB of memory. unless you Getting apps repository of software. need a copy of the Linux Mint Cinnamon distro. there and everywhere. ecosystem waiting for you. being used widely in science and industry. Mint ISO file from. With Up and running removed the worry of getting infected by Linux Mint. More recently. When Linus Linux and not GNU/Linux. be ISO you downloaded. these are called distros for So it’s not such a bad thing to understand. Click Next. The default is 8GB. but if you Mint starts and. The fact is that with gives you access to hundreds of programs and development platform is that it was created by Linux.php programs has always been from a central and download the 32-bit build. available on all Linux platforms. Install it and be aware Memory. you’ll find there – not all good. and how good a development platform it Linux has been its lack of ease of use (Mint is an exception to that rule) but then.net Coding Made Simple | 11 . For extended use. Finish and Display.com/download. in which case get With Windows. from its use is going to come at the bottom of the to-do Unlike Windows and Mac OS X. file and directory manipulation software is being run at some level. If you have an older or slower machine. calling the OS Linux rather than on it. glibc is the core C library used in Linux and Unix’) predates Linux by several years. alongside powering list. ease of What’s a distro? runs the majority of the internet. WorldMags. and wealth of the most advanced tools freely effectively create their own OS to distribute. In many ways. Head to www. is still not that usable). The two were put together and GNU/Linux GNU/Linux has far more to do with convenience was born – an operating system using the Linux and laziness than politics – the full title is just kernel and the GNU toolset. you type a command or click an icon – GNU text editors.linuxmint. protected and know your system is 64-bit. Linux that Windows or OS X. You can leave it out or use the Install icon to properly install to store the virtual OS file. running Linux from this. there weren’t any graphical in the same place. the Terminal system called Wine – but the obscure laptop wireless cards can cause remains an efficient way of controlling Linux. graphics driver from your card’s manufacturer. We’re not really here to talk about using Linux commands. following a is. could wish for. you can also install USB drives. the ones you’ll care about – do have graphical Linux – you can run them via a There are a couple of exceptions: certain more interfaces these days. or hold down C on the Mac – suitable USB thumb drive and.linuxmint. as discussed in the you want to create a DVD copy or redo the Usually. Going back to the early days of This largely means things you’re used to in in every detail but there are a few standard computers and Linux.net Easy ways to run Linux If you’re not a big Linux user. you don’t need to – Linux is flexible enough some PCs boot from a suitable optical disc by similar boot process as discussed above. and take advantage of over 1. such as the command line. www. so computers were controlled set of programs. Linux open-source community issues. virtual versions to versions running off spare and run this – it looks complex.github. then you’ll probably a DVD. Many of them – or all Studio aren’t directly made for drivers. including writing the ISO file to a Mac system. Mint on a USB drive 1 UNetbootin Linux 2 Install Mint 3 Boot and run To run Mint from a USB stick. command it has to offer. manufacturer. To get this to work. and on most types of hardware – from www. The fact is. and we’ll use the process. However. there’s no need to Linux was developed originally in this type Photoshop and development worry about drivers – they’re built into the of environment. The standard way. once settings. The main stumbling block is ensuring of Linux create space alongside Windows and you’ve got your hands on the ISO.com. Select Diskimage and locate the file message says to press F11 or F12 to select the download tool UNetbootin from http:// in the Download folder. DVDs or on low-cost hardware such virtual PC is pretty easy if you stick to the default Linux on your system directly. a VirtualBox walkthrough. as computers were so Windows won’t work the same in Linux. you need to install the dedicated a consistent set of tools and interfaces to such as LibreOffice. That isn’t to say you can’t add based on Terminal use. When you first turn on a PC. 12 | Coding Made Simple WorldMags. Most versions as the Raspberry Pi. The truth pressing F11/F12. you can virtual optical drive. when you first turn on your PC. and we don’t blame you. Linux Mint will now run. menu and click OK to create the drive. Krita and a whole range of You don’t need to know anything about the freely available and The Terminal Terminal to use Linux on a day-to-day basis.net . is to burn it to under Storage that you add the ISO file to the make a dual-boot system. open-source products If you’ve heard of Linux. that offer the might fear or just wonder about is a thing However. One key one is interfaces. but creating a For the brave-hearted. This can be called a a Terminal and use the ls command to list a can also download Valve’s Steam gaming client number of different things. WorldMags. resolve problems. Some PCs have their own unetbootin. which you access through text Linux is that it’s not Windows or Mac OS X. on default. It’s not why we’re here but you called the Terminal.github.virtualbox. we would advise you to at least open same capabilities. Adobe Linux is that.io. on the whole.700 Linux games system. It is a direct Linux isn’t Windows interface to the operating system and all of its One thing to keep in mind when you first use Drivers tools. it offers has created its own tools performance. Ensure you have the boot device.org (see previous page). then one area you but it’s good to know that it’s there just in case. So big commercial products where are all the drivers? The cool thing with entirely through text commands. that it can be run in a number of ways beside. so all of its core tools are tools such as Microsoft Visual Linux kernel. Install from. but they’re generally not required. prompt or command-line interface. Gimp. nor does it offer the same move over from Windows. This installs the live correct USB drive selected in the pull-down specific button – consult your manual or disc ISO file directly to your USB drive. but it’s best practice to do this drive. You’ll need the Mint ISO file from yourself.io. or be questions that often crop up when people much slower. then you have a local copy to hand if selects the USB drive as the boot device. and cd to change directory. you need to ensure your PC be ideal. such as Microsoft Office. while if you want maximum 3D gaming and when it comes to troubleshooting. you top of or alongside most other operating Another option is to install VirtualBox from need to use a write tool such as UNetbootin systems. depending on the directory. you first need a The tool can directly download the Mint ISO You can now boot your PC from the USB USB drive at least 4GB in size – 16GB would image for you. There are more options not want to destroy your existing Windows or usually get it to boot from alternative media by available. older PCs and people who want modern I free software that can be redistributed by absolutely anyone. which aim themselves at different types of users. While it does lean to the more base to start from. com/steamos Ubuntu moved to a more from standard desktop use to server. ease of use and the large software Mageia based on Debian and is a custom OS that base of Ubuntu. SteamOS is created by Valve mouse design.linuxmint.org enough to get it installed and up and running. businesses. took the crown of the most used and often ranked in the top five distros. The choice can be bewildering. to build from scratch. Mint be the sexiest distro on the block but it’s widely www. such as experienced hands-on Terminal types.github. when they’re deemed stable enough. with a program menu and developers and software vendors. a couple of high-quality distros that can be Arch bones distro.debian. as Fedora only gets Arch Linux but without all the easy-to-use distribution that would be suitable these features when they’re stable. Linux distro world is. It might not SteamOS Based on Ubuntu. It technically the father of the it’s the big-business distro stands alongside Ubuntu and Mint for its ease most number of spin-off distros. complete beginners. This. the company behind the PC digital desktop icons. whereas most largely because it’s another corporate. slower computers. from media editing and so many more. as steampowered. here’s our rundown of the major distro groups. Ubuntu are merged into the Red Hat distribution. Software. they Manjaro in the world. As we mentioned above. Red Hat is a billion-dollar business www. worth mentioning because it funds below). this has lead to a proliferation of different versions of the Linux OS appearing. because it’s hardcore Linux geeks to servers. popular distro after it’s super-stable and can be put to many uses. This is Here’s more of modern. excellent way of testing the latest technologies community has taken the base a huge number of spin-offs have been created because Fedora tends to get them before most of Arch and created a pre-built Linux distro that – both official. From its www. Mint offers the simplicity of distribution system called Steam. a paid-for Linux distro. touch-like desktop. and is. including one used by enterprises and corporations. Q WorldMags. also called a rolling- unofficial – because it became such an easy release distro.redhat. enjoy from a box under your TV. Fedora luck with it. home streaming and version that’s known as Cinnamon. Features are tested in Fedora widely known – Linux distro and. The majority are general-use distros. and a more fancy Showing you how fluid the integrating controllers.com ashes comes a fresh and powerful desktop One of the older distributions It’s highly unlikely you’ll distro. WorldMags.io/ was spun out of the Debian project to create an isn’t as scary as it sounds.org drives a front for the Steam Big Picture mode. which eventually went bust. Mint orientated distro that www. The Manjaro for anyone and everyone to use. but there are ways of effectively getting the same Linux that you almost have it’s very stable and has complete repositories technology with a freely available distro. those with fancy interfaces. Debian is also come across Red Hat as desktop and complete software library. but A super-advanced version of It’s really designed for servers and experts. science. an example of how Linux is used in a fully Linux users wanted a traditional keyboard/ sponsored project and is much admired by commercial way. This of software. Debian itself can be thought of a bare. the developers easy interface and easy software centre.com also has a long-standing pedigree.mageia. A Ubuntu The Fedora project was big advantage is that Arch’s active community www. unusually.archlinux.net Coding Made Simple | 13 . www. for older. but with optimised versions www. such as Ubuntu Server. OpenSUSE technical side of distro releases. There are Linux distros tailored to a host of common uses. popular – or at least the most Linux technology.opensuse. Mageia was the store into one experience that you can created off the back of a long. It’s an complexity. because it comes with just freely used.com created by Red Hat as a test of experts delivers the latest builds of software This is arguably the most platform for cutting-edge before anyone else gets them. Over the years. with an easy installation. which offers a powerful but easy-to-use on the block.com awesome OS that’s exactly what you want. SteamOS is installation. It is.org have gone out of their way to try to make it Another business. but it also means you get an. which means that it is also very means you need to be an expert to have any easy to extend. accessible to all levels of users. n the Linux world. is constantly updated. running commercial Linux distro called Debian Red Hat Mandriva.net Linux distro guide A tantalising taste of the many different flavours of Linux. too. but also other distros. of the most popular in the world – Ubuntu (see however. so to help you get started if you’re interested in finding out more about Linux. of use yet manages to bring new features.ubuntu. and Android games and a device. 48% Exclusive access to the Linux Format subscribers- only area – with 1. & On iOroSid! And Bundle £77 For 12 months SAVE Includes a DVD packed with the best new distros. WorldMags. features and reviews. Instant packed full access on your of the hottest iPad.net Subscribe to Get into Linux today! Choose your Get into Linux today! package Print £63 For 12 months Digital £45 For 12 months Every issue The cheapest comes with way to get Linux a 4GB DVD Format. 14 | Coding Made Simple WorldMags. apps. lot more. Every new issue in print and on your iOS or Android device. Never miss an issue.net .000s of DRM-free tutorials. iPhone distros. The Lakes.uk/LINsubs Prices and savings quoted are compared to buying full priced UK print and digital issues.net Coding Made Simple | 15 . Offer ends 12/04/2016 WorldMags. NN4 7BF. WorldMags. Northampton. You will receive 13 issues in a year.net Get all the best in FOSS Every issue packed with features. tutorials and a dedicated Pi section. United Kingdom to cancel your subscription at any time and we will refund you for all un-mailed issues.ag/magterms. 3 Queensbridge. If you are dissatisfied in any way you can write to us at Future Publishing Ltd. Prices correct at point of print and subject to change. For full terms and conditions please visit: myfavm. Subscribe online today… myfavouritemagazines.co. File We can access the management. On a standard Linux Mint installation. Besides account is limited. Linux directory hierarchy. we’ll see commands or that we’ve got pathnames. outside of our home directory – it’s all taken care of by Mint’s 16 | Coding Made Simple WorldMags. text directory one level editing and music playing can all be done with not one single up through the . as such. to jump to the very top of the filesystem and see what the view is like from up there. the Firefox root access. right-clicking on things gives the usual and a rather menacing flashing cursor. For example. which lives at /home/user/ in the menu. we can get more information by using the -l (long) option: $ ls -l This shows us file metadata such as permissions. VLC for playing movies. you won’t have to painstakingly transcribe directory. Music done at the done from the command line. The ~ is shorthand context menus. but a # . viz. and so on. playing a video) – from the command line. access to the manipulation and the Transmission BitTorrent client. not least because it stirs up ignore our hungry cursor no more.net . If required. We find ourselves confronted with menu in the bottom-right. WorldMags. you should issue: $ cd / $ ls We see all kinds of tersely named directories. together with the directories of any other users that are on the system (of which there probably none).. there’s a system tray area to which diverse user@host:~$ applets may be added. our user’s directory. it’s a very powerful way to work. Perusing the aforementioned for our home directory. open windows will appear an arcane prompt of the form in the taskbar. and thanks to If we want to see a listing of all the files in the current tab-completion.net Get started with Mint and Python Take a crash course in how to use the command line and follow our guide to create your very first Python program. The /etc/ directory houses configuration files. pretty much anything you might be used to $ ls . So if we do click. you can access is granted through the sudo command (take a look quickly access things by typing a few characters into the at. doing in a GUI can be done – or at least instigated (for we will see a listing of the directory /home/ in which we’ll see example. LibreOffice Writer is a more than adequate word processor for almost there’s generally no reason to do anything with the filesystem everybody’s needs. but we recognise /home/ from being there a couple of sentences ago. The $ shows that we do not have including (but not limited to) the LibreOffice suite. root navigating the program groups in the Places menu. web browser.. We can navigate the directory hierarchy using the cd command. If things were arranged differently. which limits the amount of damage we can do. MS-DOS. last modified date and file size.” and a few others. Let us down the spines of many people. privileges.com/149/). But command line-fu. and start doing some long-repressed memories of darker times. don’t worry. Gimp for image Root is the superuser in Linux and. Downloads. It’s compatible with Microsoft Word files. terminal. we use the ls command. which advanced users enjoy manipulating. operator. we would see The idea of working at the command line sends shivers that a root shell has not a $ in its prompt. M int’s Cinnamon desktop (unlike Ubuntu’s Unity) is We shall begin this tutorial by opening the Terminal cosmetically quite similar to Windows: there’s a program from the menu. So if we type that in and lengthy hit Enter. Much “Pretty much anything you might directories for of your day-to-day computing can be be used to doing in a GUI can be Documents. you will find a plethora of pre-installed software. ownership information. In fact. but apart from that. which temporarily elevates our livesearch box. package manager. home directory at any time simply by calling cd with no All programming begins with simple text files. There isn’t a reasonable notion for attached to your system. lather and repeat >>> ‘hello there. too. So start the Python 3 interpreter by typing: issue a worldly greeting. And readable code is and then press Return to use our existing file. but that doesn’t stop them $ python3 helloworld. messages as a matter of course. Rinse. the moment of truth – let’s see whether we can do it with strings. the /dev/ names. which is not commence departure from nano with Ctrl+X.py being added or multiplied: If all goes to plan. and our worth adopting the newer 3. It’s known as a Read-Evaluate Print Loop based text editor. Your first ever type error – congratulations! Exit For a more thorough look at the command line. This enables us to shortcuts displayed on the bottom for searching (Ctrl+W). unless you’re morally particular program. If you’ve never used a terminal- returned to us. it’s easy to see how directory contains device nodes representing all the hardware such confusion may arise. friend’ with a cup of tea. For example. as is tradition in such matters. but on Linux. in ‘hellohellohello’ which careless typing is punished. The five-minute introduction at. then you might dismayed to learn that the (REPL). a friendly greeting should be displayed.linuxmint. so you may as well try that everything is a file. Disk partitions get names such as subtracting or dividing by strings. But it’s not just numbers that we can add up – command line. press Y to save necessary but does improve readability. We can return to our program and run it. If >>> ‘hello’ * 3 that didn’t happen.3333333333333333 As before.7 by default but it’s Python programs all use the . and we can arguments. So let’s do that to start with. it’s fun to explore and familiarise get confused with actual programming directives or variable yourself with how Linux does its filing. This is so they don’t program and lived to tell the tale.net Mint comes bundled with some pretty wallpapers. so attempting to do that sda1 or sdb2. Q WorldMags. WorldMags. welcome to the world of programming. our newly created directory and create our Python script: $ cd ~ $ cd ~/python $ mkdir python $ nano helloworld. enter Python commands and have the results immediately saving (Ctrl+O) and the like.py Mint currently uses the older Python 2. Type the following into nano: >>> 1 / 3 print(‘Hello world’) 0. Then settle down ‘hello there. we’ve had to enclose our string in quotes. It is possible calculator to perform basic arithmetic: to select text and paste it using the middle mouse button. We call them strings because Python can run our program: they are strings of characters. which you peruse by right-clicking the desktop and choosing Change Desktop Background. There are some helpful guidance and a different prompt: >>>.net Coding Made Simple | 17 . Let’s navigate to new directory in which to store our Pythonic labours. satisfied in the knowledge that you wrote a Notice that we enclose strings in quotes. Now We’ve put spaces around each operator. and the primary video card lives in /dev/dri/ results in an error. and then create a use the humble nano editor to create one. Since strings can contain spaces. terse prompted to save any changes). >>> 9 ** 2 Getting Python to print messages to the terminal is easy – 81 we use the print() function. Programmers encounter diverse error card0. now. The nano text editor is pretty easy to $ python3 work with – you can press Ctrl+X at any time to exit (you’ll be We are presented with some version information. We’re going to create our first Python towards Python programming now. but >>> 32 * 63 positioning of the cursor is done with – and only with – the 2016 cursor keys.x series. For example. interpreter is good for trying out code snippets but it’s no use com/tutorial/view/100. we can use it as we would a standard mouse can’t be used as you might expect here. see the the interpreter by pressing Ctrl+D or typing exit() . ’ + ‘friend’ the editing and running stages until it works. is going to opposed. We’re going to focus our attention for proper coding. That said. all from the command line. This is quite a radical idea to digest.py extension. Back at the A Good Thing. net the UK’s best-selling Linux magazine OUT NOW! DELIVERED DIRECT TO YOUR DOOR Order online at supermarket.co.uk or find us in your nearest WorldMags.Get WorldMags. newsagent or bookstore! .myfavouritemagazines. coding won’t work correctly. learn to code is almost an essential for the open. Promise. If you knowledge is more than useful – it’s an time to pick up. WorldMags. as a don’t know how to Python. access to every language under your friends are going to be being taught in schools. If you’ve always wanted to learn. helps you get more out of the minutes to create a fun game in Python.net Coding Made Simple | 19 . Knowing how Linux itself. laughing at you… Knowing a bit of code helps with using So grab our hand and let’s take just a few We’re not being flippant. can open doors to a new career or which languages are right for you and your source fiend. Other than taking a bit of school curriculum and web development. Be it basic Bash scripting or help you troubleshoot why that webpage projects. jump straight in with our quick-start guide. C oding is the new cool. then see how you can tackle the new knowing how to read a bit of PHP. WorldMags. terminal.net Coding isn’t scary. there’s also no cost and. the sun is just waiting an apt-get away. particularly now that coding is FLOSS user. all essential skill. 7 with: The IDLE development environment is purpose-built for Python. are not defined for strings. age. Most distributions version yet. converting a string to a float. So open up a terminal (LXTerminal in Raspbian) and start Python 2. wherein Python commands can brackets in the print line are only required in example. the looks something like its target type: for interpreter. then the 3-point-something. >>> age = float(age) The last line shows that we can also So we’ll use it to now to introduce some >>> age multiply strings – division and substraction. immediately. Variables in Python are automatically for strings. tacking the latter string on to As you might suspect. of Python installed. ' is '. type(name) and so on.7 yum. if you can’t find an icon for it. If this returns a result that begins with 2.2) is now Python 3. so you can Data types dictate how data is >>> name = 'Methuselah' easily see the changes you have enacted. let’s introduce the idea of variables: interpreter will show you its value. If that fails to produce the goods. but the interpreter number (one with a decimal part) with: 'BetelgeuseBetelgeuseBetelgeuse' is a great way to test smaller code fragments. using the can be quite subtle. however.0') will work. $ python2 -V pygame) and should be able to install it through While the latest release (1. Installing Pygame. ElementaryOS) with apt-get install idle . start at the command line. notably Arch Linux and the the appropriate package manager – pacman compatible. on the other hand. If. then use the Pygame module to make a simple game. Python can also go the other the division operator / works differently if We can assign values to variables. one of its arguments is a float: Installing Python and Pygame If you’re using Raspbian on the Raspberry Pi everything is fine. float('10.net . characters) and age is an integer (a whole >>> 'Hello ' + 'world' You can exit the interpreter at any point by number). will bundle the IDLE environment with each version be precise) for this tutorial. and use print but this will only work if the original string Both methods start the Python interactive statements to see them. in which we’ll explore the basics of the language.') function str() .9. pressing Enter name is a string (short for a string of the end of the former. Follow the instructions in the box below to check which version of Python you have and install Pygame.net Get with the program T his is going to be a very gentle introduction to programming in Python. Thus: causes Python to display a global greeting. then check Python 2 Users of other distributions will find a similarly chances are that you already have at least one availability with the command: named package (on Arch it’s called python2- (probably two) versions of Python installed. fundamental coding concepts and constructs. so addition works differently the following incantation: versions. Some distros. zypper or whatever. don’t ship the 2. Here the + operator stands for >>> print('Hello World') assigned a type based on their content. Just as division works differently for first Python program. or an Integrated Development – we can transmute age to a floating point >>> 'Betelgeuse' * 3 Environment (like IDLE). So concatenation. but they don’t do any harm and it’s but float('Rumplestiltskin') will not. That we are able to do this is testament to the power of Python and Pygame – much of the tedium inherent in game work is abstracted away and. then command to install Pygame: then go hunting in your distro’s repos. WorldMags. You can check this by typing 'Hello world' pressing Ctrl+D or using the exit() command. Just typing the variable name into the however. Python version by typing: Users of Debian-derived distributions (including try running the commands $ python -V Raspbian on the Pi) should use the following idle or idle2 . start up IDLE and start a command prompt from there by choosing Python 2.7 Shell from the Window menu. >>> str(123) + str(456) For larger programs. Alternatively. in Python 2 >>> print(name. so let’s do that now. you see $ sudo apt-get install python-pygame or any flavour of desktop Linux. and the effects of this >>> age = 930 can convert ints or floats to strings. be typed at the >>> prompt and evaluated Python 3. for the most part we work with intuitive commands. It is here that we will forge our good practice to write. once we’ve covered some elementary programming constructions. 20 | Coding Made Simple WorldMags. Technically.7 to series by default. ' years old. You can install it on $ python2 Ubuntu (or in this case. Check your default pull it in as a dependency. no distributions are shipping this recently released Fedora 22. so we’ll stick with Python 2 (2. Whether on a Raspberry Pi or a larger machine. it makes sense to work in Some types can be coerced to other types '123456' a text editor. change way. them to our hearts’ content. wherever possible. by carefully typing out ambidextrous code that will run in both floats and ints. We represented internally. First. for example. For example. Iterating over each list item. For this reason. make your move’ prompts. You Only Get One Match. like the humble for loop below. and the second player either with the goal of forming unbroken lines such as always blocking one side of your chooses a colour or places another black and (horizontal. Another type of loop is codeblock and causes our loop to run. perfect player) can force a win if they start. in fact. these are of no consequence. This one. which is friend/other personality with which to play. Entering a blank (even in the absence of any other coding print() line being issued five times – once for line after the print statement ends the knowledge) that some counting is about to each value in the range. or even subtracting energy from all enemies just smitten by a laser strike. We have for now we just need to know that range(5) usually using four spaces. Work by L Victor code modification: just disobey the first few for a beginner tutorial).6000000000000001 Such quirks arise when fractions have a non-terminating binary decimal expansion. The basic rule set as we’ve modify the code to force use of swap2.000 you can play. happen. so you’ll need to find a Allis has shown that a good player (actually a ‘Player x. vertical or diagonal) of length 5. Yet to become a master takes player one to choose colours. opponent’s ‘open three’ line or obstructing a another white counter on the board and allows Traditionally. with the line. when used in the while loop. It could be appending entries to a list. >>> 3/2 WorldMags. 1. big tournaments use a game. table row or enemy manually would be repetitive and make for lengthy.net Coding Made Simple | 21 . but it’s used in some variations. So our variable count is going consistent. it implies to iterate over each of these values. WorldMags. returns a list consisting of a range of following the for construct ‘belong’ to it. If you don’t indent the second variables is a good idea. … print('iteration #'. Python shouts at you. which will give you only the number of decimal places you require. >>> 1. but Such codeblocks need to be indented. The first player years ago. adding up totals for each row in a table. (Besides. why make life hard for yourself?) Sooner or later. features after the first line. in this case. When you hit Enter There are all kinds of Pygame-powered games. on the board. an integer by the looks like [0. count) integers. you’ll run into rounding errors if you do enough calculations with floats. The range() function. 2. Sometimes. though you can introduced a new variable. You are free to but we’ve gone for the smaller 15x15 board years of practice. the prompt changes to … lots of fireworks but limited means of ignition. They can be worked around either by coercing floating point variables to ints. We haven’t included implemented it heavily favours the starting entirely possible to obey this rule without any an AI (that would be somewhat too complicated player (traditionally black). The Alternatively. programmers desire to do almost the same thing many times over. We’ll see this in practice when we program our Gomoku game later. Players take turns to each place a Bovu game with their desktop. We’ll cover lists in just a moment.net >>> 1 >>> 3/2. There’s a few things going on here.5 Funny the difference a dot can make. ‘broken four’. when we mean 2. there are plenty of online versions mitigate against this. and KDE users get the similar starting strategy called swap2. Check it out at. places two black counters and one white one counter on the intersections of a square grid It’s easy to figure out some basic strategies. but it’s worth being aware of them.0 . the board has 19x19 intersections. Going loopy Often. originated in China some 4. because the interpreter knows that a discrete codeblock is coming and the line(s) >>> for count in range(5): isolation. we have loops.2 * 3 0. Python is all about brevity. or using the round() function. Check out the following doozy: >>> 0. Giving sensible names to your the interpreter. Note that we have been lazy here in typing simply 2. 3. hard-to-read code. Rather than iterating over a How to play Gomoku Gomoku is short for gomokunarabe. 4]. To roughly Japanese for ‘five pieces lined up’. which you can verify in use as many as you like so long as you’re name of count .ly/LXF202-onematch. WorldMags.net list, our while loop keeps going over its code 0 up to and including 99, which could equally really only scratching the surface with some block until a condition ceases to hold. In the well be achieved with range(100) in Python 2. basic graphics and font rendering. We need following example, the condition is that the However, the concept is more powerful – for a single function, exit() , from the sys user claims to have been born after 1900 and example, we can get a list of squares using the module so that we can cleanly shut down before 2016. exponentiation (to the power of) operator ** : the game when we’re done. Rather than >>> year = 0 >>> squareList = [j ** 2 for j in range(100)] importing the whole sys module, we import >>> while year < 1900 or year >= 2015: And after that crash course, we’re ready to only this function. The final import line is just … year = input("Enter your year of birth: ") program our own game. You’ll find all the code for convenience – we have already imported … year = int(year) at, so it pygame, which gives us access to pygame. Again the loop is indented, and again you’ll would be silly to reproduce that here. Instead, locals , a bunch of constants and variables. need to input a blank line to set it running. we’re focusing on the interesting parts, in some We use only those relating to mouse, We’ve used the less than ( < ) and greater than cases providing an easier-to-digest fragment keyboard and quitting events. Having this or equal to ( >= ) operators to compare values. that you can play with and hopefully see how it line here means we can access, for example, Conditions can be combined with the logical evolves into the version in the program. To dive any mouse button events operators and , or and not . So long as year in and see the game in action, download with MOUSEBUTTONDOWN without has an unsuitable value, we keep asking. It is gomoku.py and copy it to your home directory, prefixing it with pygame.locals . initialised to 0, which is certainly less than and run it with: 1900, so we are guaranteed to enter the loop. $ python2 gomoku.py It’s all in the (Py)game We’ve used the input() function, which returns On the other hand, if you want to see Throughout the program, you’ll notice that whatever string the user provides. This we some code, open up that file in IDLE or your some variables are uppercase and some are store in the variable year , which we convert to favourite text editor. Starting at the first line is a not. Those in uppercase are either an integer so that the comparisons in the reasonable idea… It looks like: from pygame.locals or should be while line do not fail. It always pays to be as #!/usr/bin/env python2 considered constants, things that do not prudent as possible as far as user input is This line is actually ignored by Python (as change value over the course of the game. concerned: a malicious user could craft some are all lines that begin with # ) but it is used by Most of these are declared after the import weird input that causes breakage, which while the shell to determine how the file should be statements and govern things like the size of not a big deal here, is bad news if it’s done, say, executed. In this case we use the env utility, the window and counters. If you want to on a web application that talks to a sensitive which should be present on all platforms, to change the counter colours, to red and blue, database. You could change 1900 if you feel find and arm the Python 2 executable. For this for example, you could replace the values anyone older than 115 might use your program. nifty trick to work, you’ll need to make the of WHITE and BLACK with (255,0,0) Likewise, change 2015 if you want to keep out gomoku.py file executable, which is achieved and (0,0,255) respectively. These variables (honest) youngsters. from the command prompt (assuming you’ve are tuples (a similar structure to a list, only it copied the file to your home directory, or can’t be changed), which dictate the red, The opposite of listless anywhere you have write permission) with: green and blue components of colours. We mentioned lists earlier, and in the exciting $ chmod +x gomoku.py Next you’ll see a series of blocks project that follows we’ll use them extensively, You’ll find you can now start the game with beginning with def: – these are function so it would be remiss not to say what they are. a more succinct: definitions and, as is the case with other Lists in Python are flexible constructions that $ ./gomoku.py codeblocks in Python, they are demarcated store a series of indexed items. There are no Next we have three import statements, by indentation. The initGame() function restrictions on said items – they can be strings, two of which ( pygame and sys ) are initialises the play area. Here’s a simple ints, other lists, or any combination of these. straightforward. The pygame module makes version that shows what this function does: Lists are defined by enclosing a comma- easy work of doing game-related things – we’re WIN_WIDTH = 620 separated list of the desired entries in square GRID_SIZE = (WIN_WIDTH) / 14 brackets. For example: WHITE=(255,255,255) >>> myList = ['Apple', 'Banana', 'Chinese BLACK=(0,0,0) Gooseberry'] BGCOL=(80,80,80) The only gotcha here is that lists are zero- def initGame(): indexed, so we’d access the first item of our screen.fill(BGCOL) list with myList[0] . If you think too much like a for j in range(15): human, then 1-indexed lists would make more pygame.draw.line(screen, WHITE, (0, j sense. Python doesn’t respect this, not even a * GRID_SIZE), (WIN_WIDTH, j * GRID_ little, so if you too think like a meatbag, be SIZE)) prepared for some classic off-by-one errors. pygame.draw.line(screen, WHITE, (j * We can modify the last item in the list: GRID_SIZE, 0), (j * GRID_SIZE, WIN_ >>> myList[2] = 'Cthulhu' WIDTH)) Lists can be declared less literally – for pygame.init() example, if we wanted to initialise a list with pygame.display.set_caption(‘LXF Gomoku’) 100 zeroes, we could do: screen = pygame.display.set_mode((WIN_ >>> zeroList = [0 for j in range(100)] WIDTH,WIN_WIDTH)) This is what is known as a list comprehension. initGame() Another example is Many tense counter-based battles can be pygame.display.update() >>> countList = [j for j in range(100)] had with your very own self-programmed If you add the three import lines to the which results in a list containing the integers version of Gomuku. beginning of this, it is actually a perfectly 22 | Coding Made Simple WorldMags.net WorldMags.net the display, hence the last line. track of the game, we use a two-dimensional Astute readers will notice that the grid square array (a list of lists) in the variable grid . overruns ever so slightly at the edges. This This is initialised as all 0s, and when a player is because drawing 15 equispaced parallel lines makes a move, a 1 or a 2 is entered accordingly. divides the board into 14, but 620 (our window The first job of the tryCounterPlace() function size) is not divisible by 14. However, when we is to reconcile the mouse coordinates where add in some window borders – since we want the user clicked with a pair of coordinates with to place counters on the edge lines as well – which to index the grid variable. Of course, the 620 turns out to be a very good number, and user may not click exactly on an intersection, we were too lazy to change it. Although rough so we need to do some cheeky rounding here. around the edges, it’s still testament to If the player clicks outside of the grid (e.g. if Pygame’s power and Python’s simplicity that they click too far above the grid, so the y we can do all this in just a few lines of code. coordinate will be negative) then the function Still, let’s not get ahead of ourselves – our returns to the main loop. Otherwise, we check game still doesn’t do anything. that the grid position is unoccupied and if so Joel Murielle’s graphical Gomoku is draw a circle there, and update our state array available from the Pygame website. Pygame takes all the pain out of working Finer points grid . A successful move causes our function to From here onwards, we’ll refer to the actual return a True value, so looking at line 111 in the with sprites – notorious troublemakers. code, so any snippets we quote won’t work in code, we see this causes the next player’s turn. isolation – they’re just there to highlight things. But before that is enacted, by valid Python program. The initGame() You’ll notice that the FONT variable isn’t the updatePlayer() call at the top of the loop, function doesn’t do anything until it is called defined with the other constants; this is we call the checkLines() function to see if the at the last line, by which time we’ve already because we can’t use Pygame’s font support latest move completed a winning line. Details of initialised Pygame, set our window title, and until after the Pygame’s init() method has how this check is carried out are in the box. set the window size to 620 pixels. All been called. Let’s look at the main game loop When a winning counter is detected by variables set up outside of function right at the end of the code. The introductory our state-of-the-art detection algorithm, definitions – the five all-caps constants at clause while True: suggests that this loop will the winner() function is invoked. This replaces the beginning and screen – are accessible go on for ever. This is largely correct – we want the text at the top of the screen with a inside function definitions; they are known to keep checking for events, namely mouse message announcing the victor, and the as global variables. Variables defined inside clicks or the user clicking the exit button, until gameover loop is triggered. This waits for a function definitions are called ‘local’ – they the game is done. Obviously, we exit the loop player to push R to restart or rage quit. If a cease to exist when the function exits, even when the application quits – clicking the restart is ordered, the player order is preserved if they have the same name as a global button triggers a QUIT event, which we react and, as this is updated immediately before variable – again, something to be aware of in to with the exit() function from the sys checkLines() is called, the result is that the your future coding endeavours. The variable package. Inside the main loop, the first thing loser gets to start the next round. screen refers to the ‘canvas’ on which our we do is call the updatePlayer() function, This is a small project (only about 120 lines, game will be drawn, so it will be used which you’ll find on line 32. This updates the not a match for the 487-byte Bootchess you extensively later on. The initGame() text at the top of the screen that says whose go can read about at function’s first act is to paint this canvas a it is, drawing (‘blitting’) first a solid rectangle so technology-31028787), but could be extended delightful shade of grey (which you’re very any previous text is erased. in many ways. Graphics could be added, welcome to change). Then we use a loop Next we loop over the events in the events likewise a network play mode and, perhaps to draw horizontal and then vertical lines, queue; when the player tries to make a move, most ambitiously, some rudimentary AI could making our 15x15 grid. None of this artwork the tryCounterPlace() function is called, with be employed to make a single-player mode. will appear until we tell Pygame to update the mouse coordinates passed along. To keep This latter has already been done… Reading between the lines Part of Key Stage 2 involves learning to elements to its right have the same value. In check row positions further right than this understand and program simple algorithms. Python, it would look like this: because our algorithm will reach out to those We’ve already covered our basic game flow positions if a potential line exists there. Our algorithm – wait for a mouse click (or for the for j in range(15): variable idx effectively measures the length of user to quit), check whether that’s a valid move, for k in range(10): any line; it is incremented using the += check if there’s a line of five, and so on. At the pl = grid[j][k] operator, short for idx = idx + 1 . heart of that last stage lies a naïve, but if pl > 0: The algorithm is easily adapted to cover nonetheless relevant, algorithm for detecting idx = k vertical and diagonal lines. Rather than four whether a move is a winning one. while grid[j][idx] == pl and idx < 14: separate functions, though, we’ve been clever Consider the simpler case where we’re idx += 1 and made a general function lineCheck() , interested only in horizontal lines. Then we if idx - k >= 5: which we call four times with the parameters would loop over first the rows and then the # game winning stuff goes here necessary for each type of line checking. Said columns of our grid array. For each element, parameters just change the limits of the for we would check to see that it is non-zero (i.e. Note that the inner loop variable k reaches a loops and how to increment or decrement grid there is a counter there) and whether the four maximum value of only 9. We do not need to positions for each line direction. WorldMags.net Coding Made Simple | 23 WorldMags.net Languages: An overview O ne of technology’s greatest curly brackets used by so many other allocate memory as it is required achievements was IBM’s Fortran languages for containment purposes. Likewise, and free it when it’s no longer compiler back in the 1950s. It there’s no need to put semicolons at the end of required. Failure to do so allowed computers to be programmed using every line. Python has a huge number of extra means that programs something a bit less awkward than machine modules available, too – we’ve seen Pygame, can be coerced into code. Fortran is still widely used today and, and our favourite is the API for programming doing things they while some scoff at this dinosaur, it remains Minecraft on the Pi. shouldn’t. highly relevant, particularly for scientific Unfortunately, 40 computing. That said, nobody is going to Beginner-friendly years of widespread C start learning it out of choice, and there are Other languages suitable for beginners are usage have told us that all manner of other languages out there. JavaScript and PHP. The popularity of these this is not a task at which Traditionally, you have had the choice comes largely from their use on the web. humans excel, nor do we seem between hard and fast languages – such as JavaScript works client-side (all the work is to be getting any better at it. Informed by Java, C and C++ – or easy and slower ones, done by the web browser), whereas PHP is our poor record, a new generation of such as Python or PHP. The fast languages server-side. So if you’re interested in languages is emerging. We have seen tend to be the compiled ones, where the code programming for the web, either of these languages from Google (Go), Apple (Swift) has to be compiled to machine code before it languages will serve you well. You’ll also want to and Mozilla (Rust). These languages all can be run. Dynamic languages are converted learn some basic HTML and probably CSS, too, aim to be comparable in speed to C, but at to machine code on the fly. However, on some so you can make your program’s output look the same time guaranteeing the memory level, all programming languages are the same nice, but this is surprisingly easy to pick up as safety so needed in this world rife with – there are some basic constructs such as you go along. PHP is cosmetically a little malicious actors. loops, conditionals and functions, and what messier than Python, but soon (as in The Rust recently celebrated its 1.0 release, makes a programming language is simply how Matrix) you’ll see right through the brackets and maybe one day Firefox will be written it dresses these up. using it, but for now there are For those just starting coding, it’s simply baffling. “Although any language will by a number of quirks and pitfalls that users of Opinions are polarised on what is the best language to learn turns impress and infuriate you, traditional languages are likely to find jarring. For one first of all, but the truth is that Python has a lot going for it.” thing, a program that is there isn’t one, though for very ultimately fine may simply small people we heartily recommend Scratch. and dollar signs. It’s also worth mentioning refuse to compile. Rust’s compiler aims for Any language you try will by turns impress and Ruby in the accessible languages category. It consistency rather than completeness – infuriate you. That said, we probably wouldn’t was born of creator Yukihiro Matsumot’s desire everything it can compile is largely recommend C or Haskell for beginners. to have something as “powerful as Perl, and guaranteed, but it won’t compile things There is a lot of popular opinion that favours more object-oriented” than Python. where any shadow of doubt exists, even Python, which we happily endorse, but many Barely a day goes by without hearing about when that shadow is in the computer’s are put off by the Python 2 versus 3 some sort of buffer overflow or use-after-free imagination. So coders will have to jump fragmentation. Python has a lot going for it: it’s issue with some popular piece of software. Just through some hoops, but the rewards are probably one of the most human-readable have a look at. All of there – besides memory safety and type languages out there. For example, you should, these boil down to coding errors, but some are inference, Rust also excels at concurrency for readability purposes, use indentation in easier to spot than others. One of the problems (multiple threads and processes), your code, but in Python it’s mandatory. By with the fast languages is that they are not guaranteeing thread safety and freedom forcing this issue, Python can do away with the memory safe. The programmer is required to from race conditions. Programming paradigms and parlance With imperative programming, the order of have its own variables (attributes) and its own is not for the faint-hearted. This very abstract execution is largely fixed, so that everything code (methods). This makes some things style is one in which programs emphasise happens sequentially. Our Gomoku example is easier, particularly sharing data without more what they want to do than how they done largely imperative style, but our use of resorting to lengthy function calls or messy want to do it. Functional programming is all functions makes it more procedural – global variables. It also effects a performance about being free of side-effects – functions execution will jump between functions, but toll, though, and is quite tricky to get your head return only new values, there are no global there is still a consistent flow. around. Very few languages are purely OO, variables. This makes for more consistent The object-oriented (OO) approach extends although Ruby and Scala are exceptions. C++ languages such as Lisp, Scheme, Haskell this even further. OO programs define classes, and Java support some procedural elements, and Clojure. For a long time, functional which can be instantiated many times; each but these are in the minority. Functional programming was the preserve of academia, class is a template for an object, which can programming (FP) has its roots in logic, and but it’s now popular within industry. 24 | Coding Made Simple WorldMags.net which will provide these additional peripherals. as evidenced by industry consistently reporting difficulties in finding suitably qualified applicants for The FUZE box gives you tech jobs in the UK. It’ll be disappointing if the from the concerned parents and confused particularly like setups such as the FUZE box. then education secretary Michael Gove acknowledged that the current ICT curriculum was obsolete – “about as much use as teaching children to send a telex or travel in a zeppelin”. but rather There are also many free resources on the Speaking of tiny things. the BBC will distribute 20-pin edge connector. Yes. Rightly not to mention a glorious array of Pi cases as though this compilation all takes place on or wrongly. and it’ll plug straight into sensors. Python. The Micro:bit features a web. too. mouse.uk/ directions in which one can seek help. all-in-one device. and code entered here your progeny hollers at you (that’s what kids do. world. learning the dark example. which connects it Python documentation) are a little dry for about a million ‘Micro:bit’ computers to Year 7 to the Pi or another device. programmed in a number of languages genuinely thrilled that children as young as Mercifully.net Coding Made Simple | 25 . the Kano. to stress that the device is in no way intended Linux Format – Coding in the classroom I n September 2014. the Raspberry Pi (see and training for this venture. the more about it at www. then you can get The devices have gravity and motion claiming it is vital for understanding how the one for about £25. mediacentre/mediapacks/microbit. Microsoft on their Master Skills to lesser teachers easy enough to get to grips with. the ICT must be compiled before being downloaded to the Micro:bit. the UK embarked on a trailblazing effort that saw coding instilled in the National Curriculum. clarification on the finer details are sketchy. many private firms will benefit available to protect it from dust and bumps. WorldMags. But there are more wholesome albeit chunkier. You can find out curriculum. and we will enjoy the BBC Newsnight interview with page 82 for more) is another great way to are relieved to hear it will not tie the the then Year of Code chief.bbc. HDMI cable and rings that could connect further Learning opportunities possibly a wireless adapter. we’re Ethernet cable to your router is not an option. it’s all too easy to end up in cable. billed as a DIY computer). then. but machines can work in tandem. Coding skills are much sought after. if trailing an sensors or contraptions. They can be Criticism and mockery aside. “Without any coding. If you’re willing to product to its Windows 10 platform. Such a pairing these skills alongside their offspring. SD card. even as we speak. Of course.co. For one thing. your telly. Raspberry Pi’s tiny form factor is appealing. The arts of syntax. you’ll need to scavenge a some buttons. but it seems points of recursion and abstraction. to compete with the Raspberry Pi. – a visual programming language. wherein she provide a learning platform. “What’s the plural of mongoose?” and curriculum was ‘as much use as present. despite settle for the older B+ model. amidst the pre-launch hush (though it should be then follows through seeking teaching kids to send a telex’. admits not knowing how to code. when based. Microsoft-provided code editors are all web- Fear now. requiring instead to be programmed 400 ‘Master Teachers’ who could then pass and distributions such as Mint and Ubuntu are from a more capable device. induced tiny hell. The device – indeed the combination WorldMags. they means of communicating with the outside Linux install will provide a great platform to cannot function as standalone computers. have no means of output besides a 5x5 LED will be necessary for the Micro:bit to have a Refurbishing an old machine with a clean array. to compile locally is offered. code editors can’t be used offline or no option kids resulting from the new computing which embed the Pi into a more traditional. When the initiative was announced in 2013. is generously providing the software around the country. Unlike the Raspberry Pi.” available in schools now). and most of this would be spent on training just do just this. Some of them (such as the official new learning regimen. so that the kids. These are even smaller than the Pi. There are five GPIO keyboard. there are many kits available (for including C++. JavaScript and Blocks five are. as well as Bluetooth and world works. everything you need to start The ‘Year of Code’ was launched to much fiddling with registers or making GPIO-based mischief. you’ll always find great but with a heavy rotation of USB devices Micro:bit spokesbods have been keen tutorials monthly in magazines such as thrown in. Far more important was imparting coding wisdom unto the young padawans. though this was slightly quelled as details emerged: a mere pittance was to be added to the existing ICT allocation. We Microsoft servers. All the software you need is free. semantics and symbolism. to coincide with the to complement it. but we’d encourage adults to learn pupils. fanfare. ye parents. At apparently).com. Fans of schadenfreude Besides a stray PC. If you have the time and some knowledge. for five. at least as far as how governmental blunder. too. Not all of them are going to be thrilled at having to program them. you’ll get a teacher to maintain order and provide defence against any potential pranksters. provides the The Code Club phenomenon is spreading with more on the way. while these days kids expect them to provide a constant barrage of entertainment in the form of six-second cat videos or 140-character social commentary. This kind of community thinking is very much in the spirit of open source. It’s an ambitious introduces core ideas. any entry barrier to getting into coding is fine by us. You can find out more at material. then a term of web design (HTML and CSS). Projects are carefully designed to keep kids interested: they’ll be catching ghosts and racing boats in Scratch. Code Club also provides three specialist modules for teachers whose duty it is to teach the new Computing curriculum. Back then. candidates will be represented as a string of bits. concluding with a final term of grown-up Python coding.to six-year-olds. if not entirely obliterates. requires students to learn at least Throughout the curriculum.uk. The final stage.to 11-year-olds and consists of two terms of Scratch programming. All the tutorials are prepared for you and if you can persuade a local primary school to host you. and doing the funky Turtle and keeping tabs on the latest Pokémon creatures in Python. to introduce the idea of formalising instructions.net .net of the device and the Pi – has a great deal of potential but there exists some scepticism over whether anything like the excitement generated by the 1982 launch of BBC Micro will be seen again. armed with commercial interest and corporate control. Boolean algebra. functions information security – skills the want of which studying Kohonen or Knuth alongside Kant. providing 26 | Coding Made Simple WorldMags. students will coding populace. or binary arithmetic. and data types. and pupils two programming languages and understand also learn the vital skills of online privacy and are learning Python alongside Mandarin. Q Code Clubs There are also over 2. You will require a background check.codeclub. and schools (or other kind venues) worldwide. the scheme will also lead data. Alongside this. such as loops and different types of information can all be project. WorldMags. £100. You’ll now find them as far afield www. They will also necessary to address the skills shortage in learning to use web services and how to gather gain insights into the relationship between this area. to much-needed diversification among the aged 11 to 14. The project materials clubs across the UK. but perhaps such a radical step is variables. computers were new and exciting. The Cortex M0 ARM The first. The second stage (ages 7 to 11) information theory. though. provide space and resources for this noble extracurricular activity. it’s well worth volunteering as an instructor. Algorithms battery-powered Micro:bit.org. Code Club. But anything that lowers. Get with the program The syllabus comprises three Key Stages. Students will also touch on has led to many an embarrassing corporate or then we’ll be thrilled.000 volunteer-run code an access-for-all gateway to coding free from as Bahrain and Iceland.000 courtesy of Google. have already been translated into 14 languages. If it works out. We also look forward to ne’er-do-well students hacking each other’s Micro:bits or engaging them in a collaborative DDOS attack on their school’s infrastructure. With luck. to name but a few. The Code Club syllabus is aimed at 9. covers processor is at the heart of the algorithms in a very general sense. for secondary students hardware and software. will be described in terms of recipes and schedules. WorldMags.net The home of technology techradar.com WorldMags.net . We’re going to look at a more general purpose tool called Now we’ll change up our program slightly.” called name interface’s major containing the string features opposite. ‘Dave’ . We have declared a variable run-through of the quantities that. and you probably realise that the same effect could be achieved just by changing ‘world’ to ‘Dave’ in the original program – but there is something much more subtle going on here. Geany is pretty basic as far as IDEs go – in fact. so we have no need for this. such as IDLE for Python (see page equally well call /usr/bin/python3 directly. going to happen. Our print() function above does our prompting for us. So our Python 3 code should begin: huge project involving complex build processes. which will be used to prompt the user for input. it’s more of a text editor on steroids than an so make our greeting a little more customisable. well.net . You probably knew what was to our python/ directory to select the file. This is why #!/usr/bin/env python3 integrated development environments (IDEs) exist – so that The env program is a standard Linux tool that is always the editing. Before you start. A tab 28 | Coding Made Simple WorldMags. name) $ sudo apt-get Note the space install geany after Hello . Python is terribly fussy about indentation. but it is more than sufficient for this tutorial. linking and debugging can all take accessible from the /usr/bin/ directory. vary. It keeps track of place on a unified platform (and you have a single point at where various programs are installed. vary. We’re going to Geany. Before we go further. unless you have some personal You’ll find Geany in Mint’s repositories. On Mint. running and debugging even The grown-up way to begin Python files is with a directive simple programs can rapidly become painful. you still should be. our shebang could for a particular language. Edit the code IDE. We can test our code by pushing F5 or clicking the py program from before: Select File > Open and then navigate Run button (see annotation). In the terminal window. by show how variables can be used as placeholders. and even if it wasn’t. because this can differ which to direct programming rage).net Get started with IDEs Speed up your programming workflow by using Geany. T he cycle of editing. which level we are at in a nested loop. The input() function can also be given a string argument. it’s worth talking about tabs and spaces. so you can install it grievance) so that it looks like this: either from the Software application or by doing: name = ‘Dave’ $ sudo apt-get update print(‘Hello ’. you need to install Geany from Mint’s repositories. a lightweight integrated development environment. 92). which takes a line of user input and returns that string to our program. input() . and in doing some measures. We can start by opening up our helloworld. So known as a shebang. Variables allow us to abstract away specifics and deal with quantities that. Correctly indenting code makes it easy to demarcate code blocks – lines of code that collectively form a function or loop – so we can see. WorldMags. or whatever characters you can muster. type your name. This is a line that tells the shell how it imagine how ugly things can get when working on a ought to be run. We can elaborate on this concept a little more by introducing a new function. compiling. Change the first line to name = input() and run your code. (keeping the shebang above. and press Return. Some IDEs are tailored wildly from distro to distro. Now start Geany from the “Variables allow us to abstract otherwise the output would look a Places menu. The program took your input and courteously threw it back at you. well. There’s a quick away specifics and deal with bit funny. for example. case. but just because an editor renders a tab character as this clause – so long as they respect the indentation. space bar eight times. We can put as many lines as we want in editor. we can also use likely to break it. The code we’ve just introduced is first. Python happily works with files that The else block is run when the condition is not met. though. function returns the length of a string. the else block from above can be if name == ‘Agamemnon’: included. The reason Python is fussier than other languages about Note that strings are case-sensitive. Of course. recognition. name) perhaps the PyDev plugin for Eclipse. you’re typing. don’t forget IDLE. If the you choose to do it. Geany opens your recent files in tabs. As well as testing for equality. Code folding Code editor Code folding is de rigueur for any IDE. and keywords are highlighted. but it saves happier with a couple of terminals open – you wouldn’t be the you considerable effort. WorldMags. say. The len() disposal to illustrate this. So if you’re working on a more involved. Tabs By default. When the program finishes or breaks. represents a fixed amount of white space decided by the text greeting is issued.. which is packaged with Python – highly readable – we use the == operator to test for equality we cover it in the Raspberry Pi chapter on page 92. If you want to else: check out something more advanced. we wish you good luck with your condition is met (ie Agamemnon is visiting). We need some more coding concepts at our the greater than ( > ) and less than ( < ) operators. you can study any output or error messages here before closing it. Let’s start with the if conditional. Python eight spaces. multi-file project. Or maybe you’re It can be hard to get used to the autotabbing. So just adding a random indent to your code is of our program. Q WorldMags. so someone called these matters is because indentation levels actually form part agamemnon would not be recognised as an old acquaintance of the code. variables and imports in the current file.net The Geany interface Run button The Run button (or F5) will save and execute your Python program in a terminal. – in this use tabs or spaces. see PyCharm or print(‘Hello ’. Clicking on the + or . However and use a colon to indicate a new code block is starting. Agamemnon uses it. so long as they’re consistent. Also. print(‘Ah. together with the line on which they are declared. noting that Geany print(‘My what a long name you have’) automatically indents your code after the if and else Now anyone whose name is 10 characters or more gets statements. if that behaviour is still desired. related code is just one click away.will reveal or collapse Geany is good at guessing the language the block of code on the adjacent line. so we could instead Suppose we want our program to behave differently when make our if statement: someone named. too. Clicking will take you straight there. Symbols The Symbols tab lists all the functions.) There are many other IDEs besides Geany.. my old friend.net Coding Made Simple | 29 . the program behaves exactly as it had done before. that doesn’t make it equivalent to pushing the knows that they all should be run when the condition is met. then a special continued adventures in Linux and coding. The main area where you enter or edit code. Replace the last if len(name) > 9: line of our code with the following block. WorldMags.net .net WorldMags. ...................32 Functions and objects .................................................................................. 40 Recursion .................................................................................................................................................................. 52 Common mistakes ..............................................WorldMags.......................................net Coding basics Now you have the tools........ it’s time to grasp the basics of coding Lists ......................... 34 Conditionals ....................................................... 46 Integers .......................................... 38 Program structure ...... 48 Using loops .......................................................................................... 44 Sorting algorithms .................. 54 WorldMags.........................................................................................................................net Coding Made Simple | 31 ........................................... 36 Variables ......................................................................................... 50 Compilers ........................ for instance. any particular concept. “baked beans”] peculiarities of your chosen language. the process a trip to the supermarket. And that’s on top of the syntax and >>> shoppinglist = [“milk”. Both methods work. but most prefer the convenience. 32 | Coding Made Simple WorldMags. When someone begins coding. It’s for this reason that some of the earliest lists are stacks. This is where lists start to become interesting. provide in this book. But lists are dynamic.net . and a list is just another example. It might not be important what that order is. but they’re still useful for temporarily holding learning values. following one to the new item. Programmers like to call loosely. because We’d like to make this challenge slightly easier by looking the method for adding and removing values can help to at basic approaches that apply to the vast majority of define the list’s function.append(“soup”) a great helper. for example before retrieving them in reverse order Python. For example. Some languages like to make either by following an example project. In Python. with values either pushed on to the end or pulled off. related snippets of information a data structure. because each value is itself One of the best approaches is to just start writing code. beginning with the concept of lists. the like a stack of cards. for example. there’s an overwhelming number of different ideas to understand. to add a new item to the end of a list because all the You don’t get far with any moderately complex task application has to do is link the last element to the new one. which are more processor intensive. “bread”. it’s faster for the CPU circumstances and languages. such as the ones we that distinction. And our first target is lists. A list is a convenient place to store loosely-related the insertion point. and they’re the only real shoppinglist list. then links both the preceding item and the snippets of information. you could create a list of those values with the following line: into solutions. you can execute a function called append to programming the same effect: environment is >>> shoppinglist. without a list. the Stacks and queues relationship might be something as simple as food – ‘milk’. This is technically a list of lists. such as a chunk of memory. or by piecing together examples from Each of these items has been added to the freshly created documentation. And list logic in code is just like in first splits the links between the two items on either side of real life. WorldMags. it would make much I explaining the basic programming concepts. or a browser’s ‘Back’ button. Processing speed means that stacks aren’t a necessity If you’re any more. With a shopping list. and one of the first way to get to grips with the problems and complications of things you often want to do is add new values. but it’s the order that differentiates a list from a random array of values. t’s difficult to know where to start when it comes to remind you what’s on your shopping list. the values you put on the list first are the 1 2 3 4 5 first out (FIFO). rather than lists with values inserted and removed from the middle. in the Eric In Python. If you were writing an application to of data it contains is in a specific order. The list could be your terminal command tab completion history. The most important characteristic for a list is that the chain ‘bread’ and ‘baked beans’. absorb and eventually turn more sense to put these values together. POP PUSH A QUEUE With a queue. whether that’s a holiday to Diego Garcia or If you insert an item into the middle of a list. a list – a string of characters.net Get to grips with Python lists Let’s start by exploring some of the fundamental ideas behind programming logic. There are many ways to use a queue. but the most in fact. and a great deal. interpreter – although they are. It’s perfectly possible. ‘bread’. But You can change the order in lots of ways. and should lines of Python code.net Coding Made Simple | 33 . and explanation in a script or assigning to popping off a value from the end. ‘bread’. contrast to a stack. print tip PUSH The for loop here gives a value to x that steps from 0 to We’re using Python len(shoppinglist). WorldMags. But at their heart. because simply typing shoppinglist will output the list’s contents. This is in a script and something you can try together. the values you put you’re unlikely to grasp the logic. If you’ve got on these pages. ‘milk’. Q WorldMags. 0 is the real first element in a list and your own code. You can output a value from any point in the array. operations. it just uses an argument for the pop command. The symbols. known as FIFO. Typing shoppinglist[1]. ‘milk’. and because lists are shorthand for so many different data types. it can be removed easily with pop: >>> shoppinglist. a great language for beginners. ‘soup’. >>> shoppinglist [‘apples’.pop(0) how the language works. and you can now start typing following will remove the first item in the list. This is especially true of Python – because it has so many convenience functions. and they help to distinguish between another variable. but Python’s 4 sort method is tough to beat: >>> shoppinglist every concept we discuss works with other languages. in our case the word soup. regardless of your them. output ‘milk’ from the interpreter: This is a brilliant way of learning >>> shoppinglist.. And if you want to output the list by treating it as an array. the queues. ‘soup’] too – it’s just a matter of finding >>> shoppinglist. too. and can turn lists into super-flexible data types. which is a method to return the length of for our examples a list. such as popped off the stack. and now we hope you’re wondering what all the fuss is about. ‘soup’] If you can follow the logic of that simple piece of code. Python is an exception. These symbols represent the cursor immediately. interchangeable. and that’s the best place to start. for entire list. The main problem is that it can get complicated quickly.. shoppinglist[x] POP .net This will add soup to our shopping list. for example. These offer a big advantage over the original primitive programming in general. you might wonder why there comprehensive Python tutorials. When we’ve added it to our shop. you might have to construct something like: A STACK >>> for x in range(0. but for other languages. unless you know what they do. rather than needing any This would require the same amount of relinking as of Python’s interactive interpreter. the processing limitations in mind. ‘milk’.sort() for the functionality. value is output to your terminal isn’t an option to pop the first value off the stack.append(“apples”) the correct syntax >>> shoppinglist 3 [‘baked beans’. just a chain of values. but you will obviously lose the immediately by typing in to the current state of your code. You can quit the turns a list into something called a ‘queue’ – the values you something you might want to build into interpreter by pressing [Ctrl]+[D] put on the list first are first out. It’s doesn’t have any special commands for accessing the first at this point you’ll see the cursor value. which is LIFO. Errors in a Modern lists single line are far easier to spot than Lists are no longer limited by processor speed to stacks and those in a 20-line script that’s being run If you’re learning to program. and most modern languages and frameworks for the first time. Each location in the list is output as we loop through it in because it’s the order they were added (FIFO). As with nearly shuffles through these values from beginning to end.pop() Using Python’s interpreter If you’re running these commands from the interpreter. Python is particularly good at this. With a stack. As we Launching the interpreter is as simple explained. handles logic chosen language. There’s really nothing more to it. the only difference between a queue and a stack is as typing python from the command where the pop value comes from. 2 then it’s safe to assume you’ve grasped the logic of lists.. as well as in our more len(list) to return the length of a list. ‘baked beans’. making 1 the second. obvious is to preserve the order of incoming data. If you execute a function that you’ll see the contents of the last value in the list as it’s symbols preceding the snippets of code returns a value. and includes plenty of built-in functions for manipulating lists without having to write all things code-wise. you typically need to construct a simple loop that instance. they’re on the list last are the first out (LIFO). and you can also get Python interpreter can teach you provide a vast number of handy functions for dealing with a really good feel for how Python. ‘bread’. [‘baked beans’. it can be difficult 1 working out what might be happening in any one chunk of code..len(shoppinglist)): Quick . as well as experimenting with syntax and the concepts you’re working with. will return the second value in the list. ‘apples’] >>> shoppinglist. which is why Python line without any further arguments. You might wonder why we have three > and data. because a function is a kind of list for code logic. This led to one of the most primitive hacks of the day. there’s a good chance it was written in BASIC – a language Functions also make program flow more logical and easier embedded within the ROMs of many of the home computers to read. But you’d have needed to be a wealthy Acorn Archimedes owner to get those facilities out of BASIC.net Understanding functions & objects After introducing the concept of lists. jump to the new code. but while you’re constructing your project. with many systems projects. it’s a basic example of a function if you can execute it from another part of your project. functions are independent blocks of code that are designed to be reused. Functions can also return a value. you need to remember where you are in the code. 34 | Coding Made Simple WorldMags. and written on a home computer. they simply store one value after another. and you can keep your favourite functions and use of the early eighties. such as the sum of a group of numbers.net . functions become the best way of grouping even using line numbers. If your first programming project was from wearily turn it off and on again. and they allow you to write a single piece of code that can be reused within a project. and it’s this idea that led to the machines. it’s time for us to tackle the fundamental building blocks behind any application. They allow the programmer to break a complex task into smaller chunks of code. type the following: the best uses. you can try these ideas without getting too BASIC wasn’t retro. The cooler kids would change about 30 years ago. BASIC programming without functions can be a little like writing assembly language code. If you want to repeat a series of lines. Either way. And when it’s one piece of BBC BASIC was the first programming language many of code that’s being used in lots of places. It’s not built at runtime. You can then easily modify this code to make it more efficient. naturally breaking complex ideas into a group of far 10 PRINT “Hello world!” easier ones. From the interpreter. for example (just type python on always put to the command line and add our code). and accept arguments. them again and again. RUN and a carriage return. This bundle both the code logic and the data the logic needs to would create an infinite loop that printed ‘Hello World’ for ever work into completely encapsulated blocks. for instance. You they can work on functions and files without breaking the had to find a computer shop displaying a selection of operation of the application. and there’s a good chance that the functionality and splitting your project into different source following might have been your first program: files. But what must have come soon after lists in the mists of language creation is the idea of a function. then the text to say something rude and add colour to the output. But let’s start at – or for the 10 minutes it took for the store staff to notice and the beginning. Lists W have been around since people started to write one line of code after another because. fixing it once is far us came into contact with. If you then work with a team of programmers. Functions are fundamental for all kinds of reasons. BASIC provided some of this functionality with procedures. With Python. WorldMags. but functions give that chunk of code a label. and jump back after execution. These are a special kind of function that followed by 20 GOTO 10. That could be a list of numbers to be added. which can then be called from any other point in your project. You’d then sneak in and quickly type the above line creation of objects. and much like their mathematical counterparts. to add functionality or to fix an error. When you break out of single-file BASIC code was mostly sequential. easier than trawling through your entire project and fixing your same broken logic many times. in essence. for example. e’ve already covered a concept called a list. and we pass the two values – each to indent the code and make sure Python understands quickly get complicated. You should see the output you’d expect from a example creates a class that contains projects for the better..27 same name as the original list but that might look confusing. 0. If you alter the function >>> instance = Shopping(“Bread”.99.. The best way is to first write your application. where it’s common sense to give each menu item its own function. 18]) That’s functional 53 programming in The biggest challenge comes from splitting larger a nutshell. The best example is a GUI. return The art of objects . partly because one for the item’s name and the other this. and why types are often To show how easy it is to create something functional. Other languages aren’t so picky. press language-specific features and how this class could be quickly [Return] to create a blank line. 12. You can process this string within the function by 0. return (sum (plist)) convoluted requirements – apart from its weird tab . 13. and how the world of classes problems differently. formatting.item ‘Bread’ expect to find a string passed to the function whenever it’s >>> instance. def __init__(self.. we’ll declared in header files because these are read before the now build on the idea of lists from the previous tutorial. main source code file. You should be able to see statement. self. but for a beginner. This can be solved by opening the function . function with a name like helloworld(). previous shopping list: >>> class Shopping: Passing arguments . When you’re using Python is very forgiving when it comes to passing types to The only slight problem with this solution is that you’ll get other packages. All we’ve done in our code is say there’s going to >>> pricelist = [1. You can’t . Instead of a shopping list... unless you can be certain where how they work. whereas the term object but it begins to make less sense. this task becomes second nature.. But it does mean you can send what input they’re expecting and what a list of values in exactly the same way you define a list: output they return. and go to the trouble of completely rewriting the code after proving the idea An IDE.. we’ll create a list of prices and then Working out what your language requires and where is write a function for adding them together and returning the more difficult than working out how to use functions.. Most other languages will want to know numbers to the function.99] be some data passed as an argument to this function. item. 2.. just it’s able to create the function. and you’ll need to press [Tab] at the beginning of side processes. You’ve now created a function.. price): There’s a problem with our new function: it’s static. After creating a new function called helloworld() that there’s less ambiguity on how class is the structure of Shopping while with the def keyword. For a programmer. but you should A class is a bit like the specification functions from within the interpreter. which is why we didn’t need to define exactly what an error if you try to pass anything other than a list of are exposed.50. Any lines of code you now add will be applied to the separation from the main flow and called __init__ is run when the object is function. for its price. This is something that should be don’t need to know exactly what kind of types an argument may contain before checked by the function. and Quick >>> addprices(pricelist) we’d like Python to call this plist. such as Eric. and you’ll find yourself splitting up ideas as the best way to tackle a specific issue within your project. and that’s why you often get those numbers come from. An object bundles functions and the refers to when specification is used As ever with Python. Python will >>> instance.. for instance. problems into a group of smaller ones. >>> def helloworld(): WorldMags. Dealing with objects can created. >>> addprices([10.. and better the object is instance.. and you’ve just both the item and the price from our jumped forward 30 years. only the functions functions. so within your code. Q and objects easier.. But don’t worry about that yet. it’s only when you’re attempting to write your first solution that better ones will occur to you. You plist contained. which can be launched from either the icons in the toolbar or by selecting the menu item. pass and process arguments. 6. In our example. which signals the end of the function.49. But >>> def addprices( plist ): Python is perfect for beginners because it doesn’t have any . can make working with functions works. 4. it’s an intimidating prospect. you need to be very careful about type of data they accept together. obviously be doing anything other than simply printing out for an object.item = item change anything...30. self.85 You can still create classes and changing print (“Hello World”) to print str...85) definition to def helloworld( str ). WorldMags.net Coding Made Simple | 35 . print (“Hello World”) . and you can do that by enabling it to . This simple and objects can transform your coding interpreter. definitions before the program logic. what’s passed to the function.price = price up to external influence. implementations.. It could even have had the tip 16. And total value. Here’s the code: that’s why they can sometimes appear intimidating. It can now be executed by typing helloworld(“something to output”) and you’ll see the contents of the quotes output to the screen. The function with .. the interpreter precedes each new line a function should be used..price called. 0. After the return there are so many different concepts. Often. regardless of functions or programming finesse. Many developers consider their first working copy to be a draft of the final code. and partly because it expanded to include other functions (or and you can execute it by typing helloworld() into the requires the programmer to think about methods). the formatting.net . WorldMags. without any user interaction. we print a different message.python. a conditional statement is something like this. halt the transaction. Or if the Consequent Alternative variable PRICE is bigger than 500. too: there. if X contains 10 we print the message as else: before. thereby turning this into a long branch print “Program finished” in the code. you’ll be asking questions in your code: if the user has pressed the [Y] key. and we’ll come if x != 10 If X is NOT equal to 10 on to that in a moment. go to the pub. (We don’t use newfangled electricity around here. But most of the time. If you’re writing a program that IF condition. Here..” Ifs. but you can put more lines of code in inside the conditional statement.net . as in everyday life: if the At its core. org/dev/peps/ if truefunc(): pep-3103/ 36 | Coding Made Simple WorldMags. Get your head around coding’s ifs and buts. buts and maybes play a vital role in motor racing. Python style: if x + 7 == 10: if x == 10: print “Well. A condition is just a question.. we create a new variable (storage place for There are alternatives to the double-equals we’ve used: a number) called X.) Or if all the pages have gone to the printers. turn off the gas. providing they have the indents. We then use if x > 10 If X is greater than 10 an if statement – a conditional – to make a decision. you can call a function inside an if statement and perform an action depending on the number it sends back. the great Formula 1 commentator. Why? Read the explanation print “Execution begins here. simply processes and churns out a bunch of numbers. kettle has boiled. but then call the somefunction routine elsewhere in print “X is NOT ten” the code. and if not (the if x >= 10 If X is greater than or equal to 10 else statement). we print an affirmative message. If not. X must be 3” Comparing function results While many if statements contain mathematical tests such as above. and store the number 5 in it. Here’s an example in Python code: print “X is ten” x=5 somefunction() else: if x == 10: anotherfunction() print “X is ten” In this case.. Note the if x <= 10 If X is less than or equal to 10 double-equals in the if line: it’s very important. Look at the following Python code: def truefunc(): return 1 Python doesn’t def falsefunc(): have switch/ return 0 case.. If X if x < 10 If X is less than 10 contains 10. as they do in computer programming. then you might be able to get THEN ELSE away without any kind of conditional statements. then continue. M used to say “IF is F1 spelled backwards. And action action so forth.” at www. These comparison operators are standard across most Here. That could be a big function that calls other functions and so forth. urray Walker. stop. we’re just executing single print commands for the programming languages. You can often perform arithmetic if and else sections.net Adapt and evolve using conditionals Any non-trivial program needs to make decisions based on circumstances. the principles are applicable to switch(x) { nigh-on every language. Another way that some programmers in C-like languages int main() shorten if statements is by using ternary statements. For instance. but print line. The lines beginning with if So. number 1. Q Big ifs and small ifs In C. replace 1 and 0 with True and False for code clarity. In Python and many other languages. because if here { assignment used as truth value. if (x == 1) else puts(“One”). If you puts(“X is 5”). run gcc foo. if (x > y) result = 1. If you recompile this code with gcc -Wall foo. you’ll see Yay but not Nay. it skips past it. and act on the then ./a. that’s conditionals covered. and case 3: puts(“Three”). result. you might be but if you’ve just written a few hundred surprised to see the X is five message lines of code and your program isn’t def falsefunc(): appear in your terminal window. Although we’ve focused on here can be replaced with: Python and C in this guide. type it into a file called We’re not saying “if X equals 5”. return False and the program will operate in the same way. number storage places (registers) with another number. This is neater and easier to read. with executing the indented code. else if (x == 3) Here. return True If you run this program. at the end of the day – the CPU can compare one of its case 2: puts(“Two”). It’s a small consideration. if (x == 5) { But only one instruction will be executed. They’re really simple functions: the first sends back the bit of C code – try to guess what it does. “put 5 in X.c. we call a function here. Program execution begins at the and if you like.h> Ouch. print “Yay” WorldMags. Instead of foo. the second zero.net if falsefunc(): Assignment vs comparison print “Nay” value of X to be 1! Well actually. is an indication that you might be doing function it calls. so you if (x = 5) The solution is to change the if line to could replace the functions at the start with: puts(“X is five!”).h> following the first matching case. shome mishtake? We clearly set the It’s caught us out many times. Otherwise. especially C. indentation – you have to explicitly show what you good enough for C – we need to use When you execute it. Now the program def truefunc(): } runs properly. if X is bigger than Y. Note that this doesn’t make the resulting code magically } smaller – as powerful optimising compilers do all sorts of C. If the if statement sees the number 1. put them in curly braces like if (a == 1) the following: puts(“Hello”). Note that the break Clearing up code instructions are essential here – they tell the compiler to end In more complicated programs. not a comparison. In some languages. this could be the root cause. do something like this: puts(“Have a nice day”). a long stream of ifs and elses the switch operation after the instruction(s) following case can get ugly. want with curly brackets. And it all boils down to machine code case 1: puts(“One”). C doesn’t care about Here we see how indentation isn’t puts(“Have a nice day”). and then we have our first if statement. if (x == 5) instead. where the if (x == 5) indentation automatically shows which code puts(“X is 5”). int x = 1. } Contrast this with Python. and some other languages. include a switch statement tricks – but it can make your code more compact. To attach both statement followed by a single instruction: instructions to the if. Shurley behaving. break. break.c (to show all warnings). you but it will print the second.out to execute it. and if that succeeds. That’s because only the don’t need to use curly brackets when using an if first is tied to the if statement. you The first four lines of code define functions (subroutines) have to be very careful with but in the if line we then performed an that aren’t executed immediately. which simplifies all these checks. For instance. result becomes 1. result = x > y ? 1 : 2. } Remember to thank your CPU for all the hard work it does.. result = 2. { Consider the following code: int x = 2.c to compile it and rather. it goes ahead #include <stdio. if not. else if (x == 2) This can be shortened to: puts(“Two”). you can something wrong. execute the code in the curly brackets”. This only does its work if it receives the number 1 back from the int x = 1. break.. otherwise it’s puts(“Three”). belongs to which statement. So int main() you’ll see that GCC mentions when you run this. it won’t print the first message. what the single equals sign does. That’s use. consider this C program: have been executed. WorldMags. look at this assignment. curly braces to bundle code. 2. it will execute everything #include <stdio. but are reserved for later comparisons. doing a comparison. and other languages that share its syntax. we did. jump to a different place in the code depending on the result.net Coding Made Simple | 37 . anything with variables and the contents of memory. Your program calls lots of different subroutines. the version of x we were using in myfunc() was a local variable – that is. you can without accidentally trampling over one another’s data. WorldMags. so let’s look at another implementation here. to Well. In most high-level languages. Why? Because variables are variable. and it stays that way back in the main code. For instance. or absolutely everywhere in all of It didn’t do anything with the x variable that was declared explanations the program’s files. myfunc() How do you know that those routines aren’t messing about print x with the RAM where X is stored? If you’re totally new to Python: the def bit and the The results could be disastrous. and in Python you can do this by inserting the following line into the start of the myfunc() routine: global x This makes all the difference. So. but the function had its own copy of the variable. You’d be totally terrified of choosing variable names that implementations. As control jumps back to the main chunk of our to the rest of the program. might be in use elsewhere. but then the myfunc() routine grabs that x as a global variable and sets it to 10. Still. How did that Most well. this 38 | Coding Made Simple WorldMags. and accidentally changing someone else’s data. and stores the state of the arm in a variable x=1 called X. we can choose happen? Didn’t we just set x to 10 in the function? documented whether it should be visible to the current chunk of code. How variable scope is handled varies from language to language.net Variable scope of various variables Caution! That variable you’re accessing might not be what you think it is. it’s the same one as we used in the main body of the code. so once you’ve got the program design. and you were writing a article. we access x as a global variable – that is. we see that x is set to 1 at the start. there are legitimate reasons why you might want to make a variable accessible to other routines. can control the scope of a variable – that is. so that multiple programmers can work essential to keeping code maintainable – imagine if all basics from this together on a project. implementing their own routines variables were accessible everywhere. We print it out to This is where the concept of variable scope comes into confirm that. we create a originally envisaged. the idea that one part of the program could do print x anything with memory became less appealing. starts punching people instead of stroking puppies as Program execution begins with the x = 1 line. outside of it. explore specific good for modularisation and keeping data safe and secure. and play.000-line software project. This is scope. Try this: This was fine for simple. and these instructions could do your programming journey. Change of routine So most programming languages provide this level of protection. By adding the global command. It’s routine to be dropped inside a 50. languages have the current source code file. variable called x and assign it the number 1. So if we run this Python code now. it affects only the code located inside the function. and doesn’t of variable This level of control is absolutely fundamental to good want to interfere with data it doesn’t know about. Have we said ‘variable’ enough now? O nce upon a time. you might have a program that controls a robotic arm. The function lives happily on its own. we code. we print x again… and it’s back to 1. especially when the arm following two lines of code are a function which we call later. In programming. We then call a function which sets x to 10.net . low-level programs but as time went def myfunc(): on and people starting making bigger and more complicated x = 10 programs. Previously. print x some of which may have been programmed by other people. Let’s start with a bit of Python code. scope defines how a variable is visible prints it. yes. programs were just big lists of and therefore it’s a good thing to get right in the early days of instructions. x). adds 1 to it and prints it out. that variable. For x is 3 } instance. in foo. So. #include <stdio. so there’s { no guarantee that the RAM is zeroed- int x. that’s a matter of own time. line at the top. they are only created in RAM x = x + 1. Note that while putting the x declaration outside of personal choice for your particular program. and you’ll see the intended result. Pointers are a tricky business! Q Remember to initialise! By default. references in C++).net time in C. So it’s somewhat clearer that myfunc() has its own version of void myfunc(). static variables is However. static int x = 0. then compile and run it. why don’t compilers just set variables. the number You can tell GCC to warn about the will probably be different each time use of uninitialised variables with the If you try to use automatic variables that haven’t been you do. does with automatic variables. given any value. but it’s extra work for the So if you have a program like this: CPU and adds a performance hit. and then and GCC tries to be pretty efficient. we call myfunc() three times. making room for other bits myfunc(). WorldMags. right? used previously by other data. so that’s something to look up in your global variables.h> int x = 0. a way to stop that. Once the } int main() routine containing the local variable has Here. Setting that chunk of RAM to zero } requires an extra CPU instruction. Inside the } a great way to get some of the benefits myfunc() routine. longer be useful. that’s not the only job you need to do. x). that variable will no which creates a variable x containing int x = 10. it rule is: use global variables only when necessary. but the general functions makes it global to the current source code file. WorldMags.c and you want to use that in bar. because we’re explicitly creating variables with int. Try to keep doesn’t make it global absolutely everywhere in all of the data isolated inside functions. because they might be the variable to zero? That would created somewhere in RAM that was make everything a lot safer.? Well. take it away so that the line just reads x = 20. But what happens if you } There is.. the output void myfunc() This is still a local variable that can be becomes this: { manipulated only by code inside the x is 1 int x = 20. Whereas Python is pretty flexible about using variables that you haven’t defined previously. printf(“x is %d\n”. void myfunc(). Most local variables are automatic – that is. Run the program. #include <stdio. yes. routines can’t access it. as it and now the variable has become global – that is. and bobs. change the declaration in myfunc() to and that’s by declaring a static variable. Well. compile and run it again. So. the compiler no doubt already guessed that running will typically reclaim memory used by this produces 1 with each call of myfunc(). but those features are specific to All of this leads to one final question: when should you use individual languages. using accessible by all functions in the file. but it retains its state x is 2 printf(“x is %d\n”. current function.h> compiler that it should preserve the state of the variable between calls. The compiler doesn’t from inside main() to after the void myfunc(). ditch it at the end of the function. Move int x = 10. most C compilers don’t don’t blindly use variables that set newly-created automatic haven’t been initialised with some variables to zero. every time the function is called. So if you have int x = There are usually ways to access the local variables from 10. it’s myfunc(). because x is being created printf(“x is %d\n”. But how do you go about making the variable but in future calls it doesn’t initialise the global in this particular instance? The trick is to put the int main() variable as new again. you’d need the one function in another (for example. that x is global and can be modified everywhere. on the very first call it sets up x as zero. The moral of the story is: -Wall flag. Consider this: Automatic variables #include <stdio. in the latter file.c. This is especially kind of value! true in the case of automatic Now. we still have a line that says int x = 20. of global variables (retaining its state The int here is still creating its own version of the variable. You’ve printf(“x is %d\n”. { finished. each time. because outside zero. when you have no other option. myfunc(). when program execution reaches the printf(“x is %d\n”. and when local? Ultimately. If you’ve got a big project with multiple C files. the variable. so void myfunc() throughout execution) without exposing { it to the rest of the program.. prepare for some horrors.net Coding Made Simple | 39 . C is a little more strict. point of their initialisation. look at the following C code: The static keyword here tells the Here. x). out. x). and only use a global variable source code.h> The compiler allocates space for variables in RAM that may have been int main() used for other data before. myfunc(). however. { state from before. but retrieves its variable declaration outside of the functions. x). pointers in C and line extern int x. you’ll have to use the extern keyword. Knowing that we need some www. for loops. Output data: monthly payments and total interest Input: mortgage value. The next thing we need to do is figure out how to combine all those arguments – all that input data – to get the output we’re after – monthlyPayments. there are two types of data (and much more) is vital if you want to learn to program. (Picture from: based on faulty assumptions). some set processes – recipes of “I want to make Space Invaders. but at 4% per annum. monthlyPayments = 0 Read through the above text carefully and pick out all the return monthlyPayments types of data that are described. so long as you’re confident that it’s reliable (your program won’t work properly if it’s Check often for bugs in your program. money. we’re going to look at the art of designing programs. It’s not really anything to do with programming. but that’s not really the important thing involved. smaller ones. we’re going to do something a little different. interest. by looking at the data might be unfamiliar. term): programming problem is to closely examine the specification. Functions: one task at a time To demonstrate. but that sounds like two problems instead of one – sneaky! you don’t have the faintest clue where to get started when You’ll find that many programming problems look like this faced with a new programming challenge.” but on closer inspection a kind – that you can follow that will help to direct your you’ll see that the problem’s actually made up of many thinking and make solving a problem much easier. separate the data into input and output. There’s not much to this function yet. and we’ve Once you’ve identified the smaller problems. Let’s say that Mike will be to focus in on one. Knowing about if clauses. – you’ll start with a grand description of what you want to do: There are. you can get to a point where you know all of the elements.com/photos/fastjack/282707058) 40 | Coding Made Simple WorldMags. We’re going to start with the needs a mortgage of £150. We’ve given the function a name. but it’s some extra knowledge that we need to solve the problem. Let’s take a look and see what we have so far. but what was the point? Well. WorldMags. we’ve created a variable to hold this information. He wants us to help him. and we’ve specified all the input data as arguments to the function.net Building proper programs Learn to break problems down into manageable chunks. annual interest rate. But there. but it’s often helpful to start with a sketch and fill it out later. lists and functions take a look at the output data. duration Great. we need an example problem. The first step when tackling a def monthlyPayments(mortgage. Some of the Python features we use to solve problems Identifying these smaller issues. This is what might be called ‘specific knowledge’. Since we know that we’re trying to work out the monthly payments. n this article. however. As you’re doing this. Innsbruck. is often the first step to finding a solution. Since that sounds exactly the same as what Mike wants to know what his monthly repayments will be in we’re doing now. paying it back over 30 years.000 to buy a nice house in monthly payments problem. and instructed the function to return it when it’s finished. it’s more of a sketch than something that might be useful.net . let’s try to create a function for our monthly each situation. and how much interest he’ll have paid in the payments problem. This is in this tutorial (you can always look those up on the internet called top-down development. with Mike paying it back over 25 years at a bookazine. You can use any source you like. easier ones. A bank has agreed to loan him the money at a rate If you look back at the tutorial on page 10 of this of 6% per annum. you’ll see us explaining that functions are great fixed monthly rate.flickr. If we have to come up with two pieces of output data. your next task settled on a simple mortgage calculator. end. yourself) – the important thing is the thought process that we must go through. I Instead of looking at a specific feature that shows up in many programming languages. that was pretty easy. This is often a vital step in successfully completing a programming problem: identifying and finding the specific knowledge necessary to complete the problem. as we show you how to design a well-sculpted program. Another bank agrees to lend him the because they allow you to break a complex task into smaller. that’s great. larger problem. Mike wants to live here..net information about how to calculate mortgage repayments. By looking that we came up with: closely at this information. we managed to find monthlyPayments (200000. N): def monthlyPayments(P. but testing regularly will make spotting and fixing bugs much easier. but consistency can calls both the others and prints their output in a pretty help avoid mistakes. we looked up print statements specific knowledge to check that which allowed us to certain variables are what you’d “A good way of finding out solve the problem.net Coding Made Simple | 41 . r..0 . N. finished. with expect them to where the problem lies is by working solutions be at that point to all of the in the code. P) us anything about the amount of interest paid. c is the monthly payment. At this point. One important thing to be wary of is that all of the inputs that we have are in the same units as the formula expects. r. and work them out using a calculator. P the amount borrowed and N the number of monthly payments. a quick Google search turned up this handy and entirely relevant formula on Wikipedia: c = rP / (1 . we’re ready to move on to might have to further divide the subproblems. at the end of all this. making it easier and more Now that we’ve established a test case. it’s worth testing what we have put N) together so far. 30) = 1467. WorldMags. Finally. and instead look at solvable and then work your way back.math. but this is exactly what you would do would allow us to check that r was what we expected. what did our whole development check it with. adding more print statements” subproblems. r the monthly interest as a decimal. print ‘Total Interest:’. Also. Be sure to take note of the expected result. N): And that’s our function for calculating monthly payments print ‘Monthly Payments:’. If it doesn’t. Q WorldMags. P): (N * 12 * -1)) return monthlyPayments def mortgageComp(P. come up with a few values of P. but you would the second: calculating interest paid. totalInterest(monthlyPayment It’s obviously not the complete program. N = N * 12 monthlyPayments = (r * P) / (1 . we’ve added a couple of lines to (From Wikipedia’s Innsbruck page. This is what our final program looks like: import math import math def monthlyPayments(P. For some. to tackle almost any programming problem. def totalInterest(c. following the method laid out here. a good This was called incremental development. We called this top-down development.(1 + r)^N) Here. Designing programs Before you can test code. and he needs us to figure out whether he can afford it! Because they’re not here. This isn’t necessary.52 a way to split the problem in two. N). We’ll leave you to do just keep going until you reached a level that was easily that. print r The steps are simple. and working like this is known as incremental development. format. note that we have changed the argument names to The simplest way to do this is to create a third function that match the formula. you need some test cases to So. print the result.0 / 12.) convert them. 8. Notice how all the variables needed to calculate c in this formula are already provided to our function as arguments? Putting it all together Now we must convert this knowledge into our programming language of choice.pow (1 + r). Here’s one and identifying the input and output data involved.0 come up with a solution to the original. as it doesn’t tell s(P. beginning with sketches and testing each as we progressed. and developed solutions to each of these as separate functions. modify the code manageable. solving each level as how you can tie these two functions together. where we had to. r. monthlyPayments(P. r process look like? and N. you With the first problem solved. and when you reached it. In this case. we For example: combined them to r = r / 100. 25) This is a vital step in the development process. filling out our function sketch. We began by critically reading the problem specification.0 / 12. r. N. mortgageComp(150000. way of finding out where the problem lies is by adding more Also remember that. 6. N): r = r / 100. r. If everything matches. We then so that the function gets called with these arguments. co.uk/t3 WorldMags.myfavouritemagazines. M RE E O G NT3.C C T O A N M AT O R T T WorldMags. CYCLING AND MORE… LIFE’S BETTER WITH T3 E GET FIT FAST IN 2016 WITH THE VERY BEST TECH FOR RUNNING.net . net Not your average technology website EXPLORE NEW WORLDS OF TECHNOLOGY GADGETS. culture and geek culture explored Join the UK’s leading online tech community twitter.com/GizmodoUK facebook.net . WorldMags. SCIENCE.co.gizmodo. DESIGN AND MORE Fascinating reports from the bleeding edge of tech Innovations.com/GizmodoUK WorldMags. or why they do what they do. syntax isn’t from any one specific language. i >= 1. It’s the programming In the above snippet. and that it should be increased X factorial by one with every iteration of the loop. to the value 1. To make use of it. We’ve used a more bending your brain around what might be a more complex C-like syntax for the for loop. we can use a function that calls itself in return. this is easier to read than the range keyword we’d need to This is because recursion is simply a way of solving a more use if we wrote the same code in Python. it can save you from eccentricities of one implementation. we’re going to ask the function to control itself knowing that it has been called from within itself. factorial of a positive integer (we have to say this because the which is why this is an iterative approach. But if you do this. such as GNU (GNU’s for i =c. And that way uses recursion. equals 24.net . Don’t forget that as well as passing values to and returns the correct answer. recursion is a function to give a number’s factorial. examples of value of i steps down from c. You can then just copy and paste Pseudo code like this is used to explain a concept and to them into your code without necessarily understanding how create a template to show the logic of a program. If you’re working on complex problem by repeating a simple function. but be careful – you may well land on your own head. and easiest. Here’s the pseudo code for an updated factorial function that uses recursion instead: function factorial(c) 4 3 2 1 1 2 6 24 if c > 1 else return c * factorial(c-1) return 1 All that’s happening here is that we’ve replaced the old factorial function with one that calls itself and expects a value To calculate the factorial of a number. or connecting to the same virtual loop) to step through a range of values. That’s recursion! a function. many uses of recursion are well print total documented and explored. WorldMags. the input value. because recursion is cool. for example. and as a result. for instance. without being weighed down by the peculiarities or write a few lines of code.net Recursion: round and round we go Jump down the ultimate rabbit hole of programming ideas. but the they work. Instead of controlling the If we wanted to approach this problem in the same way function from a for loop. i-- not Unix). because we think problem without recursion. It needs to be you’re missing out. the In programming. but it’s a concept much clearer in code. ecursion is one of those concepts that sounds far we’ve been doing with previous tutorials – a strategy known R more intimidating than it really is. of itself from within its own code. Rather than being a pseudo code sketch of any potential solution is a great way run manually from another function. or start thinking in four dimensions. or as iterative programming – we’d maybe write a function that multiplied two values within a for loop which was counting down through the factorial input value. it calls another instance of communicating your ideas or proving your concept works. the function itself can return a value. We’ve used the desktop from within a virtual desktop. In other words. you don’t need to grasp complicated mathematical ideas. Honestly. writing that this function repeats from within itself. The Each iteration of the multiplication is controlled by the code. The factorial of 4. we create a for loop that uses a variable equivalent of pointing two mirrors together to create a called i (that’s a common name for variables within a for seemingly infinite corridor. The trick is a problem and don’t know how to approach it. That’s confusing to read. usually using 44 | Coding Made Simple WorldMags. C-syntax to say this value needs to hold a number more than (>) or equal (=) to the value 1. which exact same result. function would change otherwise) is the product achieved by You might already see from the previous piece of code multiplying the whole numbers it contains against one that there’s a slightly more efficient way of achieving the another. It’s one of the detailed and clear enough for the reader to understand the best ways of letting the CPU do all the hard work while you logic. is 4x3x2x1. this invade one level after another of someone’s dreams to might look something like the following: implant an idea into their subconscious. In pseudo code. or even understand function factorial(c) the meaning of recursive acronyms. one of the classic. total = total *i For the most part. This is 120 moves forward. you’ll have to could be an infinitely complex image. WorldMags. and multiplies this by the value that’s returned. which is what will launch other iterations. on for ever is because we first check whether the length of Before we start. so that the code that called the function can use the value. this means that all the installation.fd(length) mathematical solutions and filesystem searches. you will need to make sure you each line is going to be greater than 10. To turn this into a fractal. and this can be easily achieved by adding the most famous were documented by the French fractal(length*0. 2 and then 1. which itself returns (2x1) to the previous call. and on. returns (4x3x2x1).. you’ll see the Turtle the quickest ways to understand the concept.net Coding Made Simple | 45 . for example. following into the Python interpreter: because the cursor moves slowly along the path as our fractal Quick is being drawn..fd(length) Python interpreter prints this out without us needing to do trtl.fd(length) line. return 1 create a function to draw a star. we’re going to quitting. You can see that while it’s harder to understand the logic of how the final value is calculated..fd(length) something can be approached using recursion. but the reason why this doesn’t go we’re going to do using Python. which returns (3x2x1) which. but instead uses the relative position of the sleep (seconds) >>> factorial(5) a cursor and an angle to draw the path with the cursor as it command within your code. or doing . As long as the incoming value is greater than 1. by typing fractal(200). very useful if you >>> import turtle as trtl want to see the def fractal(length=100): final Turtle graphic The last two lines in that example are simply executing the if length < 10: rendering before the factorial() function with the value we want to calculate.net the return keyword. Fractal algorithms use recursion to add infinite same function from within the function itself at the end of levels of detail to what’s a much simpler algorithm. another star at the correct point. the return values start to trickle back because factorial() is potentially infinite. The Turtle module itself needs you to install until the main star itself has finished and the fractal is tk-8. in turn. type the can also see exactly what our script is doing as it’s doing it. We use this to draw and display lines with as little other part-completed stars can draw their respective limbs code as possible.fd(length) Congratulations – you’ve solved the problem using recursion! trtl.5 for its drawing routines. we want to execute the are fractals. then expand this to draw anything else. there’s one cursor first move forward before turning left 144 degrees and particularly effective set of functions that can be used to drawing another line. When return window closes. if you have an idea that trtl.. should look like.left(144) Google search will reveal whether it can and what the code. The Fractal call the fractal function again. If you want your . too. the function finishes and returns the final calculation. and these the star. This is true of the majority of recursive solutions. you end up with what distribution doesn’t add this automatically. factorial() will be executed from within itself with the values 3. If you call factorial(4). then a simple trtl. making this solution more efficient and less prone to errors. which is why you see the results under this line.left(144) repetition. Some of each limb. Drawing with Turtle graphics sleep to the top of >>> factorial(4) is perfect for fractals because it doesn’t draw lines with your script and use 24 co-ordinates.3) after every trtl. other trtl. As with the factorial function. and so on. else: limbs.fd(length) all sorts of places that require an indeterminate amount of trtl. If you run the above piece of code. This will mathematician Benoît B Mandelbrot in his book.. But to start with. and a further one on each of those to pause before . trtl. no longer being called recursively. but it should be part of any default Python drawn.. But its complexity is 1. or by adding that But if you want to visualise recursion in action. only this time with a length Geometry of Nature. return c * factorial(c-1) end of each of its limbs. tip >>> def factorial(c): The fractal we’re going to create is called a star fractal. With just a few lines of code. with another star drawn on to the Python application .. Q WorldMags. the trtl. though. if c > 1: This is a five-pointed star.. or return pseudo code. Using the Turtle graphics module means we ending beauty of recursion.left(144) can’t think of a solution yourself. which is one of command to the last line in a script. And that’s the never install it yourself.. add from time import . such as many sorting algorithms. The first is Python’s Turtle return from the function. It does this four more times to complete illustrate both its advantages and its complexities. Even if you trtl. either from the Generating fractals interpreter. If you want to see this as Python code so you can try it out. If it isn’t. factorial calls itself with a new value that’s one less than the one it was called with. which means if your complete. This star. there’s a lot less code than with the iterative approach. When it hits We generate this fractal with just 16 lines of code. but there are many easier algorithms value around a third smaller than the original.left(144) anything else. 1 is returned and multiplied by 2.. and stars will stop being indefinitely graphics module.left(144) You should now be able to see how recursion can be used in trtl. then we have two dependencies installed. that can be created with just a few lines of code. like each card to the correct location in the list.net Super sorting algorithms Let’s take our coding further and introduce you to the unruly world of algorithms. away from the computer and the value of the two cards. that you have two statement. and if it is.2] amount of time to return the sorted list. but have you ever stopped to wonder card[0] = card[1] how on earth it works? It’s a fascinating question. you’ll also get a gentle introduction to algorithms and with the values 8 and 2. It works amazingly on the left was worth more than the card on the right. you’d leave them as they were. 8 5 2 9 Bubble sort 5 8 2 9 works by comparing adjacent elements in the list. What do you do? Easy. 46 | Coding Made Simple WorldMags. and you’ve got a huge list that you need to put in order. for example. if the card on the right was worth more. copy So. so what happened? won’t get anywhere very quickly. As it does so. You’re happily writing a little Well. and if the card P program. if card[0] > card[1]: This is really handy. it’s pretty simple: you’d look at them.8]. Because there’s no operator in Python that enables us to switch the position of two elements.net . That’s obviously not what we about how to sort a Python list with a million items in it. the way. ython is a great language. and it doesn’t even care how big the list is – it could What would that look like in Python? be millions of elements long and still take virtually the same cards = [8. where do we start? Sorting a list with a computer.2]. WorldMags. How would you put these two cards value. We then check to see whether the how to think about their performance. There’s a list of cards. You should find that difficult when you first begin. you want. and in the card[1] = card[0] next two articles we’re going to introduce you to some of the print cards techniques that are used to solve this kind of problem. Along That seems pretty straightforward. efficiency and sorted data. When we tried to do the second assignment. many programming problems. we ended up with both cards having the same hearts cards from a deck. we did what seems most Sorting two cards natural to us – we used the assignment operator to copy the But what if you step back. and you’re away. If you start off trying to think you don’t get [2. we just in numerical order? copied two identical cards. you’d switch them around. seems incredibly abstract and Run that code and see what happens. first card is more valuable than the second. just call the sort() method on the list. but [2. The problem is that after the first copy list of a million items? Imagine. the largest element ‘bubbles’ its way to the end of the list. quickly. 000 j=i+1 operations. the n2 term is always cards[j] = cur going to be far larger than the n term. while swapped: #sort until swapped is False That is to say the increase in the amount of work becomes swapped = False #assume nothing is swapped more and more rapid for every element added to the list. five loops: 20 operations. it will end operations this time. operations = n x (n . loops x num. WorldMags. and before we do any copying. these two operations. and bubble sort just two cards. and we It’s pretty clever. and it’s definitely not how Python does it. where it belongs. cards[i] = cards[j] In the general case given above. we’d There’s a definite pattern here. The element with the greatest value will always end up What about if we add a fourth? It will take three increasingly longer for every on the right-hand side of the comparison. performance The idea is that we loop over the entire list. 2. However. That on a fast computer. This code shows how a bubble sort might be implemented in Python: Big O cards = [8. but it’s pretty close. Q WorldMags. Eventually. in computer science it’s only ever the largest term that’s considered. and To understand why this is. – that means (and swapping. Speed matters The terminology used for this is ‘big O’ notation. In total. albeit harder to implement. In the end. so sorting a list two elements long isn’t particularly Bubble sort impressive. Because of this. comparisons loop. on each num. and it will simply get worse for every card from if cards[i] > cards[j]: there on. This for i in range(len(cards) . bubble sort had to do two comparisons – once makes the most sense here. 1] What this means is that the amount of work bubble sort does swapped = True increases in polynomial time for every item added to the list. it won’t move any further. 7. reverse order. said.1): #loop entire list is why it’s so slow for large lists – a 10-element list may take cur = cards[i] only 90 operations. Bubble sort OK. if we have n elements. Because we stored a copy of the first card’s value when we overwrote it with the first assignment statement. Five cards? That’s four comparisons and up at the very end of the list.000-element list will take 999. you should get the correct answer. we could use the copy to set the second card to the correct value. This means that. and three loops. to the number of elements in the list. work done by bubble sort is: We’ll know the list is sorted when we run a loop in which num. and four loops. and the number of until it reaches the largest element from the previous comparisons is always equal to one less than the number of iteration. Take a look at this code: cards = [8. bubble sort has to do the most work possible. it takes in turn. Bubble sort is any size list and it will get the job done. if we were to loop over the list only once. and hence will always swapped = True #reset swapped to True if anything have a much larger influence on how well the algorithm is swapped performs.net The way to get around this is to store a copy of the first card’s value outside of the list. operations = num. so will always be comparisons on each loop. if necessary) each set of adjacent elements In total – that’s six operations. compared in the next pair of elements. comparing it has do two comparisons on each loop. are much closer to how Python does it. 3. and then again to check If you fancy looking at sorting algorithms that are much that there’s nothing else to sort. There may be much work our bubble sort algorithm has to do. The work done by bubble get only the largest element in the correct position. if you try to actually considered to be one of the worst-performing sorting use it on a large list. you’ll find that it’s painfully slow – even algorithms. to get the cards in the correct place. assuming that they’re in with O(n2) bubble sort. it’s not quite how we would do things in real life.1) = n(n . Notice that. At this point. let’s think a little about how works all right for small lists on fast computers. 4.n nothing gets swapped.2] card0 = cards[0] if card[0] > card[1]: card[0] = card[2] card[1] = card0 print cards If you run that. it had to perform just faster.1) = n2 . because it’s loops. we’ll encounter another largest element that always And we can see that the number of loops is always equal ends up on the right-hand side of each comparison – that is. The way sort seems to conform to the formula: to get around this is to keep looping over the list. It’s easy to implement. When we had times when you just want to get the job done. That’s 12 element added.net Coding Made Simple | 47 . right? You can now use this program to sort say that bubble sort is a O(n2) algorithm. but a 1. But we can extend the same technique to sort a is an algorithm list that has an infinite number of elements – this is known as When we add a third card. the amount of now in the correct position. don’t discard it entirely. when discussing the performance print cards of an algorithm. jump to page 102. So. But rather than either. 16. and this is normally represented by a 1 for on is 170 (2+8+32+128). The first is octal. say. 64 and 128. And that value can be as 2’s compliment If you want large only as the number of bits the CPU supports. Using this logic with the above question. Computers use a numeral system called reference to 2’s compliment. If you write a PHP script for the web. is equivalent to 2. But you’d be wrong. and uncover the hidden meaning behind 1. which is -85 – the correct value. a scheme for handy display binary to store these on/off values within their registers and representing negative values in binary. the most significant bit – the one languages. topic in the 21st century. This is. If we move that script can have a huge impact on the performance of your bit to the left so that the 1 occupies the third slot along. yields 10101011. But what’s a bit? It’s represent in 2’s compliment? You might think. so that 1 becomes 0. Number systems are just as important for high-level assign them in that order. and it changes the mode for up to memory. Y ou wouldn’t think that numbers would be a relevant represents a number that’s double the bit to the right of it. its lowest level. The reason this method was chosen rather than swapping the most significant bit is because most binary arithmetic can still be performed on these negative values in exactly the same way they’re performed on positive values. If we enable every bit in an 8-bit binary number. 2. is 10 in octal. a process known as flipping. 4. and thousands of times a second. then with 1 added 11111110. we first subtract 1 from 10101010 to get 10101001 and flip the bits to 01010110. That’s a difficult couple of sentences to knowledge of how computers deal with numbers. These Consider the following question: what does 10101010 to see binary days. so that calculated or stored have an impact on performance. which gives a decimal value of 86. a base 8 system that uses the numerals 0-7 to hold 8 values. for example. Adding 1 to 10101010 (-86). so here are some examples: systems used to process them. WorldMags. which is the 2’s compliment representation of -2. that means either 32 or 64 bits. the negative of 00000010 is first 11111101. holding the largest value – is usually on the left. for example. right down to hardware and design. Typically. While we’re in the binary zone. 7+1. 8. that the binary value represented here in real time. or 00000010. information. single operation of the CPU can deal only with a value held within one of its internal registers. If we enable more than making any small binary value represents a number one bit at a time. Your code total value might be run doubles to 4. 2 and -1b1010101. it’s count them. and the digest. The position of each bit within a binary value meaning of the bits and what they represent. it’s worth mentioning a couple of other numeral systems sometimes used when programming. and adding 1 (there is a single exception to this). after the last registers update literally a switch that’s turned on or off – a single bit of couple of paragraphs. The clue is the KCalc has a and a 0 for off. having some minus 1 (or 28-1). And it’s not all for low-level stuff like assembler following values: 1. “The position of each bit within a so on. discrepancy in then all the values how those that’s double the bit to the right” are added numbers are together. so the answer to the question is -86. a we get a maximum value of 255. 00000011 represents 3 (1+2) and 10000011 represents 131 Numbers are important because they engage the CPU at (128+2+1). So. in fact. But for better or worse. reversing the configuration of bits. the binary small changes in the way you process numbers within the number 10. It does this by 64 bits of data. will help you to write better The positions within an 8-bit binary number have the programs. if there’s one thing giving a sequence of bits the ability to represent every value computers can do well. 48 | Coding Made Simple WorldMags. the servers.net . After all.net Hidden secrets of numbers Allow us to channel the living spirit of Dan Brown. 32. Billions of between zero and double the value of the most significant bit times a second. hexadecimal. and no more. for Ø1 1 1 Ø1 1 1 example. there’s short int. and how the underlying systems that take your code and make it run work. unless you want to. such as when rounding the value of pi to 3. it has numbers. such as 0. you need to prefix the something called an include file for C and C++. On most machines. there’s tip Data types long int and if you need smaller. and this limit is hidden within want to input a 2’s compliment binary. and it’s another create a utility that variable as you come to use them. and that’s the equivalent of four bits of data. As you can see with the last example. An 8-bit value has become known as a byte. they do when many of these are combined. which is most often ‘-0b1010101’ defined as int in programming languages such as C and C++. you’ll find replacing the 0b with 0c and with hexadecimal by using 0x. ‘0b1010110’ hardware and its internal representation of a value as bits. But understanding a little about what they mean and how they relate to one another OR XOR can help you when looking at other projects. like early bytes.net Coding Made Simple | 49 . codes with any reasonable binary editor. it’s (the value held by an 8-bit value). Q WorldMags. because they wonder how they’re have decided to forgo the advantages of specifying the size of to read or write to supposed to know what they need to use before they write a variable for the simplicity it gives to programming. But unless you’re dealing with small fractions. Typing a binary number will output the decimal value: =1 1 1 1 = 1 ØØ 1 >>> 0b01010110 86 Binary and You can convert values to binary using the bin function: that reason. The compiler or interpreter needs to know about type One set of types we’ve neglected to cover is those that because it wants to assign only enough memory and include a floating point. which is why it’s often used when you play with binary values. and for storing raw binary data = 1 ØØ 1 within your program. that an unsigned int can hold a maximum value of and both of these numeral types have supporting functions 4294967295. you can do so using Python’s interpreter. This is an binary formats. because the designers hold together is essential if you want confusion in the beginner. If you architecture of your CPU. through the its dire consequences. you can enter a binary value using the 0b prefix – that’s a zero followed by the b. in reality. there’s no need for the usually enough just to create a variable of type float to deal compiler to ensure more than this amount of storage is with these numbers. If you know worry about the size of a float. this also works with The largest number an int can hold depends on the negative integers. This problem. where most machines rounding errors in employees’ payslips into his own account. which is base 16. there’s no standard storage size bitwise operators bring logic to >>> bin(86) for many data types. >>> bin(-85) The best example is an ordinary integer. and this is a great way of getting familiar with how the numbers work.14159. A byte’s worth of data is still used to store precise number. characters to this day. you need to specify the generally don’t need to worry about any of this in languages how bits and bytes type of a variable before you can use it. >>> oct(85) This is why an int is usually the most generic variable ‘0o125’ type. You Understanding In many programming languages. because this is typically used to store a single introduced by rounding a value up or down from a more character. communicates with external hardware. The biggest problems when dealing with floating point Although the number of bits in a byte used to vary. It always depends on your computer’s your programs. and But computer hardware has moved on. If you need larger.net just as 9+1=10 in decimal. Hex is a more Ø1 1 1 readable equivalent to binary. which is why it’s often used for memory and binary editors. you write the declaration for each example of something known as Duck typing. it’s the precision that’s your variable is never going to have a value greater than 255 important. Similarly. From version 2. uses the characters 0-9 and a-f to represent decimal NOT AND values 0-15. WorldMags. reason why Python is such a good beginner’s language. 1 1 1Ø 1 1 1Ø If you want to play with numeral systems. But. to the pure 32-bit Pryor’s character in Superman III when he siphoned off the PCs of the last decade and to today. and if you paste this value into a binary for converting integers: calculator. Ø1 1Ø which as an 8-bit value equates to 108. You can avoid using these numeral systems in your code =Ø 1 1 Ø and your projects won’t suffer. which you can view through ASCII While small rounding errors aren’t likely to cause problems.5 or 3. So. This can cause such as Python. For and amassed a large fortune. was brilliantly illustrated by Richard 16/32-bit era of the Atari ST and Amiga. or the code. and why programmers try to stick to integers. returning a 2’s compliment binary. available. Rather than processing to handle that number. are settled on 8. 1 1 1Ø the number 6c in hex is 0110 (6) and 1100 (12 = c) in binary. you’ll see this requires 32 bits of storage – >>> hex(85) probably the most common architecture in use. have a processor capable of handling 64-bit instructions. It takes exactly three binary bits to BITWISE OPERATORS represent a value in octal. it can store large numbers and can be addressed Quick efficiently by most recent x86 CPUs.6 onwards. Even 64-bit ‘0x55’ machines can properly interpret 32-bit values. and an data with -0b. You can do similar things with octal by equivalent for other languages. but it gives you a better insight into what’s happening: for ( int i=0 . linked and run (this is the big difference 50 | Coding Made Simple WorldMags. a loop on its own is used mostly to programming sense. because it includes the implicit definition of a variable. as ways to step through data. Without loops. programmers are 1 forced to write everything in longhand. is a chunk of the same code that’s solve a simple calculation. This line needs to cpp -o helloworld’. Range is a special the command previous tutorials in this bookazine. leaving the loop when it gets to 5 (a total of five steps when you include zero). It’s the idea of a loop. you can’t really guess at the the results. we’ve already programming task would called i in examples. and it’s the same with other languages. It’s the 3 difference between sowing a field by hand or by using Jethro 4 Tull’s horse-drawn You can see in this snippet seed drill. the syntax looks slightly different. Which is why. because it requires a specific With a method or a function. we’re returning related to the idea of recursion. and for filling arrays and files./ any time discussing the various kinds of loops you can part of the for loop (as denoted by the :). condition. helloworld’ to see implement. or for waiting for a specific designed by the programmer to be run over and over again.. the variable i iterates between 0 and 4.. and how in recursion calls another instance of itself.. move to the next page. Otherwise. try reading this again. for when you need to wait for a On the following line. almost any requires a variable. and without loops almost . peculiar parts of any language. . a know only what input is needed and what output to expect. Ours is used several of no exception.net . in the more complex solution. } When compiled. The for loop is one of those they’re self-contained islands of logic.net Using loops and using loops If we have explained how to use loops adequately. A loop is a >>> for i in range (5): much more primitive construction. condition. perhaps. In many ways. This is because for is slightly different from most loops. A fter losing ourselves in the surprisingly complex problem by adding a loop in your code. because while combines a conditional statement within a loop’s structure – they’re both designed to be re-run over and over again too. we print the value of i. A loop. output from the syntax of the for loop. and that’s the for keyword. “Without loops. This is followed add the source code to a text file them in our become impossibly tedious” in Python by the phrase in and build it with examples in range (5). ‘g++ helloworld. typical for loop looks like the following: Everything else should be handled by the function. the programmer needs to syntax that doesn’t feel that logical. or how you might attempt to solve a linear But without prior experience. i++ ){ cout << i << endl. the most common loop It’s different from a function or a method. usually to build a programmers use them to solve problems. They’re used as counters. You just have to accept that whatever syntax they do use does the equivalent of defining a variable and creating an acceptable set of circumstances for the execution of your program to leave the loop. that the initial for statement If you want to Loops are so integral to code. In our previous example. We print the value of i within the loop so you can see what’s happening. which for some reason is nearly always build your own C++ application. But we’ve not spent be tabbed or spaced in because it’s going to be executed as Just run ‘. i < 5 . keyword in Python that we’ll revisit in a couple of paragraphs. But where a loop or function to a simpler concept. print (i) any programming task would become impossibly tedious. WorldMags. they’re domain of using numbers in our code. This is because they encapsulate what computers do well: 0 repetition and iteration. and write code that 2 can’t accommodate unknown values or sizes.. If you write the same thing in C or C++. In the case of Python. check. within your block of code. However. This is exactly what the Python loop is doing. many languages also It’s simpler this way. as follows: it illustrates one example where do. the output is identical to our Python example from earlier. and building into your code the certain circumstances.net Coding Made Simple | 51 . This includes only the conditional if you use a do. This might sound like insanity if you ever want the Quick while. This can be helpful in arguing against infinite loops.net between compiled languages such as C/C++ and interpreted languages such as Python and JavaScript). The advantage of farming it out to a function is that do { you experiment you’re no longer restricted to using it in just the for loop. but it’s slightly more efficient and elegant alternative is a while loop. Using an because we’re used 3 infinite loop means you can be sure your application is to thinking of zero as nothing. but it’s 2 running. for example.. Of course. Range is a function in Python that takes a start point. you need to have first grabbed the input... such as the first position in an . break can be used to rather than adhering to those required by for. and you’re free to make that check positive in any way This is all the above loop is doing in C++. you could modify the for loop. Using break. but this can take take some input and then only test against that input at the more effort and might not be as efficient. so you could get the value of i to count down instead by changing the loop to: for ( int i=5 . by making the while loop wait for a variable consist only of the x character. and that’s using conditional checks for leaving a loop as complex as you need. Q WorldMags. as you don’t need to restrict yourself to numbers – range can use indices of Python is still a sequence. where the use of an infinite Nearly all languages >>> while i > 0: loop is the best way of building your application. You should be able to see from this that both the value of i and the value checked for by the condition can be changed. If you want to check the state of some print (i) input. the while statement at the end of the normally use this section of code to tidy up files. an infinite loop – simply a loop that never satisfies its exit In Python.. but not Python. because the do is used to start the user wants to quit the application.. WorldMags. is to place the conditional loops early if you need to. It’s also much more versatile. and isn’t useful in itself.while works well. but typed your code. like this: processor to skip over the remainder of your code. It grabs some input you choose. and the cout line is simply printing out the value of i during each iteration. the best you enter the loop. for example. If you wanted to count down in Python. This seems . and just something you 1 using while is probably the easiest way of creating one. and hasn’t exited under some other condition. this function would look like this: smaller applications.while loop to encapsulate the entire function. we need to take a closer look at the range keyword used in the first example. If you put on one value in the range. there’s a good case for while there are still some dirty plates’. 0. whether it’s from a file or from someone typing on the keyboard. One example count zero as a . and for i in range(5. However. much the same as the inputs for a C++ for loop. i -= 1 is if you want to build a tool to monitor the state of a server or value. i > 0 . and you’d Most importantly. a stop point and a step size. and cin >> c. } To do the same in Python. and by using while you can make the provide an escape from loops like this.. as well as leaving other kinds of other languages. the variable i is declared as an integer (int) and incremented (i++) one value at a time for as long as it remains less than 5 (<5). such as when you want the loop to ability to escape on a specific condition. because it lets effect. we could recreate the previous for loop using condition. and languages. for example if you have detected that the called a do. the execution section and the while is used to close the section. -1): that’s taking input. Another trick in escape from an infinite loop. array. something called the break command.. In C++. to reach a certain value. processes loop is checking the condition.. the function counts from zero up to to learn with the value -1. You could Infinite loop do this in a normal while loop by asking for the input before If you don’t need the iteration of a for loop. after which it quits the loop. 4 controlling the rendering within a game engine. anything else will create a different char c.. i--){ cout << i << endl.while loop... This is normally for loop quickly. but there tip >>> i = 5 are certain times. of your code continues after the loop section. This example is oversimplified. You also find infinite loops watching hardware inputs or illogical at first.. print (i) some other service. such as ‘do the washing up and memory before an exit. You could easily emulate the behaviour of a for from the keyboard using cin. Another common use for while is to create what’s known as make sure your calculations attain that value at some point. 0 (true) {} is all that’s needed. Then. especially for end of the test. as we a great language did in the original loop. and see results you’ll find many programmers use range for convenience } while (c != ‘x’). while have to get used to. and waits for that input to loop. In the C++ code. You might want to escape from a checking at the end of the block of code. as soon as you’ve throughout their code. resulting file isn’t intended for human consumption. wouldn’t it? Finding mistakes puts(“Hello. from the GNU project. but Compilers exist for many different programming they don’t understand human languages. and that is what we are going to directly tell the CPU in English that we want to print a use here.c and then run the following commands: gcc foo. C omputers aren’t actually very smart.. Then main you’ll just see code is processed. we have to somehow tell the machine this information Dissecting a program in binary. human.c from the source code into a binary executable file called a. such as the zeros – because that’s all that a CPU understands. and it’s one of the most important components of a million things in the space of a second. and readable source (stdio). The execution should begin). like this.out: ELF 32-bit LSB executable.out. for GNU/ Linux 2. First of all. this makes things a bit complicated.. not stripped If you try to examine the file yourself. but there’s a difference between compiled and interpreted languages. If you’ve never seen C before. This is because we mere mortals can’t read binary. enter this command: 52 | Coding Made Simple WorldMags. would be nigh-on impossible. Sure. as in the screenshot shown on the left. pulled apart.out The first command uses GCC to compile foo. to transmit videos of cats around the internet. and the second line runs it. languages. This final. then you’ll just see gobbledygook./a. Ultimately. In a code is processed. pulled apart the #include line says that we want to Try to read a binary compiled and converted into binary code” use standard input executable file in language. { That would be a nightmare. imagine if your programs looked like this: First up. but here we’re going to focus on C. to fix this problem. converted into binary code that the CPU can understand.out – you’ll see output similar to the following: a. So. and output routines a text editor.c . and so less is trying to convert it into plain text characters.out for instance. But then. consider this simple C program: 10010010 11100011 #include <stdio.net . and the puts command means “put up characters program that does this is called – naturally enough – a string”. For us Linux kernel. using less a. Intel 80386. dynamically linked (uses shared libs).6. where a load of messed. source brief explanation: on the latter later). they can do a compiler. jumbled up and eventually says that this is the main part of our program (that is. version 1 (SYSV). WorldMags. Enter this text into a file called foo. the entire concept of This simply prints the message “Hello world!” to the free/open source software falls apart.h> 01011011 10001101 int main() . wait for a key to be pressed and so forth. By far the most common compiler on Linux is programmers. because it’s everything in a computer boils down to binary – ones and the language used for many important projects. but we can peek into some of the stages in the compilation process. you might be a bit we use compiled puzzled by some of and interpreted the text. We can’t GCC. and help us an operating system.net The magic of compilers A compiler turns human-readable code into machine code. You can get more information about the resulting file by running file a. so here’s a languages (more “In a compiled language. message on the screen.15. and if you gave your code to } someone else for modification… Well. screen. world!”). Q the puts (put string) function from the C library. and (a. into CPU-understandable instructions. an interpreter reads It doesn’t know what’s coming up. call 80482f0 <puts@plt> the loop is going to be executed five Interpreted languages can. using the objdump 10 LET A = 1 interpreters allow you to pause them command. and it’s called assembly language. such as important. Assembly is a human-readable way of representing the instructions that the CPU executes. Most of them are unrelated to our program. this places the location of our “Hello world!” fundamentals. parsing complicated it’s a list of CPU instructions written in a slightly more instructions. and benefits. is a entire source code file and converts it much simpler program that simply those human-readable instructions into their binary into CPU binary instructions in one fell steps through the program line-by-line. Assembly But wait! There’s an intermediate step between the C code and binary. instead.h file have been included in it. knowing in advance that each line step by step during execution.LC0. the compiler can be useful where speed isn’t crucially a moment ago. and on the right a disassembled binary. (%esp) been written about the science of compilers – it’s not a call puts subject for the faint-hearted! But now you know the Essentially. in that you don’t have to Jump back! at run time.c > foo. GCC now runs an assembler to convert a program called a compiler takes an An interpreter. In larger.p WorldMags. As we’ve seen in the former. So. This file is then complete. In assembly. Those are the exact same instructions as the ones we saw times. the compiler can spot bare like this. So. In other words. where you can simply say “print a We’ve highlighted the areas showing identical instructions.(%esp) bigger picture. Now.net With the -E switch. the output from gcc -S.p in a text editor and you’ll see that it’s much longer than the original program. -E or -S switches). most programmers prefer Have a look at the list file now – it’s a disassembly of the 50 END compiled languages over interpreted binary file. without the interpreted. with all the information that GCC needs to start converting it into machine code. These two lines are exact CPU instructions – as programmers. expressed in a slightly different way.c language such as C++ is an even harder job than writing an This produces a file called foo. Having your whole work prints a message five times on the are used to tell the Linux program loader some useful things screen. programmer about them. But tucked away in there. the compiler does much more work in this ‘pre-processor’ stage. and we have a individual lines from a source code file just dutifully executes things as and program that’s ready to run. In contrast. Precision and the process of how human-readable source code is converted PRINT lines if that makes execution individual execution rule here. programming language: compiled and errors that might come up and warn the In the normal process of compilation (that is. for example the Bash replacing the whole bunch with five scripting language. that’s make various optimisations.out > list 30 LET A = A + 1 of execution. This offers some essentially interpreting each instruction advantages. Similarly. it can be quite humbling to see single instructions laid There are two main types of quicker. Given that modern CPUs execute billions of instructions per What are interpreted languages? second.net Coding Made Simple | 53 .s that contains the operating system. and you will certainly look at your code in a text string into a register (a little like a variable). and acts on them one at a time. It then adds extra information to the resulting file swoop. readable form. when it sees them. because the contents of the stdio. For instance. Consequently. take this wait for a compilation process to finish We can take the a. now enter this: that writing a fully-featured compiler for a complicated gcc -S foo. telling the CPU exactly a compiler are deep and complex. and then calls different way from this point on. like so: 20 PRINT “Hello world” and make changes in the middle objdump -d a. more complicated programs. in terms of managing variables. but these are the Don’t think for a second that we’ve completely covered two most important lines: the compiler here. It’s much lower-level than typical languages On the left. how would a compiler look condensed down into CPU-readable and set up the environment. Open foo. you’ll at it? Because a compiler processes the binary makes for better performance find these lines: source code file as a whole. passing control around to different functions. such as C and Python. we tell GCC that we don’t want a binary executable file just yet. you have never touched assembly before. and many process. equivalents. The inner workings of WorldMags. Most of it will look like complete gibberish if and so on. handles #define statements and places additional information into the file for debugging purposes. string for me”. It’s only right at the bottom that you can see the main function and our puts instruction. on the other hand. and therefore full of assembly language It’s pretty clear what this does – it ones because of the performance instructions. it sees the than a background program parsing movl $0x8048490.out file and go one step backwards in the BASIC program: before testing your work. we want only to see what happens after the first stage of processing. and many would argue which instructions it should execute. It expands macros. to the assembly language stage. gcc -E foo. 40 IF A < 6 THEN GOTO 20 Ultimately. you have to move memory around into the video buffer – for instance. Shelves full of whopping great books have movl $. Think of all the work a compiler has to do assembly language version of our program. however.out) to make it a valid Linux executable. there is no way that we can break them down into smaller pieces. or it could be as complex as describe what it does and how it does it. forcing you to sell your home and declare what your own code does. and because self-contained code functionality is easier to test and forget about. When you going to write or how you’re going to solve a specific problem. you’re not expected to understand you should always go back and clean up whatever code you how a specific function works. This might sound strange. they are there purely to help could also mean a subtle rounding error in your tax returns other developers and users understand what a piece of code that prompts the Inland Revenue to send you a tax bill for does. you need to change over time. Even if you’ve had four cups of coffee and triple- check every line you write. This might mean it interpreted by the language or the compiler – they don’t crashes and dumps the user back to the command line. the comment will also be coloured differently to make it more obvious. way. Finding the problems weeks or months. But we don’t mean you need to write a book. You need only to study the The IDLE end up with. one of the most frustrating things you have to the delicate art of troubleshooting. for example. while you can’t always plan what you’re This is exactly how external libraries and APIs work. memory problems or just inefficient code. Either simple text descriptions about what your code is doing. your usually including any inputs and expected output. It might be as simple as a typo – a missing revisit these old bits of code. Comments are broken logic. Keep your words as brief as they need to be – sometimes that might mean a single line. You should model your own comments on the same idea. but no matter how clear your insight might have been when you wrote it. hunting down problems than you do coding. But. you don’t your variables making your project as easy to understand as possible have to know how it manages to be so efficient. When your applications grow more complex than calculates and how it works. both because it makes documentation easier. In Python. t doesn’t matter how much care you put into writing your becomes important as it starts to grow. documentation of the interface and how to use it within the Python IDE has a redundant variables and bolted on functionality into illogical context of your own code. but you don’t really want to cause too many. even though do is solve a difficult problem twice – once when you create our examples of code from previous tutorials stretch to no the code. If you want to can show how code easier to maintain and easier to understand. Everything a programmer needs to debug mode that places. they are there to remind you of millions of pounds. WorldMags. and your skills in programmer. you can spend more time you to understand anything about what a piece of code does. How you add comments to code is dependent on the language you’re using. They’re not program won’t do what you wanted it to. The importance of documentation The first is that. give it a few days. install Qt.net Avoiding common coding mistakes Bug reports are useful. the second thing you should do is add a few comments to bracket or the wrong number. and again when you want to modify it but don’t more than 10 lines. the results will always be the same – at some point. before you worry about debugging. and it may as well have been written by How quickly your mistakes are detected and rectified is someone else for all the sense it now makes. But it affect how your code works. Everything that comes after this symbol will be ignored by the interpreter. know only what to send to the function and how to get the results back. Going back and cleaning up these areas makes the know should be included in the documentation. you should follow a few simple rules while writing your code. sooner or later you are going to make a mistake. Here’s what to avoid and how to avoid it. And as a dependent on how complex the problem is. you’ve probably needed to debug them as understand how it works. for example. comments are usually demarcated by the # symbol in the first column of a line. The more detail 54 | Coding Made Simple WorldMags. or may even obviate the need for just a few lines or functions. for instance. yourself bankrupt. And use Qt’s excellent sorting algorithms. For instance. and if you’re using an editor with syntax highlighting. Which is why as you need to know only the inputs and outputs. more importantly. A line or two of simple description you’ve transferred them from these pages to the Python can save you days of trying to work out what a function interpreter. and you seldom I code. Whenever you write a decent chunk of functionality.net . This is because it’s likely you’ll have used now. for example – although Python is pretty better wear your flameproof jacket for that release. When you start to code. for case sensitivity. This happens in C or C++. Most languages offer both inline and block comments. This is why it’s often a good idea to create your own variable names out of composite parts. give it to other people to test. you need to test it variable only after you’ve assigned it a value. something ready to release. Python users can denote blocks of comments using a source code literal called a docstring.Though not a programming language. But this does be. Initially. Q Comment syntax Different languages mark comments differently. if sense of code hierarchy. If you’re using an IDE. and usually have for example. However. but expect. which is Python a convoluted way of saying ‘enclose your text in blocks of triple quotes’. if. or that it needs a runtime errors. you use a variable without first saying what type it’s going to is all that’s needed to create unpredictable results. And when you’ve got you’ve assigned it a value. we’ve included this because you’re likely to have already seen the syntax. and they’re initiated by using a couple of little consensus on what a comment should look like. difference between compiled languages and interpreted ones. C/C+ can be – not just with the kind of values your application might even more random. and there seems to be of code on the same line. Python enforces this by breaking are in the correct A related problem that doesn’t affect Python is using execution if you get it wrong. you can go back and flesh out your thoughts when you don’t feel like writing code (usually the day before a public release). you’ll introduce many errors without realising it. or a comment after a piece different start and end characters. Watch out for using a single equals sign code be ready for the wild frontier of the internet. else. colon at the end of compound statement headers. such as int x to declare x an integer. When # is followed by a ! it becomes a shebang # and is used to Bash tell the system which interpreter to use. you can’t assume a default value created don’t make sense. for example: #!/usr/bin/bash BASIC REM For many of us. and sometimes a misplaced bracket script won’t run. this is the first comment syntax we learn C /* This kind of comment in C can be used to make a block of text span many lines */ C++ // Whereas this kind of comment is used after the // code or for just a single line <!-. WorldMags. there’s a good chance that its syntax highlighting will stop you from using a good at catching these problems. but with an extra * at the beginning */ = heading Overview As well as the hash. It’s only after doing this can make Python trickier to learn. not necessarily generating an error. Typing print (x) in Python. # A hash is used for comments in many scripting languages. If necessary. lambda. of text (or code you don’t want interpreted/compiled). but with anything that can be input. Your code should the value held in an uninitialised variable is unpredictable until fail gracefully. in Perl you can also use something called Plain Old Documentation. class and break.net Coding Made Simple | 55 . especially with keywords and your own instance. if you don’t stop a lot of this you can use the variable in your own code. like this ‘’’ WorldMags. Typos are also common. and you’d to check for equality. This is the big know about its strict tabbed requirements. there are characters before the comment. Block comments are used to wrap pieces a couple of rules. will result in an error. but other languages try to make place. you won’t know what is and isn’t a keyword – a word used by your chosen language to do something important. Only then will your syntactically correct. To begin with. with x = 1. in action --> Java /** Similar to C. This is because the interpreter knows the type of a When you’ve got something that works. the errors However. This is careful in Python that the colons where conditions and functions use code hierarchy to split and indentation Undeclared values the code into parts. Inline are usually for a single line. Python is good at avoiding is inaccurate indenting. in both languages. rather than go with real words. because it can span lines. rather than randomly. Each language is different. where they can go undetected because they are your code in ways you couldn’t imagine. but don’t write a book. or your undeclared values. so make them as brief as you can without stopping your flow. but not if you precede the line variable names. for instance. as well as less obvious words such as yield. import. but it does Perl force you to explain your code more thoroughly =cut ‘’’ As well as the hash. and HTML therefore comments. Adding comments to code can be tedious when you just want to get on with programming.net you put into a comment the better. You also need to be careful about for an uninitialised variable. However. raise and assert. but Python’s list of keywords is quite manageable. for example. especially in conditional They’ll have a different approach. It has a specific format. and will be happier to break statements. Another type of problem You have to be protected keyword. and includes common language words such as and. net .net WorldMags.WorldMags. ..............WorldMags............................................................ 76 Databases ...................................................... 70 Modules 74 ...................................... 78 WorldMags........net Coding Made Simple | 57 ....................................................... 64 UNIX programs part 1 ........................................ it’s time to advance your skills Data types ....................................................................... 66 UNIX programs part 2 ............................................................................................................................................................ 58 More data types .................................................................... Persistence .... 60 Abstraction ................................................. 62 Using files .................................................................................. 68 UNIX programs part 3 .............net Further coding Now you’ve got the basics down.............. ‘a’]. including slices. or integers. The computer has a few basic If you combine different types of numbers. ‘Fish’]. 65 The computer’s world is a lot more limited. It returns looking only at particular. type retains the most detail – that is to say. these are like a You can also use the same operations on strings and lists. we’ll look at a few more advanced topics that build on what we do here: data abstraction. In later articles. for example. there are all the different types of food multiply two numbers and Python will return the result: and the list that stores them – each of which has its own kind >>> 23 + 42 of data. What makes them I Python and the concepts that accompany them. In You can test this by using the type() function. Python knows about the type of whatever argument you pass to it. the elements are all strings. [‘Bananas’. ‘cake’. but it’s data that they operate on. such as ‘Hello World’. For instance. WorldMags. such as <type ‘float’> you’ll see a TypeError. there are lists. while the * operator repeats the contents of the string or list. basic data types. in a data in Python. 10. other types of numbers. >>> word = “Hello” >>> word[0] ‘H’ >>> word[3] ‘l’ >>> list = [‘banana’. too. but that doesn’t 2 stop it from working with them. 3 and 2580 are all examples of these. Lists are identified by the square brackets that enclose them. 10. but they have different effects. subtract. divide and shopping list program. Let’s go through the basics of data in Python. the value returned by Python will be of whatever represent all the variety in the world. and more. You can use >>> type(8 + 23. in that they are a sequence. the interest There are lots of things you can do with the different types of rate and the term of the loan are all types of data. In some ways. we’ll be covering the basic data types in string. which begins from 0. such as an int ones it can work with. There are also strings. Finally. The + operator concatenates. It doesn’t know >>> 22 / 11 the difference between all these data types. In a mortgage Working with data calculator. >>> type(8) in real programs floats (such as 10. there’s an amazing variety of different types of data. n this article. but you could create another list that mixes different types. too. such as such as trees.01) wrong type can ‘Banana’ and ‘Pizza’. These are identified as a sequence of <type ‘float’> cause problems. >>> “Hello “ + “World” “Hello World” >>> [“Apples”] * 2 [“Apples”. characters enclosed within quotation marks.35 or 0. In this example.8413) and complex (complex <type ‘int’> getting the numbers). we have and a float. and in the programs that we’ll write. the value of the mortgage.net .net Different types of Python data Functions tell programs how to work. In the world. and that you have to use creatively to and a float. “Apples”] Strings and lists also have their own special set of operations. if you add an int We’ll begin by highlighting three data types: first. two strings or two lists. ‘Oranges’. If you want to reference the last 58 | Coding Made Simple WorldMags. [‘Bananas’. While we’re numbers. and each item or element within them is What is data? separated by a comma. you can add. >>> type(23. These enable you to select a particular part of the sequence by its numerical index. these are ints. the returned value will be a float. ‘tiffin’] >>> list[2] ‘tiffin’ Indexes work in reverse. including longs (long integers). that is combines together.01) in which case either double or single quotes. fancy structures different is that the elements that make up a list can be of any type. ‘tiffin’. together. The second word in that construct function to a variable name: doesn’t have to be item.lower() English language dictionary. You can also see this in action if you apply the type() on each item in the list. ‘tiffin’. You’ll find you create a tuple you cannot change it – and that tuples are lots of useful tools. among the list type’s methods are append and insert. To see the order of the arguments and the so long as it’s unique within that dictionary. These are known as methods. Then you pass any arguments identified by round brackets. For example. It’s quite like an see how different >>> word. What makes them different is that they’re associated with a particular piece of data. It works the same with strings and any other data a tuple in that they contain a collection of related items. once provides for the data types we’ve looked at before. such as sort and reverse! Q WorldMags. too: differ in that the elements aren’t indexed by numbers. and hence have a different syntax for execution. ‘cereal’). we created the list as we would normally. Tuples are very similar to lists – they’re a sequence data In the meantime. They make it >>> english[‘free’] easy to manage all the bits of data you’re working with. and to tuples and dictionaries (which we’re immutable data type as the key (strings are immutable. WorldMags. the indexes don’t start at 0. If you try to use full range of methods available. -3 the third. then a single equals sign. we used the idea of variables to ‘as in beer’ make it easier to work with our data. The big become familiar with some of the other methods that it difference is that tuples are immutable – that is to say. -2 will reference the second-to-last character. >>> list. we’ll be ready to look at how you There are two other common types of data that are used by can put this knowledge to use when modelling real-world Python: tuples and dictionaries. and so on. Consider this data that you want to assign to that variable. but by Python code and >>> word = “HELLO” ‘keys’ and are created with curly brackets: {}. that’s just a variable name that >>> type(word) gets assigned temporarily to each element contained within <type ‘str’> the sequence specified at the end. about to look at). The key is the word that you’re data types work ‘hello’ looking up. too). ‘cake’. ‘burrito’] to the variable. read the Python documentation to type. its previous association is forgotten Python documentation. ‘chicken’] >>> list. and the value is the definition of the word. ‘chicken’] As you can see. you can use any lists and strings. problems in later articles. They’re similar to functions such as type() in that they perform a procedure. you’ll need to consult the an already existing key. and ‘as in liberty’ greatly reduce the complexity of development (when you use sensible names). ‘tiffin’. ‘pasta’. ‘cake’. First comes the name of the of the sequence types is looping over their contents to apply variable. Variables are a way to >>> english[‘free’] = ‘as in liberty’ name different values – different pieces of data. then we element in a list by appending index notation to the variable used the for… in… construct to perform the print function name. you can use the same notation with a -1 as the index. >>> english = {‘free’: ‘as in beer’.append(‘chicken’) >>> list [‘banana’. In the examples. each unique to that particular type.net Coding Made Simple | 59 . however. ‘tiffin’. small Python program: From that point on. ‘pasta’) >>> list [‘banana’. They experiment with object. completely and that data lost for ever. you are referring to the data that you assigned for item in list: to it. followed by the piece of an operation to every element contained within. a method is invoked by placing a period between the piece of data that you’re applying the method to and the name of the method. as opposed to square brackets: The Python interpreter is a between round brackets. ‘linux’: ‘operating system’} Variables >>> english[‘free’] In the previous examples. but with the Other data types basic data types covered. and they can contain elements of mixed types.net element of a list or the last character in a string. just as you would with a normal (‘bananas’. Looping sequences As we saw above. Methods Lists and strings also have a range of other special operations. Note that when working backwards. whenever you use the name assigned list = [‘banana’. in Python you create a new variable with One common operation that you may want to perform on any an assignment statement.insert(1. There are lots of different methods that can be applied to With Python dictionaries. That’s all we have time to cover in this article. Dictionaries are similar to a list or great place to function. we saw this in action when we print item referenced the second character in a string or the third First. We could just as well >>> type(list) have written for letter in word and it would have worked <type ‘list’> just as well. We demonstrated how they work with different operators. 60 | Coding Made Simple WorldMags. . The first is the name of the file to open. we’ll be using The Time Machine. WorldMags. and that we’re counting individual words. should be opened in: r stands for read.-. not lines.python. we introduced Python’s most tm = open(‘timemachine. lower() and split(). by HG The result should be every line of the file printed to the Wells. the first being None and the second being common word the list of characters to be deleted./:.txt’. For example.<=>?@[\\]^_`{|}~’) Machine. the and The). which removes specified characters from the beginning and end of a string. strings. By putting this code in to a . tm. the program will print the today we’ll be using a for… in… loop. lists.. consider the same word but in different cases as one word. As an example. program.. the entire path would have to be most useful methods. give much insight given. Looking at the Python string documentation (http:// docs. ‘r’) I common data types: numbers (ints and floats).net .txt. such as all punctuation marks. To see how this works. screen. We didn’t. whitespace characters. w for write or rw for read-write. removing a set of characters. by lower() speaks for itself.. results to the screen. We’re going to write a program that counts the number of Notice we’ve also assigned the file to a variable. which you can download from Project Gutenberg.strip() Hardly When passed with no arguments. tuples and dictionaries. with punctuation. There are several ways to do this.. we also need a way to different cases (for example. we can see that there are four methods that can help us convert line strings into a format closer to that specified by the description: strip(). and explained a few of their In this example. however. It should look like this: try opening timemachine. really – it converts every character in HG Wells. it needs to be passed be the most two arguments. n the previous tutorial. but to represent a single word.translate(None. Each of these are methods. ‘!”#$%&\’()*+. we have been able to read only entire lines as strings. in The Time >>> line. which is one of the jobs we needed to our counting get done. In this article. open() is passed two variables. is used like this: >>> line. so we times each unique word occurs in a text file. The second argument specifies which mode the file into how they might be used in real situations. however. it removes all surprisingly. and if the same word occurs but in With a reference to the file created. As it stands. strange whitespace characters (such as \r\n) and different cases intact. To use it in this capacity. but you can also use we’re going to fix that. strip(). the first thing we’ll Cleaning up need to do is make the text accessible from inside our Python The program description also specified that we should program. This is done with the open() function: exclude punctuation marks. Finally. after The function translate() is a method that can be used for being sorted. say cw.net More Python data types Learn how different types of data come together to solve a real problem as we write some code that counts words.py file. they will be taken access its contents. marks will be excluded.py.txt in the interactive interpreter the: 123 and then typing: you: 10 >>> for line in tm: a: 600 print line . we’ve saving it in the same folder as your Python file under the got the start of our Python program. Punctuation can refer to it later in the program. finds ‘the’ to from a string. As the program description suggests. translate(). and as such they’re functions that are applied to particular strings using the dot notation. if it were in a different directory from the Python script.org/library). name timemachine. abstract program. there is still some work to be for word. but in every line contained within This for loop looks different to what you’ve seen before. This dict[word] = 1 made sense until we wanted to consider unique instances. adding each entry to type for representing different abstract concepts. and in the process got to the exact. we started off with a single string occurred once in the file). incrementing it as the . one entry on a line. we’ve been able to remove all the bits of Another data type wrestled with. split() splits distinct elements inside a string in to separate strings. the key-value What’s more. At this point. is an Because all of the string methods return a new. concatenate an integer and a string.net a string to lower-case. rather than operating on the existing string.split(‘ ‘) In this example. Uniqueness Phew. too. By passing an argument to split(). very end of the file. With all punctuation removed. Try running it. That’s all we planned to achieve in this particular tutorial and Next. if the key already exists. we can use the value to store the number of filled with lines like: times each word has occurred. how to use them. the entire file. returning them as a list.translate(None. representing an entire line. and you should see your terminal screen What’s more. which is ready to receive Data everywhere! our words. It should now look like this: tm = open(‘timemachine. Put all of this in the Python file we started working on earlier. program comes across new instances of each key. representing a line. [\\]^_`{|}~’) dict[word] = 1. representing another occurrence. we As a further programming exercise. Notice. overwritten and the count will be reset. >>> line.<=>?@ else: reference.net Coding Made Simple | 61 .. and ensuring that it sick: 2 persists for the entire file – not just a single line – by placing ventilating: 2 this line before the start of the for loop: . thinking about uniqueness is of a dictionary. we are available and increment the count by 1. into smaller chunks by converting print the dictionary and put it all together and run the it to a list. ‘r’) for line in tm: line = line. As we saw last time.strip() dict[word] = count Python’s Standard Library line = line. We now need a way to identify which words are unique print word + “: “ + str(count) – and not just in this line. we’ve and seventh lines.-. count and 1 are assigned to that key’s for discovering re-assigned the line variable in each line to store the work of value. we’re guaranteed there won’t be any duplicates. line = line. we hope to the dictionary. ordinarily a simple chance to see how several different types of data and their assignment statement would be enough to add a new word methods can be applied to solve a real problem. other: 20 Start by creating the dictionary./:. WorldMags. outside of the line-looping code. at But remember. dict = {} This creates an empty dictionary.org/ list = line.. the dictionary with a value of 1 (to represent that it has For example.Q WorldMags. and we’ve made considerable progress. what methods the previous step. so by entering each word as a key within a dictionary. Our stunning progress aside.count in dict. another step closer to our data that we weren’t interested in. and we eventually split this into for word in list: a list of individual strings representing single words. To get around this. we can The first thing that should pop into your head when access both the key (word) and value (count) in a single loop. It doesn’t allow duplicate count. inside the for loop. As well as having had a the dictionary. as the + operator can’t keys. all that’s left to do is insert some code to string. we’ve passed a single space as the character to split the string around. with each word in the string stored as a separate element.iteritems(): done. modified value and assigns it to the variable count. this will create a list. into a string. it returns the library. an integer..lower() This is a little bit confusing because dict[word] is being python. it’s possible to specify which character identifies the end of one element and the start of another. while in the fourth invaluable source string. the old value is which point we put everything in to a dictionary. look at all that work we’ve just done with data! By using Putting it together the string methods. ‘!”#$%&\’()*+. to save the fruits count += 1 of your labour.split(‘ ‘) used in two different ways.txt’. why not look into can place an if-else clause inside the loop: sorting the resulting dictionary in order to see which words if word in dict: occur most frequently? You might also want to consider count = dict[word] writing the result to a file. By using the iteritems method of the dictionary. respectively. that if a word is already in the dictionary. we’ve had to use the str() function to convert store we saw in the previous article.. We’ve also split one large goal. The print section should look like this and be at the concept we’re most interested in: words. We could then iterate over the list we you’ve noticed how important it is to select the appropriate created above (using another for loop). we need to think about a way to get each word into it’s actually turn out to be quite a lot. In the second line. problems involving Pythagoras’ theorem. before returning to it in a later article.5 obscure code you have to copy and paste. only that want to consider is abstraction. We can treat the we’re first going to look at abstraction in general and as it square root button on our calculator as a black box – we applies to procedures. This second approach First. Solving building robust software). the more 1 2/1 = 2 (2 + 1)/2 = 1. I n the previous few tutorials. We haven’t listed the contents of each new function we’ve 62 | Coding Made Simple WorldMags. because it helps us to manage by thinking about square roots and different techniques for complexity. you can read about what is involved. As we repeat this procedure.5)/2 = 1. we have been looking at data. Square roots This a very powerful technique.0 guess (y). The next data-related topic we don’t care about how to calculate the square root. this time coming up with 1. 1. and even for finding the square root of a number. with a piece of code this short.5 2/1. You could type it all out again. we can do it and get the correct result. but the more typing you have to do. b): root. Creating abstractions can make code much easier to maintain. Calculators come with a button return the expected results – how would you start testing all marked with the square root symbol. and all you have to do is the parts to find where the error was? Finally. Sure. In most attempts. we’ll only make our guess more and more return guess accurate. to check that it works? What if this function didn’t method to find square roots. there’s useful code in here that could be reused in other functions. you’d have a terrible time figuring out what It’s a lot of work just to on earth it was doing. but before we get on to that. vital for steps manually.4167)/2 = 1.33 + 1. One of these was discovered by Newton. When working on and then we demonstrated how they can be put to use problems. finding them. we get closer and while (math.net Reliability by abstraction Think your code is solid? Perhaps it’s a bit too lumpy. we when solving a real problem.fabs((guess * guess) . or the code for improving a when you were at school. is what’s known as an abstraction. whether or not a guess is close enough to the actual result Luckily. written like this. would For instance. let’s start programming a lot easier. we introduced some of Python’s core data types.4167 = 1. but none of it is reusable because of the way it’s written.5 = 1.33 (1. we’ll never reach guess = (((a2b2 / guess) + guess) / 2) a definite result. we’ll reach a level of accuracy that is The first thing to note is that it’s not in the least bit good enough for our needs and then give up. What’s find the square root of a number.4167 2/1. assuming you were allowed to use calculators (and can you even identify it?). it would be very difficult to test the different you were in school. or copy and Guess (y) Division (x/y) Average (((x/y) + y)/2) paste it. and is consider the Python code below for finding the longest side of thus known as Newton’s method. take a look at the table below for how through it reasonably quickly and figure out what’s going on. we can then improve upon that result by averaging our a2b2 = (a * a) + (b * b) guess (y) with the result of dividing the number (x) by our guess = 1. such as those involving Pythagoras’ theorem. for Find a square root taking an average of two numbers. and the more likely mistakes are to make it in to your programming.4118 (1. So. this time we’ll take a brief hiatus never look inside it. To demonstrate how abstraction can help us. much easier guess.net .01): closer to the square root. every time you had to find a square technique that makes parts of this code as you go along (aka incremental root you had to do all these programming easier” development. we should start with a guess (y) of its square def pythag(a.4167 Let’s try writing that code again. how would you break out the code for testing be much more unwieldy. a right-angled triangle: It says that when trying to find the square root of a import math number (x). we don’t know how it does what it does.a2b2) > 0. you would apply this method to find the square root of 2 (for but at a glance it’s not obvious. WorldMags. for instance. which can make To get our heads around the concept of abstraction. from data.4142 some abstractions to fix the problems listed above. and if it were longer and example. all that matters is that we know how to use it and that it gives the correct result. such as that for squaring a number. Imagine if when “This is a very powerful more. there’s another. x). press this button once – much easier. Just to be clear readable.4118 + 1. Eventually. we could change the implementation completely. def improveGuess(x. we can easily test it. Assembler You treat it as a black box.net created. def closeEnough(x. WorldMags. To help keep a triangle is And. guess): . you’re not stuck with working Layers of abstraction through thousands of lines of code. . the purpose of which is also obvious. You just accept the fact that typing 2 + 3 in to the Python interpreter returns the correct result. For instance. we’ve split the code in to several smaller functions. function – six characters instead of four lines means there’s def sqrt(x.. guess): generally better. this example has demonstrated how powerful a section that finds a square root. These functions are now visible only to code within the improved by taking sqrt() definition – we say they’re in the scope of sqrt(). What’s more. Anything outside of it has no idea that they even exist. One final point: because our sqrt code is now abstracted. This code can be improved still further by taking layers of abstraction present in everything you do on a computer that you never think of. you could just call the sqrt() inside the definition of sqrt(): start. WorldMags. This advantage of scope” way. all code colliding names or the headache of figuring out what that relies on it would continue to work properly. each of which fulfils a particular role. to work with binary numbers. and far less opportunity to make mistakes. and you never have to worry about how it does this. guess): . manually changing every Hopefully. “This code can be .. and it’s done technique abstraction is... def sqrt(x. functions are unlikely to rely on their services.. we could quickly test all these auxiliary functions to particular to the sqrt() function – that is to say. This means that if you come across a much more efficient way of calculating square roots. leaving them for you to fill in. and translate alphabetic characters in to their numeric representations – There are layers of abstraction underneath everything thank goodness for abstraction!Q you do on a PC – you just don’t often think of them.. we can easily reuse any of these new our code clean.. of course.net Coding Made Simple | 63 . other longest side of narrow down where the bug was. if we later need to define similar functions for improving a guess in a different context.. For example.. but so long def improveGuess(x. you can see clearly that a2b2 is the result of squaring two numbers. guess): . import math: def square(x): . we can place their definitions what we had to a different function.. Our final code If pythag() itself was found not to return the correct advantage of scope. and make the relationship between these longer than functions. for instance. guess): more robust. def closeEnough(x. do the improvement by hand.. Think how much longer it would take you to program if you Object code had to manually take care of what data went in which memory location. For starters. guess): . If you were finding the square root of a number in functions and sqrt() clear. This has many benefits. but it’s more readable. closeEnough() and improveGuess() are for finding the result.. because each part of the code has been split into a different function.. improveGuess1() and improveGuess2() do. def pythag(a. we won’t face the issue of as we kept the function call and arguments the same.. and then compare your results with those returned by the function. and everything below that has been consolidated in to a single function call. how much easier is the pythag() function to read? In the first line. you do it once. Bear in mind that there are many everywhere. b): a2b2 = square(a) + square(b) return sqrt(a2b2) Here. when you’re programming do you know how Java Python represents integers in the computer’s memory? Or how the CPU performs arithmetic operations such as Abstraction addition and subtraction? C The answer is probably no. testing whether improveGuess() was doing the right thing would be very easy – come up with a few values for x and guess. or Google’s bots skimming websites for data to easy depending on how many assumptions the language is feed its search engine. This is read a file. because nothing is end in chunks the output from the command to a file called list. Python will generate a “No such file or directory” error. Every language will include functions to load punched cards to get patterns into a 19th century Jacquard and save data. as with most other languages. the current directory. before explicitly closing the directory. creating one if it doesn’t familiar with on the command line. reversed alphabetical list of a folder’s contents. but you able to change it. dealing with external input is as willing to make on your behalf. but it becomes difficult when you need to know where to store a configuration file or load a default icon. When you type ls to list exist. it won’t usually allow access. Most languages require you to specify a read mode outputting the contents to another. ls | sort -r will pipe (that’s the vertical bar same table. many data from the use that output as the input to another. logical sequence of events that need to occur.net . WorldMags. However. and if the filesystem knows the file is being step through its helps when you want to save the output of a command. and it’s one of the more tedious issues you’ll face with your own projects. exactly like a file. the inputs and outputs aren’t files in the sense filesystem whether to expect file modifications or not. And it’s a problem and a concept that you may be more You will first need to open a file. but that’s the way the Linux important because many different processes may also want languages will filesystem has been designed – nearly everything is a file. or changed. This is within the folder from where we launched the Python interpreter.net Files and modules done quickly It’s time to expand your library of functions and grab external data with just two simple lines of Python. we’re reading a character) the output of ls into the input of sort to create a In Python. If you know about databases. for instance. “r”) If the file doesn’t exist. or write data to the contents of the current it. folders and file locations can quickly become complicated. processes can access a read-only file without worrying beginning to the You may already know that typing ls >list. because this tells the When you Of course. most most people would recognise.txt. opening a file to line at a time. there’s always a fundamental as programming itself. we’ve used the output from our command line example to create a text file called list. contents of a file. with some creating keywords for common locations and others leaving it to the programmer. These locations may be different depending on your Linux distribution or desktop. you don’t get complexity of how data input and output can be far before facing the age-old problem of how to get accomplished is entirely down to your programming data into and out of your application. you might want to consider using environment variables. This to access the file. and then either read data from this file. In can take this much further because the output can be treated kind of problem you face with multiple users accessing the this example. but this can either be difficult or textile loom. they’ll also be different for each operating system. the file again so that other command is reading in the “If the filesystem knows processes can use it. To avoid this. These are similar to variables with a 64 | Coding Made Simple WorldMags.txt. For that reason. it won’t allow access” when you open a file. for example. and then the file is being changed. You’ll find that different environments have different solutions for finding files. Environment variables Dealing with paths. F or the majority of programming projects.txt”. the terminal.txt will redirect about the integrity of the data it holds. The write or as read-only can be done with a single line: >>> f = open(“list. Whether it’s using environment. This isn’t so bad when you only deal with files created by your projects. However. it’s the same you specify. but with a cross-platform language such as Python. When you then try to read the input. If you type env on the command line. where file – or no file type at all if it’s raw data. Repeating the code you’ve just added to your project.environ[“HOME”]+”/list. Modules extend the simple constructs of a language to add portable shortcuts and solutions. But all we’ve done is open the file.net Coding Made Simple | 65 . but not in the same way we opened list. most importantly. associated file Setting the standard Python knows which home folder is yours. as well as file input/output and support yet read any of its contents. for instance. turning code to your project: Binary files have no context the way they do things into a standard. and the one we have asked it to Which is why you default. and what it requires as an input and an output. binary file are organised according to the file type used by the If you were programming in C or C++. output when you for specific file types. use f. and more can usually be installed with just a couple of clicks Alternatively. and these embed standard os. You will find the documentation for what intuitive. which is why this is also the way nearly all does. at least for the initial input.txt”. is common to the vast majority of languages. Internally. You languages work. /lib/python2. They will become dependencies read it into a string. and you’ll see a few that apply to default locations and. you’ll see the file. This file is known as a module in Python terms. if you wanted to read the entire file. This might seem counter. Only it’s better than that. you’ll see a list of the environmental variables currently set for your terminal session. Look closely. the else. copying the But this is where the ugly contents to a Python string spectre of dependencies can is an easy conversion. you’ll see the and output this to the interpreter as a string. The start to have an effect on your “If you load os. This will list each function. which is what package managers do when to add a b flag when you first open the file. for example. you’ll need to do some extra provide a portable way of accessing operating system. The value assigned to this environmental variable will be the location of your home folder on your Linux system. because modules such as os are used by everyone. ways of doing many things a language doesn’t provide by an environmental variable.x will include all the The above instruction will read a single line of the text file modules. because Python is functions are now accessible to you. To see what we mean. you need to make sure that person has also got the code you’ve just added” organisation of the bits and bytes that make up a same modules installed. including statements and definitions.close might be. data types return is HOME. As you might guess. many different modules for Python – it’s this is being done using something called a pointer and this. If you load os. Getting back to our project. which is why other languages might call them libraries.”r”) without an This line will open the file list. for example. what it used to be stored. any other programming language) would be unable to extract those binary libraries will also need to be present on any other any context from a binary file. The line to do this is: import os This command is also opening a file. Libraries and modules are a little like copying and pasting someone’s own research and insight into your own project. This includes knowing where your home directory f. f = open(os.py into a text editor. we first need to add a line to import the operating system-specific module. you’ll see the hexadecimal values of the file output The os module to the display. so that a programmer doesn’t have to keep re-inventing the wheel. as this should ensure the integrity of your applications without worrying about where files should be filesystem. WorldMags. one called HOME. It’s only after a file has been opened that you should also be able to find the source files used by the import can start to read its contents: (and by #include in other languages). but they apply to any one user’s Linux session rather than within your own code. which we’ll look at next. add the following piece of And it’s as easy as that! Q WorldMags. As a result.net global scope in many programming languages.readline() systems. too. and modules like this ‘import’ functionality. work.py into a same isn’t true of a binary project. because the type and a way of There are even libraries called std. as well as which command will read the next line. make sure you close dependent functionality so that you can write multi-platform the open file. one of the best reasons to choose it over any other language. such as common mathematical functions. remembering how far through the file it has read. we’ve not get the raw data and string services.txt. The solution. you could from your package manager. the os module is designed to To make this data useful. but first. the command looks like this: placed. warns Python to expect raw binary. and if we want to use this within our Python script. because if you want to give your code to someone text editor. because this you install a complex package. There are many. causing an error if you try to system that runs your code. Because our file contains only text. is for your project.read(). Python (or your code is compiled and linked against binary libraries. a library does within an API.txt in your home folder. Rather than being treated as text. but it’s an historical throwback to the way that files read one.environ function from the os module returns a string from handling them. On most Linux f. or otherwise manipulate. it’s writing real programs” arguments: -E. so if you want to follow along. while using sends the output to standard out. because in Python files are iterable objects. line by line. not write to it. as follows: for line in file: print(line) The print function then causes whatever argument you The final program we’ll be implementing. and -n. send each line of the files to This means it won’t take too standard output. cat. we’re going to create a cat clone that can work with any number of files passed to it as arguments on the command line. Python files Let’s start with the easiest part of the problem: displaying the contents of a file. This time. at which point it because it’s small and focused on a single task.txt”. you access a file with the open function. because we passed a second argument to the open function. WorldMags. This is very easy to achieve. that when called with no we’re going to create a Python implementation of the arguments accepts user input on the standard input pipe popular Unix tool cat. the next task is to display its contents. but will also “You now know more whole of the first file. Create a Python program. We’re going to be using Python 3. “r”) This creates a variable. r.txt. this means you can access each line contained within simply by putting it in a for loop. which returns a file- object that you can later read from. like so: file = open(“hello. which will make it put $ signs at the end of learning the ins-and-outs of your chosen language’s libraries each line. With a file. file. which specified that the file should be opened in read-only mode. that’s what we’re aiming to do: get Our goal for the project overall is to: you writing real programs. It should accept two Standard Library. Iterable objects. It’s not long. different operating system features. displaying the long to complete.py should pipes and so on. cat.net Write your own UNIX program Try re-implementing classic Unix tools to bolster your Python knowledge and learn how to build real programs.net . such as lists.py. make sure you’re using the same version. It will only allow us to read from this file. To capture this file-object for use later in your program. With access to the file now provided through the newly- created file object. number at the beginning of each line. In Python.x. then the expose you to a selection of Python’s core features in the than enough to start whole of the second file. on standard output. of core language features you’ll be able to re-use time and again. I n the next few pages. but it makes use of a lot pass to it to be displayed on standard output. When called with file names as arguments. 66 | Coding Made Simple WorldMags. Like all Unix tools. line by line. including accessing files. cat is a great target until an end of line character is reached. Over the next few tutorials. allow you to access their individual member elements one at a time through a for loop. because some features are not backwards- compatible with Python 2. to standard out. that will later allow us to read the contents of the file hello. tuples and dictionaries. strings. you need to assign the result of running the open function to a variable. and once you’ve mastered the basics. which will make it put the current line that will let you get on with real work. Python this. so to access it. you need to loop over all the how much work is available for you to recycle).net If you put all this in a file. This simple shortcut function takes care of opening each file in turn and making all their lines accessible through a Many files single iterator. and how a files in the argv list. this is a fairly straightforward task. be able to use it to recreate the rest of our cat program so far. The part of the sys module that we’re interested in is the argv object. which is part of the Standard Library.argv[1:]: about this. there’s a glaring omission here: we would have to edit the program code itself to change which file is being displayed to standard out. when implementing new programs. add: import sys The output of the real Unix command. our program can only accept example. but compared to the real cat command. otherwise everything would be on one line!). you’ll see that it works rather well. you need to type In order to use this shortcut. WorldMags. provides a shortcut for doing To access the list.argv. Since Python has ‘all batteries included’. cat. but as things stand. operations. The Python interpreter automatically captures all arguments passed on the command line. and output all their contents to standard output. This tells print to put an empty string.py from the command line.txt with sys. for line in fileinput. There is one oddity. our program is meant to accept more than one file That’s about all that we have space for in this tutorial. you must first import it by sys. you first have to import it to your program and then access its contents with dot notation – don’t worry. Knowing this. end=””). you’ll realise this is easily done with a slice. end=””) pass the name of any text file. Passing arguments This is all right. Instead. even if you can’t see it. much is available in Python’s Standard Library (and therefore To fix this particular problem. Because there’s already a newline character at the end of each line in hello. Even though sys is part of the Standard Library. First. to import it to your program. to the top of your cat. which means you can because this is the name of the program itself. we’ll explain this in a moment.input(): When you call cat.argv[1] to get the first argument to putting import fileinput at the top of your code. the second newline character leads to an empty line. one after Although there has not been much code in this particular another. or sys. called fileinput. make it executable and create a hello.argv[1]. named argument such as: print(line. so that we could call our new program by typing cat. Q WorldMags. This object stores all of the arguments passed on the command line in a Python list. You will then your program. are exactly the same in this simple example. makes this available to your code. say. You can fix this by calling print with a second. and it will work just the same. as well.txt (there is.py hello. we hope you have started to get a sense for how one file as an argument. The only thing that you need to be careful good knowledge of its contents can save you a lot of work of when you do this is that you exclude the very first element. What we need is some way to pass arguments on the command line.txt on the command line. The reason this happens is that print automatically adds a newline character to the end of each line. and a module called sys. Of course. you should now be able to adjust the code as follows: we created previously by replacing hello. and our Python re-implementation.py file. at the end of each line instead of a newline character. it’s not available to your code by default. however – there’s an empty line between each line of output. or no character. you need to use dot notation – that is to this in the Standard Library.txt file in the same directory. argv is stored within sys. They are: “The part of the sys Because operating on all The first element of the list is the name of the program module we’re interested the files passed as arguments to a program is such a itself – all arguments follow in is the argv object” common operation. you can then print(line. This is There are only two things just one line: you really need to know for file in sys. If you think access and manipulate it using various techniques we’ve back to our previous article on data types and common list seen in previous tutorials and will show in future ones.net Coding Made Simple | 67 . . however. tuple or list) or a map (like a dictionary). saving you a lot of hard work. if it’s called without any arguments. we want it to Fortunately. which displays line numbers at the beginning of lines. the same is true. let’s dive in. alternative to sys. including the standard output. which will do most of the hard work for you.py [OPTION]. seeing as we’re on a journey to are almost identical to those that we had last time. In Linux. otherwise do this with the standard input pipe is access to the sys library. Every time a actually provides us with a much more powerful alternative to sys. provided as part of the optparse module. you Parsing arguments and options will see what happens. which version: if you followed along last time. This function is built in to than specifying the name of a file. You may not have realised it. If it’s In Python. end=””) Pretty straightforward.] print(line. and -n. method for a similar purpose.. This is a special object.net Enhance your UNIX program Our tour of the Python programming language continues. we are going to add two options to our program that will modify the output generated by our program. we’re going to add [Return]). It doesn’t matter which you do. To demonstrate this. We could a pipe as an argument.org/3/library/functions. just like the real Right.] import sys else: for line in sys. In this guide...python. but cat does in fact have a range of options. and the ability to pass options to your cat clone.py --help a string in order to remove all white space – in the tutorial. by concatenating the files’ interact with the standard input pipe. we treated like files – you can want our program to work by pass a file as an argument to repeating each line entered a command.. which shows dollar symbols at the end of lines. ability to read from the standard input pipe. find at” check to see what the length of the sys. is an iterable object.. but we need to put them together into a single without further delay. you already know everything you need to work like last time – that is. [FILE]. If we call our program with arguments. All you need to get to work greater than 1. WorldMags. now we have two modes that our program can cat. it will simply wait. As well as automatically detecting options and arguments.stdin: [this month./cat. or you can pass “Python provides us with into standard input. it will then print everything that came before it to some more features to our program. The lines that follow the use of the len() function. which you can each line.argv. stdin. Rather discover different Python functions. which is found inside the sys string. we specified the Python. we used the rstrip Usage: cat. because standard input starts off empty. Let’s write a if len(sys..argv) > 1: little sample program first to demonstrate: [last month. We’re going to implement the -E.html. To do this.argv array is. 68 | Coding Made Simple WorldMags. T he previous tutorial showed you how to build a simple new line character is passed to standard input (by pressing cat clone in Python. OptionParser will automatically generate help text for your users in the event that they use your The Python language comes with all the bells and whistles you need to write program incorrectly or pass --help to it. however. all pipes are contents together. You might be wondering how this works. and can be applied to any type of sequence object (a name of the file-object. Just like a real file. we’ll start by setting up an OptionParser. In this example.. operate in. and Python that’s present straightaway. like this: useful programs. The only point of interest here is The first line imports the sys module. as we continue our clone of the Unix cat command. then do last lesson’s version. you already have. If you run the program. and it always module. you can see the replace method applied to [jon@LT04394 ~]$ . in Python the standard input pipe tells you how many elements are in that object. Rather than printing out everything This is quite a simplistic approach. program. though. so we use a for loop to walk through There are more useful functions like this.net . a much more powerful easily do this with what we have learned so far – simply because they’re basically the same thing. So. dest=”shownum”. org/3/ should be your first port of call.” a string. Let’s think about the the necessary components: -E. with everything set. as implied by pressing saw before. a new instance of the object.net Coding Made Simple | 69 . the action store_true says to set the dest a little more complicated than it ordinarily would be because variable to True if the argument is present. removing the existing new line. WorldMags. add some new options for it to The first part. Next. help=”Show $ at line endings”) Completing the job parser.. it will strip parser = OptionParser(usage=usage) those characters from the right-hand edge instead of white parser. This removes all string to display: white space characters by default. can be detect with the add_option method. The still need to write some more dest argument specifies what logic to further control the name you’ll be able to use to “Don’t confuse yourself flow of the program based on access the value of an argument once the parsing has by putting the variables what options were set. You can call by investigating the string. We say “almost complete” because we the name of your program. you can keep yourself busy arguments left over after parsing out the options. -n. and False if it is we need to maintain a cumulative count of lines that have not.parser_args() functionality in a class. In this case. In our case. action=”store_ space. which means you’ll need to know a little bit about To get started with OptionParser. but the two will always be you can figure out how you can append a number to the set in the same order.Q WorldMags.. this logic needs to be be. in the arguments that were passed to your program and assign the next tutorial we’re going to introduce you to a bit of object- results to two array variables: oriented programming in Python and implement this (options. you’ll next want to start implementing the code -E Show $ at line endings that will run when a particular option is set. option first. If you ever wonder how to do something in Python. while the action specifies what that value should the other way around!” arguments are passed.format() method and see whether these variables whatever you like. [file].. action=”store_ The second part of the job is as simple as setting the end true”.python. or shownum. args) = parser.org/3/library/optparse. important Python convention – the main() function and the such as -E or -n. option. and pass it a usage achieved by the string. -n Show line numbers we’ll be modifying the string of text that’s output by the Just like a real program! program. we’re only [Return]). You can read about other actions at been printed as the program runs to implement the second. We’ll also introduce you to a very The options variable will contain all user-defined options.add_option(“-E”. In the meantime. In both cases.add_option(“-n”. at the right-hand edge of usage = “usage: %prog [option]. http:// docs.rstrip() method. The thing is. --help show this help message and exit code written. true”.net The Python 3 website provides excellent documentation for a wealth of built-in functions and methods. you just need to parse the While there are several ways you could achieve this. All we want this to do is remove from optparse import OptionParser the invisible line break that’s at the end of every file (or every You may notice that this looks a bit different from what we line of the standard input pipe. or showend. dest=”showend”. just white space will do. Instead of importing the entire module. and replace it with a dollar symbol followed by a importing the OptionParser object. you first need to import Python’s built-in string editing functions. so don’t confuse yourself by putting the beginning of each line.. If you pass a string to it as an argument. help=”Show line numbers”) variable in the print statement to the string $\n and the job The %prog part of the usage string will be replaced with is almost complete. as well as whether or not any been done. you need to create line break. while args will contain all positional name variable.html.python. Finally. Options: variables the other way around! With the argument-parsing -h. A class is a template. We’re going to turn our cat program into an object. such as moving one finger to press a key. because it mirrors the real world so closely. One of these is the init method. of thinking because it various paradigms that provide techniques for working program. broken down into objects which contain state – variables. the contents of multiple files to the screen. number option and to gather “It’s a very natural way To make this easier. and methods. with a those variables or with that object. we specify the methods (functions) and state that we want to associate with every instance of the object. and we can describe certain methods or things you can do with your hand. here’s our cat implementation. figuring out how to ability to echo standard input to the screen and the ability to organise them so they remain easy to read. WorldMags. or holding a cup. easy to track detect and act upon options passed by the user of our which variables are being used by which functions. You probably noticed the self variable. and its methods perform the action of the cat program – redisplaying file contents to the screen. and an object is a particular instance of that class. modelled on the template. or add new for us to implement the line features. Python objects Python implements objects through a class system. can be challenging. extend.net . such as having five fingers that are in certain locations. implement the same function with some It’s a very natural way of thinking. W e’ve come quite a long way over the last two nested for loops. One of these paradigms is Objects the concept of object-oriented programming. little careful thought. Your hand is an object. We can describe a set of properties about your hand. however. however. that are frequently used. much like we define a new function: class catCommand: Inside the class. we ended by saying that there are many ways we oriented programming. and allows you to set specific variables that you want to belong to that object. there are together everything else we’ve written into a single. and wondered what on options being put to use. and easy program. and we’ll be using this to record how many lines have been displayed. def __init__(self): self. complete with state and methods that let you work with it. in We’re going to show you how to do it in an object-oriented other words – that describe the current condition of the style. In object- Last time. mirrors the real world” managing complexity. 70 | Coding Made Simple WorldMags. that allow us to perform actions on aspect of Python programming. passed as Just to prove that it works. because it gives us an excuse to introduce you to this object.count = 1 In this case. There are some special methods. with all of the the first argument to the method. having implemented the ability to echo object-oriented code. we’re going to finish our clone of cat. where its state records how many lines have been displayed. This is run when the class is first instantiated into a particular object. the When building complicated programs.net Finish up your UNIX program Our guide to the Python programming language continues. This tutorial. All that remains is to update. although they’re not nearly as readable as tutorials. We define a new class with a keyword. the elements of the program are could implement the line counting option in our program. You could. we’ve assigned 1 to the count variable. This isn’t actually – when the program is run on the command line. It might seem more natural If there weren’t any – given the description of methods as individual actions “The last thing to do is arguments. for a in args: The logic after that is clear – for each line in the current f = open(a. It lets us refer instance of a class – how we create a new object.net earth that was about.run(sys. What is new is then increment the count and print the line. reference to whichever file is being displayed at this moment.count += 1 print(line. “r”) file. is going to be a introduce you to many different aspects of the Python language.run(f. too. The completed program isn’t very long. because that hasn’t changed. use the run method attached to the same object each time We then check to see whether any arguments have been we cat a new file in the argument list. options): #set default options e = “” for line in i: #modify printed line according to options if options. The c object to variables stored within the current instance of the object. or otherwise required in Python.. [option parsing code . i. is that we if __name__ == “__ main__”: found it meant we could re-use more code. but not when we’re importing it as if len(args) > 1: a module. WorldMags. def main(): it’s not. passing in any options extracted by OptParse along the way. but many programs follow this idiom.format(self.count is a count variable that is exclusive to individual instances of the catCommand object. defined in the init method. The name variable is special going to do this by writing a main function. This is how we create an The most important part is the use of self. it is set to main. then we call the run method of the remember how many lines were displayed in the last file. This is what will enable us the current execution of the run method ends. count.] In this way. We are useful in a lot of circumstances. which will always point to the particular instance of the object that you’re working with. when it we will too: is imported as an external module to other Python programs. different method. i. the count will passed.net Coding Made Simple | 71 . and this is a when the program runs” The final thing we need fine way to approach the to do here is actually call problem. though. Well. it is the main distinguishing feature between methods and ordinary functions. now has a variable.. but quite Now all that’s left to do is to tie everything together. so as a standalone application.showend: [.stdin. which is accessible by all its Because it’s stored as part of the object. options) we suggested you research last time. must have the self variable. Q WorldMags. we simply call the run method that can be taken by our objects – to split each argument into a call the main function with sys. continue to count correctly. we can automatically execute main when run c = catCommand() as a standalone program. though.count.. however.. c. It is an automatically populated variable. using the . We previous tutorial. end=e) Notice that we’ve passed the self variable to this method. options) Either we do as last time. it will persist after methods as the self. but it has given us a chance to just like with a normal function.count variable. the main function when the program is run: The reason we’ve done it this way. line) self. So self. making it more main() readable and less error-prone.stdin instead of a file object. These last two lines are the strangest of all. If they have.last time] if options.format method that c. and modify the end character to be else: “$\n” or we modify the line. Methods.shownum: line = “{0} {1}”. The two other arguments passed to this function are arguments that we’ll pass when we call the method later on. modify the line depending on what options have been set. As long as we to track the line numbers. and object c for each file that was passed as an argument. We’ve called this the run method: def run(self. the c = catCommand() line. even those which have no other arguments. to append the count We haven’t filled in the object parsing code from the variable. The first. while the options variable is a reference to the options decoded by the OptParse module. to the rest of the line. The run method We next need to write a method that will execute the appropriate logic depending on whether certain options are set. co.net . tablet & computer Be more efficient and increase your productivity Helping you live better & work smarter LIFEHACKER UK IS THE EXPERT GUIDE FOR ANYONE LOOKING TO GET THINGS DONE Thousands of tips to improve your home & workplace Get more from your smartphone. WorldMags.com/lifehackeruk WorldMags.com/lifehackeruk facebook.uk twitter.lifehacker. com WorldMags. anytime.T3. WorldMags. now optimised for any screen.net .COM NOW LIVE Showcasing the very best gadget news.net THE GADGET WEBSITE INTRODUCING THE ALL-NEW T3. anywhere. www. reviews and features. import fact print fact. as two different result *= n parts of your program require functions called add (for n -= 1 example. Inside this. but – in Python at least – they’re really just plain which parts rely on each other to get work done – and it’s old files. this is a tool you’re no doubt desperate for. and we’ve them by typing the module’s name. in part because you don’t start to come across it clone. and the only tool you have to do that is boring factorial function. In our cat yet to cover. followed by the name of introduced you to quite a few of the tools and techniques the function we wanted to execute: that help programmers do this. the code that dealt with the logic of echoing file contents to Yet. or you may have written a useful Create a second Python file called doMath. as you’ve relied on Python built-in or third-party modules to provide lots of extra functionality. We could access programming is all about managing complexity. there are other your program. the location of which are defined when 74 | Coding Made Simple WorldMags. The big question that’s left is. and reusing this code was as easy as typing of the latest error. we specified in your import statements. becomes more difficult to read.OptionParser() definitions or object-orientation. didn’t have to worry about using names in our own program In a long file of code. You should notice that the name of enabling you to put structure back into your code. It first looks inside all of magically got access to a whole load of other functions that the built-in modules. too.py file. if you’ve written a program of any length. followed by the function name. printing the result to the screen: and error-prone copy and pasting. You can try it out for yourself. remember The Python path the optparse module we used before. when you run the doMath. adding integers or adding fractions in a return n mathematics program). and when you’re trying to hunt down the cause namespace. instead we could focus on and name spaces. where you defined that all-important variable. define a function to visualise the flow return the factorial of a given number: “As your programs grow of data through def factorial(n): in length. With all How modules work your code in a single file. we didn’t have to wade through lots of code about until you’re writing larger programs. we few hundred lines. it’s more difficult to determine the Modules sound fancy. you should see Modules are a great way to solve all of these problems. 120 printed on the screen. we have mentioned how automatically parsed command line options. and you might think they’re dependencies between elements of your program – that is.factorial(5) Untangling the mess Now. in the same directory. From variables to function optparse. even just a the screen and to the standard output pipe. Functions seem to blur into because they were all hidden inside the optparse one another. avoid naming conflicts. and making it easier for you to share with the extension removed. complicated. As an example.py file. you’ll have noticed how quickly it that might collide with those in the optparse module. how does Python know where We included it in our program along with the import to look to find your modules? statement. Create a new directory more difficult to and inside it create a fact. I n previous tutorials. WorldMags.net Neater code with modules Untangle the horrible mess of code that you’ve made and add coherent structure to your programs. defined in that module by typing the module’s name. These problems are caused by a lack of structure. function that you want to share with other programs that first import the module you just created and then execute the you’re writing. What’s more. As your result = 1 while n > 0: problems that occur” programs grow in length.py. followed You’ve no doubt been using them all the time in your code by a dot. letting you the module is just the name of the file. if n == 1: result *= 1 there are other problems that begin to occur: for instance. One tool we’ve This was great from a readability perspective. else: you may find yourself with naming conflicts. Inside it. We can then call any function useful chunks of code between programs. they all help. you find it difficult to remember exactly import optparse – no messy copy and pasting here. is the idea of modules parsing command line arguments.net . like so: The answer is that Python has a pre-defined set of import optparse locations that it looks in to find files that match the name After putting this line at the top of our Python program. because each module has its own We have touched upon scope as a concept before. This demonstrates two The PYTHONPATH. Variable scope in modules In simple. which is a set of directories pre. WorldMags.org/dev/peps/ use it often have learned a lot about the If you’re interested in finding out more pep-0008 best ways to do things in the language – about these best practices in Python.net Coding Made Simple | 75 . its a quick refresher.python. in how show_choc() the contents of the Python path are generated. you install Python. it then searches through a list of print food directories known as the path. Python starts with the attribute (typing sys. a accessed via dot notation. in which food refers to a list of chocolate. when we import a module. starting with the Once a program has started. def show_choc(): This path is much like the Bash shell’s $PATH food = [“snickers”. Using modules can about: variable scope. and then finally it will look at all the built-in names. Read these and you’re sure to gain in terms of the easiest way to solve there are two very useful resources from some deeper insight into the language. it is a bad idea to put Before you head off and start merrily writing your own variables in the global scope. and then the module’s global scope. which particular variables can be accessed. it refers to a list of chocolate bars. there is one more thing that you need to know subtle errors elsewhere in your program. importing the sys module. This makes global variables single Python module might contain the following code: somewhat less troublesome.net/~goodger/ around since the early 1990s. it’s actually been format your code to make sure it’s. however. It can cause confusion and modules. it can even modify the path immediately enclosing function. As with any readable for co-workers and anyone else projects/pycon/2007/idiomatic/ programming language that’s been working on the code with you (including handout. “kitkat”. As we saw above. and the best ways to which you can start learning: a modern language. and then inspecting the path When looking up a variable. and serves print food exactly the same function. different scopes: the global scope of the current module. in defined in your default installation. and the local scope of the You can inspect the path in your Python environment by function.path will do the trick). single-file programs. It varies. and then any functions itself and add other locations to it. “dairy milk”] environment variable – it uses the same syntax. although you should still be food = [“apples”. Q Python style While many people think of Python as common problems. “pears”] careful when using them. “oranges”. you can bring order to your projects and make future maintenance easier. For instance.html around for any length of time. but as global scope. people who your future self).net By splitting your code up in to smaller chunks. while inside the function. WorldMags. print food the locations stored in the path consist of the following If you run that. you’ll see that outside the function the two locations: variable food refers to a list of fruit. scope refers to the part of a program from contents are all stored as attributes of the module’s name. Initially. each placed in its own file and directory. help with this problem. which food refers to a list of fruit. innermost variable and works its way out. The directory containing the script doing the importing. enclosing that. www. You still perhaps using a web form and CGI). file) the write method: … for feed in feeds: with open(“lxf-test.tuxradar.uk/rss/newsonline_uk_ . Support for it is The second is that you have to close the file after you have included in the standard library. matter) into a string first of all – for dictionaries in particular.net . or wherever you of file objects.xml”..dump(feeds. Just use pickle. Fortunately. though. or convert them to a character string and back again..load(file) 76 | Coding Made Simple WorldMags. however.com/rss”] with open(“lxf-test. and to bring a modicum of functional style into and append (a). automatically closes it for us. Python provides two tools Writing to files to make this easier for us. It’s no surprise. otherwise we would smartphones come with at least 8GB of storage. to use the function: with keyword: file = open(“lxf. but you no longer store that list of feeds on disk so you can re-use it later when have to worry about figuring out an appropriate string you’re checking for new updates. you thought had been committed to disk. application stores data in one way or another. there are two things With this in mind. while even add a new line to the end of each string. str(42) => “42”. the feeds representation for your data: are just stored in a Python list: import pickle feeds = [“. use the open() file. When using files in your Python code.close() to our program. as well. of choice – Python. saved figure this one out. we’ve shown you that this file object is in fact an iterator. edition/front_page/rss. and you don’t even have to finished using it – if you don’t do this. Working with files would be much easier if you didn’t have to one line at a time. case. this could get messy. WorldMags. It’s better. “a”) as file: To get the feeds into the file is a simple process. cached data to speed up future use. then. In our example. however. load each line in turn into a list. because you can just use the built-in The most obvious form of persistent storage that you can str() function – for example. You’ve already got some way to ask accepts many different kinds of Python objects. If you are unsure what the second line does. S torage is cheap: you can buy a 500GB external hard Easy! Notice how we used the format string function to drive for less than £40 these days.rstrip(“\n”) for line in f] application stores data The first argument to open This simple piece of Python code handles opening the file object and. You can do this manually with the close method wherever you ran the Python script from. This is easy. Suppose you’re writing your own RSS application to deal with The first of these tools is the pickle module.txt”. to-do lists or photos. and can then users to enter in a list of feeds (perhaps using raw_input(). that almost every modern Using the file as an iterator. Before reviewing that information. but now you want to have to do the file opening and closing. been flushed. worry about converting your list (or dictionary. Pickle your favourite feeds. The first is that you need to demonstrate how to deal with persistent data in our language convert whatever you want to write to the file to a string first. At the moment. your work. whether that’s stripping off the trailing new line character. We’ll leave you to configuration data. but that had not yet To open a file in the current working directory (that is.format(feed)) feeds = pickle. take advantage of in Python is file storage.txt”. try looking up Python list specifies which mode the file should be opened in – in this comprehensions – they’re a great way to write efficient. pair of jeans. and end up with everything on one line – which would have made many are easily expandable up to 64GB for only the price of a it harder to use later. this programming tutorial is going to that you need to keep in mind. “w”) feeds = [line. for that let’s look at how to write data to a file. “r”) as file: file.net Embrace storage and persistence Deal with persistent data and store your files in Python to make your programs more permanent and less transient. with open(“lxf-test.co. Re-using the contents of this file would be just as simple. you risk losing data that import any modules to take advantage of it. The list goes on and on.txt”.write(“{0}\n”. In previous tutorials. games. “. this would translate to adding were when you launched the interactive shell). it’s write. but other valid options include read-only (r) concise code. “a”) as file: “Almost every modern test. while the second finished. which means you can use the in keyword Serialising to loop through each line in the file and deal with its contents.txt”. when the block inside the with statement is in one way or another” is the filename. If you like the concept of pickling (more generically. you use it in exactly the same way as pickle – in The shelve module has its own operations for opening and the above example. a shelf is a persistent dictionary – that is to stored in the shelf. you assign a underneath. a persistent way to store key-value pairs.uk”: { “last-read”: “bar”. object that pickle can serialise.org).co. You might do this with a transfer your feed list across the network.0 applications. so you can’t use the standard open function. The problem with this is that it will only work in Python – “tuxradar. a good next stopping point is the ZODB object database. however. too: JSON. of about the shelve module: In Python. details for each in a single file by using the shelve module. serialised code! To save some data to the shelf. too. Let’s take a look at how you That’s about all we have space for this tutorial. Rather than another Python standard module. you wanted data: relational databases (for example. but makes access to the stored objects more value to that stored in the dictionary at a particular key: feeds intuitive and convenient: the shelve module. and it has other applications outside to keep track of how many unread items each feed had. then re-assign that temporary value back to about shelves. and of persisting data in files. }} the pickle data format. It’s great. that uses pickle assigning a key in the shelf dictionary to a value.zodb. do with pickle. shelf. If you want to modify the data that was Essentially. but keep can use it.net If you’re interested in persistent data in Python. some code bases have many different objects that As with files.open(“lxf-test”) identical to objects found in the JavaScript programming shelf[“feeds”] = feeds language. Of course.co. Q WorldMags. because we’ll discuss one final option for persistent imagine that as well as the list of feeds to check. you must first use a standard Python assignment operation to set the value of a Shelves particular key to the object you want to save. = shelf[“feeds”].net Coding Made Simple | 77 . There’s Accessing data inside the shelf is just as easy. there’s another option that You could then store the list of feeds and the tracking does have support in other languages. that is to say. “num-unread”: 10. is that the value can be any Python the shelf before closing it again. and keeping with. if you wanted to which item was the last to be read. Thinking back to our RSS reader application. modify it in the temporary value you say. for example: have to make it into a character string. }. track of many different pickled files can get tricky. reading. and is a way of converting objects into import shelve human-readable string representations. This is much easier. MySQL). other programming languages don’t support “num-unread”: 5.close() largely because it has become so popular with fancy web There are a few important things that you should be aware 2. which you could tracker = { “bbc. you’ll be writing interoperable. It’s much easier and more natural in Python than a relational database engine (www. you must close the shelf object once finished you want to store persistently between runs. replace pickle with json throughout. and closing files. because it’s human readable. The great thing assigned it to. and also shelf[“tracker”] = tracker because it’s widely supported in many different languages. serialising). you would first dictionary.uk”: { “last-read”: “foo”. You may have heard of JSON – it stands for JavaScript like so: Object Notation. otherwise your changes may not be stored. which look almost shelf = shelve. WorldMags. For example. however. too. the album title and year published). Artist_id 1 As relational databases are by far the most common tool for asking complex questions about data today. a unique name for an artist. but very wasteful. With the basics all the information about the artist. other information. useful form. Here. we’ve simply Album time 65:58 65:58 specified the unique ID for a row in another table. even. probably Year 1972 1972 called Artist. you’ll be able to start integrating relational and the year they split. or as you try to express more complicated ideas and Running time 65:58 relationships. its running time. or a unique title for an album).net Data organisation and queries Let’s use SQL and a relational database to add some structure to our extensive 70s rock collection. and each album can be described by lots of ‘relational’ part of a relational database comes in. Relational databases solve these problems by letting us are used to ask complex along. The techniques we looked at were flat-file based. We can then add an extra column to each table that Artist Free Free references the primary key in another table. When we want to present this album to a user. harder to “Relational databases your code. For every track on the same tutorial we’re going to introduce you to the basics of relational album. of its drop-in In our example. Relationships All that duplication is gone. As well as being wasteful with storage databases into space. To follow interpret and more dangerous to modify later. as performance becomes more important. Each CD is produced it and the album it appeared on? That’s where the a single album. or Structured Query Language). A logical place to start might be information about a single track. These unique columns form what is known as a primary key. too. We would then to the MySQL console: only need to have a single entry for the artist Free (storing the mysql -uroot name and the year the band split). what happens when you want to report all the in our music collection.net . or homogeneous table – like the one below – which is all well a combination of columns (for example. right? I n the last tutorial. we might split information about the replacements installed. and as useful as they are. or attributes. such as the databases and the language used to work with them (which is album name. in this coding and good. Where a natural primary key (a natural set Duplicated data of unique columns) doesn’t exist within a table. Year 1972 such as an object database or. but now all the data has been Let’s start by thinking about the information we want to store separated. including the artist who Every row within a database table must in some way be created the album and the tracks that are on it. unique. Track Little Bit of Love Travellin’ Man consider the table above. track in the database (storing everything else) in each of their respective tables. either based on a single unique column (for example. use the -p switch to give that as album Free At Last (storing its name. Throughout. the year it was well as the username. make sure you have got split the data and store it in a more efficient. As your applications grow Album name Free At Last more ambitious. and a single entry for each database to track our music collection. For example. You do have one. They let us identify separate entities within the database that questions about data” MySQL or one would benefit from being stored in independent tables. a relational database. in Band split 1973 1973 conjunction with information about the artist who published 78 | Coding Made Simple WorldMags. Relational database they’re not exactly industrial scale. including the artist who thinking about it in terms of the CDs that we own. WorldMags. such as their name mastered. we’ll be working on a small published and the running time). you can easily add an artificial one in the form of an automatically Album Free At Last Free At Last incrementing integer ID. a single entry for the If you’ve set a password. you’ll need to look towards other technologies. artist and track into separate tables. and called SQL. this also makes the data slower to search. rather than giving all the Track time 2:34 3:23 information about the artist in the same table. the year it was published. and can also find a way to get access album. we looked at how to make data persistent in your Python programs. we have to duplicate all the information. We could represent all this data in one large. To create these tables within the database. then retrieve the information about the artist. and that it would have taken just that column. You’ll also want to investigate the different types of whether it is part of the primary key. the type of object that we’re operating on and then you must always specify a data type for your columns. Now you’ve seen the basics. you use create database: create database lxfmusic. otherwise we won’t be able to link the tables together Track_id int auto_increment primary key. you’ll want we give the column a name. so many separated by commas. Pretty self-explanatory really! If we’d only wanted to get the ID The most obvious things to note here are that we have field. separated by semi-colons. we can show you how to use SQL to create and use your own. The database is the top-level storage container for bits of related information. eventualities are covered. look out for an appropriate incremented for every row in the database. Splitting information into manageable. such as one-to-one. First. select * from Album where name = “Free At Last”. That said. Q WorldMags. notice how similar it is to the The big thing to note is that we specified the running time create database statement. we then specify the columns which we’re name varchar(100) inserting into. education stop there. You can find out more about the create table Much as you work within a current working directory on the statement in the MySQL documentation at. many-to-one The auto_increment keyword means you don’t have to and many-to-many. This command says we want to select all columns from Album_id int the Album table whose name field is equal to Free At Last. Album_id) values the correct places. then we describe the type of data to investigate foreign keys and joins.html. the first thing we need to do is create a database. such as the python-mysql module for Python. as long as you put the right punctuation in insert into Track (title. We specify the action we want in seconds and stored it as an integer. SQL That. primary key.5/en/create-table. 1). and the properties of that object. thus forming a module. ). we’re acting. we specify the action and the object on which Album_id int auto_increment primary key. as MySQL will ensure that this is an integer that gets programming language of choice. running_time. With most databases. in a nutshell. and describing the relationships between those chunks. and you can issue your commands in whatever case you like. As for the command itself. WorldMags. To do this. and now that you know what a table and a relationship is. OpenSUSE and even Slackware. To do this. many commands you issue are mysql. most relational databases make use of SQL. but don’t let your MySQL separated entry describes one column in the database. Inserting data into the newly created tables isn’t any trickier: Now to create some tables: insert into Album (name) values (“Free at Last”). SQL doesn’t Since that returned a 1 for us (it being the first entry in the care about white space.net Coding Made Simple | 79 . and you will with the create table statement. That’s all we have space for here. With the database created. we must discover what the ID of the album Free At create table Track ( Last is. to insert and query data. (‘Little Bit of Love’. if you want to integrate MySQL with your data. of extra properties that come inside the parentheses and are MySQL does have a wide range of data types. however. Linux console. then we techniques that will enable you to be far more expressive with specify any additional properties of that column. in a different manner than in your application. 154. relationship. combining it for presentation. You can switch databases with the use command: Inserts and queries use lxfmusic. one-to-many. is what relational databases are all about. Before we can insert an entry into the Track table. two more advanced stored in it (this is necessary in most databases). we can get the information first from this Album table. reusable chunks of data. we use the select statement: title varchar(100). we’ve used lower-case letters: SQL is not case-sensitive. worry about specifying the value of Track_id when inserting Finally. from the Artist table. to manage the relationships. to take.com/doc/refman/5. we have split each command over multiple lines.net it. relative to the currently selected database. we’ve also got a whole load need to write some code to convert it for display. With the create database sometimes this means that you need to represent your data statement. whose ID is 1. such as your SQL. so we need to create it before we can start storing or querying anything else. so you can split your code up database). the only property was the name of the database. we can insert into the Track table as follows: however you like. ). you now need to switch to it. and is quickly finding favour among distros including Mageia. and finally the values of the data to be put in. create table Album ( Once again. and each comma. very easily. running_time int. in MySQL. These are known as column definitions. After logging into the MySQL console. we could have replaced the asterisk with Album_id and issued two commands. Notice the semi-colon at the end of the command – all SQL statements must end with a semi-colon. Also notice that MariaDB is a drop-in replacement for the MySQL database. WorldMags.net WorldMags.net . ........................................................ Starting Scratch 84 ............................................................................ 114 WorldMags.............................................................................. Python 3.....net Coding Made Simple | 81 .....................WorldMags........net Raspberry Pi Discover how you can develop on the low-cost......................... 108 Image walls in Minecraft ......................................................................................... Advanced sorting .................. 110 2048 in Minecraft ........................ micro-PC system Getting started 82 .................. Coding with IDLE 92 ....................0 on the Pi 98 .............................................................. Further Scratch 88 ................. Python on the Pi 94 .............. 102 Hacking Minecraft ........................... Bear in mind that the Pi (particularly non. The Software bottleneck is mostly application. there’s a special edition of Minecraft. T he Pi-tailored Raspbian desktop environment free to peruse that to learn about commands such as ls . 82 | Coding Made Simple WorldMags. Raspbian may appear Terminal velocity somewhat spartan. Windows 10. It’s possible to do this from – you may want to make a cup of tea. Compared to. which applies equally well here. tutorial (see page 16). That updates Raspbian’s local list of all available packages. handles all of the consultations with Raspbian mirrors and but there’s also Wolfram Mathematica (for doing hard sums). which install. so lightweight is the order of the day. Open LXTerminal from and image viewers. and thanks to graphical hardware are available. you’ll get important security anything from the command line. it can even play HTML5 YouTube videos. updates and the latest features or fixes for all your software. so feel The syntax is clean and concise. it’s possible to do pretty much packages pretty regularly. It system is checked against this. You should update your the command line too. the list of current packages installed on the desktop computer. Most importantly. these are offered for upgrade: acceleration. such as this one featuring a tiny arcade cabinet. as well as PDF dependencies with a minimum of fuss. say. which you can trust. there are no awkward The new Epiphany browser works well. It’s a good idea to keep the software on your Pi an even friendlier place to learn. Sonic command: Pi (the live coding synth). too – there’s Scratch (the visual coding language). making it and mkdir . This downloads packages from Raspbian’s due to the speed at which data can be written to the SD card repositories. In Pi 2 models) is considerably less powerful than your average the next step.net . not to mention the Python $ sudo apt-get update programming language. Software is your average desktop computer. either the menu or the launch bar. WorldMags. cd received a thorough overhaul in late 2015. There’s a very brief introduction to the terminal in the Mint Python is a particularly good first programming language.net Welcome to Pi Reveal the Raspbian desktop and partake of the pleasures of Python programming on the Raspberry Pi. play or work. The up to date. the managed from but remains no less functional. of packages to upgrade. In fact. so let’s see how that works from the terminal. it $ sudo apt-get can play high- definition video “The Pi is far less powerful than upgrade If there’s lots without batting an eyelid. and where newer packages remains no less functional. and enter the following wise. We’re amply catered for programming.” process may take the Add/Remove some time. Raspbian team has squeezed a great deal into the 3.5GB We’re going to use the apt-get package manager. does a remarkable job of (un)installing packages and their LibreOffice and the Epiphany web browser. you’ll run into something that print(‘Hello World’) requires Python 2. Python 3 (see page 94 and 120) has our Python programs. than others. to date. Fortune has it that by turning to the scenarios but you can also play with the Finally. Open up a terminal. there’s a for which the Raspberry Pi is well suited. and then navigate to the version of Python provided by Raspbian – 3.py tutorial (see page 16). if you haven’t already done so. cameras or LEDs. so finally the shift to 3 is Now type the following into your chosen editor gaining traction. but people have been slow to adopt. but it’s a fully working do here. Some wireless adapters work better with the Pi practice. Sooner or later. and turn your cat as its mascot. but for this tutorial we’re going to stick with the new editor. Scratch (see page 84) is a great way very next page.net Coding Made Simple | 83 . The Raspbian desktop WorldMags. You’ll also find links to help resources and. To start with.py. you’ll appreciate how efficient it is. you have a choice: you can proceed as in the Mint A tale of two Pythons tutorial and use the nano text editor. or even been shared on its website at. Keeping on top of your filing is A Good been around since 2008. by hitting Ctrl+D. Launch bar Frequently used applications can be added here – just right- click it and select Application Launch Bar Settings. Assuming you’re using the graphical things.5 million projects have University of Kent and Oracle). Many of the larger projects that used to only work on the old $ mkdir ~/python version have been ported to the new. use Ctrl+X to save and exit. Q Other programming tools We’ve only covered Python in this tutorial Then there’s also Node-RED. So we’ll now leave the interpreter about anything. For example. you will find an entire tutorial underlying Java source (if you’re feeling brave). Plus it has an orange full-blown Java IDE called Greenfoot (which to add sensors. in the Preferences menu. start the Python 3 interpreter by entering: Now we can run this and see what we have created: $ python3 $ cd ~/python Once again.4. It’s easy represent events and logic. we’ll create a directory for storing last few years.7. you could do the following: programming adventures. so it’s worth doing some research before you buy. too. Before you reflects a duality that has formed in Pythonic circles over the make that choice. and then you might have to unlearn some and then save the file. Ultimately.edu. and save it as helloworld. with connections. Thing. semicolons to terminate statements. It can watch and. to get kids (or grown-up kids) into coding. some 12. It opens at your home folder and is also capable of Terminal Network browsing Windows and other The command line gives direct access to the From here you can configure your wired and wireless network network shares. recently created Python folder. it makes more sense to save huge number of modules that enable you to achieve just your programs in text files. The black screen icon in the centre opens the terminal. At this point. operating system. the basics of open-source design using visual water your plants. monitor the weather. some tools for adjusting system settings. if you wanted to find out how many program and something you can build around in further seconds there are in a year. File manager The PCManFM file manager is lightweight but thoroughly capable. created by dragging and connecting blocks that available in Raspbian. File > Save As. Scratch was developed at MIT has been developed in partnership with the Pi into a bona fide smart device. choose.net Menu Here you’ll find all the great programs mentioned earlier – and more. for designing visual language. This teaches your letterbox. It’s a devoted to the language. which means that programs are but there are other programming languages applications based around the Internet of Things. mit. if you have a look at the introductory Mint $ python3 helloworld. lots of shortcuts for >>> 60 * 60 * 24 * 365 things that are cumbersome in other languages and there’s a As mentioned elsewhere. This graphical one located in the Accessories menu. you’ll learn about a few things you can It’s not going to win any awards. and make our first Pi Python program. and If you’re using nano. It can be daunting but. though. WorldMags. or you can use the Raspbian comes with two versions of Python installed. It’s a great beginner’s language. although Scratch can be downloaded from. Without further ado. or images. Each program is made up of a number of sprites (pictures) that contain a number of scripts. The main window is split up into sections. Costumes tab to create new ones or manage existing ones. and the little learning computer is our focus in this series of articles. or if you’re new to graphical programming. WorldMags. It’s best to use Raspbian rather than one of the other distros for the Pi for this. Broadly speaking. It’s these scripts that control what happens when the program is running. because not many of the others support Scratch. Each sprite can have a number of costumes. Click on the Click on ‘New Sprite From File’. let’s get started. so there’s no need to install anything – just click on the icon to get started. You’ll find Scratch on the desktop in core Raspberry Pi operating system Raspbian. If you’ve never programmed before.edu whether you’re using Windows. In the top-left corner. you’ll see eight words: Motion.net . Operations and Variables. or ‘Costumes > Import’ to see them. These tutorials will be equally applicable whatever your platform. while you make your programs in the middle. Pen. Good luck! Scratch comes with a range of images that you can use for sprites. Looks. Sensing. we’ll ease you gently in.net Starting Scratch Discover how to build a cat and mouse game using this straightforward beginner’s programming language. 84 | Coding Made Simple WorldMags. the bits you can use to make your programs are on the left. It’s especially good for creating graphical programs such as games. because it introduces many of the concepts of programming while at the same time being easy to use. Control. ou can use a wide range of programming languages Y with the Raspberry Pi. Sound. Each of these is a category that contains pieces that you can drag and drop into the scripts area to build programs. mit. Mac or Linux. and the programs run on the right. and hopefully have a little fun along the way. you’re going to want to get your different types of data. could also put text in them. and for a script programming languages. Then reduce the sprite size by clicking on When r Key Pressed. It might be worry about that in Scratch. the ‘Shrink sprite’ icon (circled) and then the mouse. Go To X:100. Y:100 (from ‘Motion’. Note that in some so they have to be created first. These can be used to trigger this using variables. If you drop it the size of our thumbnail. or anything. don’t forget to change 0s as score. You can do Once you have created a variable.net Variables and messages Sooner or later. or you can output them. but you don’t need to to communicate between them. you can then use messages. then you can use them to one script broadcasts a message. Set Score To 0 and Set Over to 0 (both from ‘Variables’). although we 11). Click on ‘Make A Variable’ and enter the variable name ‘Looks’). We set it to about Then drag Move 10 Steps off the bottom of the script. it will be deleted. Receive … Like variables. Repeat the process to create a variable called over. We’ll use this to start a new game (r is for reset). WorldMags. Step by step 1 Create the mouse 2 Set keys Change the image from a cat to a mouse by going to ‘Costumes > Click on ‘Scripts’. you have to create Messages to trigger it has to be linked to the same message different types of variables if you want to store If you create a number of scripts. back in the left side. you have to set them scripts in the same way as keypresses can. messages have names. to 100s). In step 3. Firstly. add the lines show (from what they are). Sometimes you program to remember something. you may need as the broadcast. When computer’s memory that your program can to be a particular value. a piece of text. and change When Right Arrow Key Pressed to Import > Animals > Mouse 1’. WorldMags. it will then place pieces of data in. can do this with variables.net Coding Made Simple | 85 . we create a pair evaluate conditions (which we’ll do in steps 6 and trigger all the scripts that start with When I of these to store some numbers in. but it is often better to a number. 3 Create and name variable 4 Reset the score Click on ‘Variables’ in the top-left (see boxout above for more details on Under the script When r Key Presses. These are little pieces of the use it in a few ways. WorldMags.net 5 Add broadcast 6 Create a loop Add the block Broadcast … to the bottom of the When r Key Pressed We can create loops that cycle through the same code many times. script. Once it’s there, click on the drop-down menu and select ‘New..’. Continue the script with Repeat Until … (from ‘Control’), and then and give the message the name start. We’ll use this to let the other drag and drop … = … (from ‘Operators’), then drag Over (from sprite know that the game has started. ‘Variables’) into the left-hand side of the = and enter 1 on the right. 7 Add to your loop 8 Hide the mouse Inside the Repeat Until Over = 1 block, add Change score By 1 (from Once the game has finished (and the cat has got the mouse), the ‘Variables’), Move 7 Steps (from ‘Motion’) and If On Edge, Bounce Repeat Until loop will end and the program will continue underneath (also from ‘Motion’). These three pieces of code will be constantly it. Drag Hide (from ‘Looks’) under the loop, so the mouse disappears repeated until the variable over gets set to 1. when this happens. 9 Resize your cat 10 Move the cat Select ‘Choose New Sprite From File > Cat 4’, and shrink the sprite In the scripts for the new sprite, start a new script with When I Receive down to an appropriate size, as we did with the mouse. Each sprite has start (from ‘Control’), and Go To X:-100 Y:-100. This will move the cat its own set of scripts. You can swap between them by clicking on the over to the opposite corner of the screen from the mouse. (0,0) is the appropriate icon in the bottom-right. middle. 86 | Coding Made Simple WorldMags.net WorldMags.net 11 Give the cat a loop 12 Set the difficulty As with the mouse, the cat also needs a loop to keep things going. Add Inside the Repeat Until block, add Point Towards Sprite 1 (from Repeat Until (from ‘Control’), and then in the blank space add ‘Motion’) and Move 4 Steps (also from ‘Motion’). The amount the cat Touching Sprite 1 (from ‘Sensing’). This will keep running until the cat and mouse move in each loop affects the difficulty of the game. We (sprite 2) catches the mouse (sprite 1). found 4 and 7, respectively, to work well. 13 Finish the loop 14 Tell the player the game is over The loop will finish when the cat has caught the mouse – the game is We now want to let the player know that the game is over. We will over, so we need to stop the script on Sprite 1. We do this by adding do this in two ways: with audio, and on screen. Add Play Drum 1 Set over To 1 (from ‘Variables’) underneath the Repeat Until block. for 1 Beats (from ‘Sound’), then Say Mmmm Tasty For 1 Secs This will cause Sprite 1’s main loop to finish. (from ‘Looks’). 15 Display a score 16 Play your game! Finally, we can let the player know their score. We increased the Press [r] and play! You can use the up and down arrows to move the variable score by one every loop, so this will have continued to go up. mouse around. You can make it easier or more difficult by changing Add Say You Scored … For 1 Secs, then drag another Say … for 1 the size of the sprites and the amount they move each loop. Good luck Secs block and then drag score (from ‘Variables’) into the blank field. and happy gaming!Q WorldMags.net Coding Made Simple | 87 WorldMags.net Further Scratch We’ve dived in, but let’s now look at the fundamentals of Scratch to understand how our programs work and set up a straightforward quiz. H ow did you learn to program? Typically, we think of a person sitting in front of a glowing screen, fingers Fig 1.0 The logic for slowly typing in magic words that, initially, mean our logo sprite. nothing to the typist. And in the early days of coding, that was the typical scene, with enthusiasts learning by rote, typing in reams of code printed in magazines. In this modern era, when children are now encouraged to learn coding concepts as part of their primary school education, we see new tools being used to introduce coding to a younger generation, and the most popular tool is the subject of this very tutorial. Scratch, created by MIT, is a visual programming Fig 1.2 This is the code environment that promotes the use of coloured blocks over that clears effects. chunks of code. Each set of blocks provides different functionality and introduces the concepts of coding in a to version 2. gentle and fun way. Children as young as six are able to use As mentioned, Scratch uses a block-based system to Scratch, and it’s now being heavily used in the UK as part of teach users how different functions work in a program. This the curriculum for Key Stages 1 to 3 (6 to 14 years old), and can be broken down into the following groups and colours: as part of the Code Club scheme of work. Motion (dark blue) This enables you to move and control Scratch uses a For the purpose of this tutorial, we are using the current sprites in your game. three-column UI. stable version of Scratch, which at the time of writing is 1.4. Control (orange) These blocks contain the logic to control From left to right: Version 2 of Scratch is available as a beta and reports suggest your program (loops and statements) and the events needed Block Palette, that it’s very stable to use, but there’s a number of differences to trigger actions, such as pressing a key. In Scratch 2.0, the Script Area and between the locations of blocks when comparing version 1.4 events stored in Control have their own group, which is called, The Stage. naturally enough, Events. Looks (purple) These blocks can alter the colour, size or costume of a sprite, and introduce interactive elements, such as speech bubbles. Sensing (light blue) For sensing handles, the general input needed for your program, for example, keystrokes, sprite collision detection and the position of a sprite on the screen. Sound (light purple) Adds both music and sound effects to your program. Operators (green) This enables you to use mathematical logic in your program, such as Booleans, conditionals and random numbers. Pen (dark green) This is for drawing on the screen in much the same way that logo or turtle enable you to do so. Variables (dark orange) Creates and manipulates containers that can store data in your program. By breaking the language down into colour-coded blocks Scratch enables anyone to quickly identify the block they Scratch online Scratch is available across many platforms. It with the same interface and blocks of code, but version of Scratch from the website. This very comes pre-loaded on every Raspberry Pi running with a few subtle differences. This is the latest latest version is still in beta but reports show that Raspbian and is available for download from version of Scratch and you can save all of your it is very stable and ready for use. Scratch 2.0. But did you know that work in the cloud ready to be used on any PC you uses Adobe Air and is available across all there is an online version that provides all of the come across. If you wish to use the code built platforms including Linux. Adobe dropped its functionality present in the desktop version, but online on a PC that does not have an internet support for Air on Linux a few years ago but you requires no installation or download? Head over connection, you can download your project and can still download the packages necessary for to the MIT website (above) and you’ll be greeted run it offline. You can also download the latest Scratch 2.0 to work. 88 | Coding Made Simple WorldMags.net An event is typically clicking on the green script associated to the stage sends a broadcast called is a quick way to flag to start the game but it can be as complex as listening for player_name. What this does is triggers belong to your particular program. which is handled via the code For this tutorial. using the Answer variable. The purpose of the We’ve broken Matt’s main loop into three parts. so let’s look at what they each do. two quiz masters. the start of the game. Once the user enters their name. Fig 1. there’s a section of code associated with Quick answer the question correctly to progress to the next round. So we have a number of actions to perform once we receive these broadcasts from Neil and the stage. can drag our blocks of code Let’s move on to Neil. the code associated with else. Double in size. it’s game over. Children typically work answered a question correctly. world. we move on is Sprite8. Neil will say your code. Neil’s code is waiting to receive this broadcast duplicate or delete a trigger from another sprite. which is basically a way to chain trigger events between sprites in the program (you can find ‘broadcast’ under ‘Control’). Matt has five sections of code that react to something called a ‘broadcast’.net need. which is repeat until answer = ubuntu. Fig 1. This large loop is triggered once we background that we want to use in our program. (see left) shows the code that Fig 1. We wanted this logo to appear right at given. Neil’s code inside support Neil sends a broadcast to Matt once the player has the main loop.1 The code used Script area In the second clears any special effects used for Matt to receive column is an area where you on his sprite. We’ve given our four game sprites names: Neil is Sprite6. broadcasts. statement which uses a condition to perform a certain Hide.5. It then stores that tip you receive three wrong answers in the game.0. or if it is false it will run Wait for 2 seconds. receive the name of the player. game_over Neil sends Matt Fig 1. This is because he’s the your programming and can be used to interact with the game main part of our game. sequence of code if a condition is true. In the case of the answer being Show. Once the code is triggered. Clicking on a sprite will Neil’s sprite to reset any special change the focus to that sprite. via the colour-coding system at insult Neil sends a broadcast to first. which is for each of these broadcasts divided into three columns.5 The second loop of has entered their name. WorldMags. Now let’s look at the logic for Matt’s sprite. we need to move blocks of ‘code’ The second part is the loop from the block palette to the script area for each sprite or that controls our game. This shows the sprites and assets that event. sprite has a lot more code than The stage The third and final column shows the results of Matt. and you must start of the game. Loop 10 times and each time reduce size by 15% You can see this as Scratch presents it visually in Fig 1. The environment the game. WorldMags. Matt is triggered to run a certain The first column is: sequence of code. there’s the Green Flag handy Sprites pane. we are going to make a quiz game. hello to the player by their name.net Coding Made Simple | 89 . question in a loop that will repeat until the correct answer is starting with the logo. Matt also has Block palette This is where a script that’s run in the event of our blocks of code are stored clicking on the green flag. the a block of code an event triggers it. below). but not be visible straight away. natural process of playing they Score Neil sends a broadcast to understand the link between Matt triggering Matt to tell the each of the blocks and how player their score.3. At the bottom of this column you will also find the very First. At the game is to score more than three points. This second loop is an if When Green Flag clicked.4 Part 1 of the main game code. enabling you to write code for effects that may be in use and that sprite only. which is stored in the Sensing Right-clicking on Each of our sprites has their own scripts assigned to run once category of blocks. and then through the Matt to taunt the player.2 and sorted by function. then stores 0 in the variable called guesses (see Fig 1. so our We then ask the question and run another loop inside of logic was as follows: the main loop (see Fig 1. player_name The stage sends a broadcast once the player Fig 1. To write code with Scratch. We wrap the associated with them.1. as a variable called Answer.3 This resets Neil’s sprite and the a broadcast to trigger the end of guesses variable. our logo is Sprite5 and the Game Over image Once we have the formalities out of the way. using associated with the stage. which we will come to later. Matt is Sprite7. called Matt and Neil. If the stage that asks for the player’s name. left). Building our game above-right). as a trigger event. they work together. Scratch uses a clear and As we can see (Fig 1. structured layout. This from the block palette to add code to our program. Each of these sprites has their own scripts to the main loop that controls the first question. Once created. in parallel to each other. who will say something nice. play a gong sound effect. If they Loops A way to repeat a sequence. we can easily Programming concepts Using Scratch is great fun but did you realise that Parallelism This is the principle of running rules that we all learn in school. first block is a broadcast score to Matt – this will trigger Matt to tell us the score. times to change the size and rotation of the sprite. The first section of the third part is exactly the same as the main loop from the previous two parts.3)). just like you’d see in the classic 8-bit games of the 1980s. associated with that broadcast.6 The last The Green Flag event is the code that controls the over broadcast is sent. We completed in a certain order. the player would have to try in our game. For our game we have two sections of code on the stage. then Neil will say ‘Incorrect’. And once because each sprite has its own code that runs data if required. finally.net . To create a variable. The first part resets two variables called guesses and score. doubled your code in just one click. The second section of code is an infinite loop that will play the loop DrumMachine continuously and set its volume to 50%. above). So let’s move Fig 1. below). who will then run thorough the end of game code The Game Over sprite has two scripts associated with it. In there you will find the ‘Make a variable button’. Click on it and you will see Fig 1. we need to use the ‘Variables’ button from the block palette. the player would be awarded a for statement (for x in range(0. then alter the variable score by 1 point and. We then pause for three seconds to allow we broadcast game_over to Matt. Hey presto – you have be connected. The stage As well as being the home of our sprites. learnt they can be applied to any coding project. which enables us language you use. To have a white ‘halo’ duplicate code in Scratch.net correct. Our have its own scripts.7 The Stage contains the sprites but it can also down to the last four blocks of code (see Fig 1. triggers the Matt to finish speaking. which is then broadcast to Matt and Neil. the game here is clicking on the green flag to start have used conditionals in our game to compare steps needed to solve a maze. the answer given to the expected answer.6. 90 | Coding Made Simple WorldMags. we use stop all to stop The first is simply that when the green flag is clicked. We’ve used that a lot in our Scratch game to perform calculations in our code and iterate coding provide a firm foundation. and the most visible event in our Scratch against the input that is given by the player. play a sound to reward the player. tip Part two of the code is exactly the same as the main loop Blocks that can be of part one and the reason why is because we duplicated the linked together will code and changed the question and expected answer. we need to create it. giving us a rotating zooming effect. In our game we used two variables – score and guesses – and we want them both to be available for all sprites. Both sections of code are triggered by the click on Green Flag event. We have the score to show the player’s progress through point. It triggers the sprite to reveal itself and part of the main code associated number of guesses that the player has. broadcast support to Matt. in turn. They can Data We use a variable to store the value of our both matched. As we mentioned earlier on. logic to say that when the number of guesses is equal to 3. you can simply right-click on the indicating they can blocks of code and select ‘Duplicate’. We can apply you are also learning to code? No matter what more than one sequence of code at the same operators to text and numbers. Neil will say that the answer is correct. the game. which in Boolean logic would be be run for ever (while true) or controlled using a score and we can later retrieve and manipulate classed as True. so that Matt and Neil can use them both. Then we send another broadcast to end of game script. The second script is triggered when the game_ Fig 1. Conditionals These form the basis of our logic The main concepts are: Events This is a trigger that starts a sequence and provide a method for us to compare data Sequences A series of tasks required to be of code. the underlying concepts of time. the stage can also contain its own scripts (see Fig 1. to hide any scripts in the game.7. Operators These are the basic mathematical once again. variables are a great way to store data. Lastly. We use conditional set its size to 100%. the sprite. But before we can use one. Matt. and then increment the guesses variable by 1 and send a Quick broadcast to Matt who will taunt the player. We then use a loop that will repeat 10 with Neil. and starts the main code loop assigned to Neil. defined as False. which. which would be used many loops to control the player’s progress the game. WorldMags. We then ask the player to provide their name. For example.9 (see right). If the player provides an incorrect answer. If they did not match. This is when you write down the logic of how your program will work.net drop these variables into our code. Matt will also say something nice. A box will appear for you to type your answer. we iterate a by 1. In both Scratch and Python. and that we reach a = 9 and then it will stop as the next value.8 below for the example that we made for our game. Matt says hello and Neil says hello and your name. If you guess correctly. So now let’s play our game. Every time we go round the loop. Else if your answer is wrong. you will be taunted by Matt and the number of guesses will increase by 1. We then create a a=a+1 conditional loop that only loops while a is less than 10. see Fig 1. there are two variables in our you’ve enjoyed learning Scratch.Q WorldMags. is Scratch can be used to help understand the logic that powers not less than 10. If the number of guesses made reaches 3 at any point in the game.9 Hit the forever if a < 10 a=0 ‘Make a Variable’ say a for 2 secs while a < 10: button to create a variable. though this is just scratching the surface of what you can do with it. You will then have another chance to answer the question. we ask Scratch to print the value of a for 2 seconds. If answer correct. from there we create a loop that will continue to iterate round until it reaches 9 (which is less than 10). then Neil will say so. Testing our game We’ve done it! We’ve made a game. and this will happen twice as there are three questions. our code will look like this: [When Green Flag is clicked] Set variable a to 0 Fig 1. Pseudo code When trying to understand the logic of our game. we like to write pseudo code. We hope Fig 1. but how do we express this in a programming language? First. you will move on to the next question. let’s do this with Scratch followed by Python. If you answer all the questions correctly. we create a variable called a and set its value to be 0. They both welcome you to the quiz. In Scratch. You will be asked for your name. ‘Pseudo what?’ we hear you say. Neil asks a question. allowing us to count the number of times that we have been around the loop. leaving you with only 2 guesses left. it’s a great tool to game: guesses and score. We’re going to move back to using the more advanced Python on the Raspberry Pi over the next twenty or so pages. Matt prompts Neil to ask the first question. Your score will increase by one.8 As you can see. Inside So why did we include that piece of Python code in a the loop. In Python our code looks like this many applications. then the game will automatically skip to the Game Over screen. The flow of the game should be as follows: Click on green flag. Let’s look at a simple example: a has the value of 0 while a is less than 10: print on the screen the value of a increment a by 1 So we have our pseudo code. enabling us to reuse their value many times in the game. understand coding but it’s also great fun to learn. change a by 1 print a This gives the variable a the value of 0. WorldMags. Matt will tell you your final score and then say ‘Game Over’. Scratch tutorial? It simply illustrates that there isn’t a lot of then increment the value of a by 1. The Game Over sprite will appear on screen and all of the scripts in the game will be turned off. We’re going leave Scratch for now. This loop will continue until difference in the logic between the two languages. 10.net Coding Made Simple | 91 . so start it up now unhelpfully appears behind the Minecraft window. however. game called Minecraft. then navigate to the python/ Minecraft aficionado. no previous tutorial. whose IDLE can talk to it. We need it open so that Space makes you (actually the Minecraft protagonist. if you were already flying). To choose a type of block to place. So either minimise the Minecraft window with the W. in Create New to generate a new world.py file probably noticed we made in the that the Pi edition is slightly restricted. S and D keys. WorldMags. complete with helpful syntax highlighting. select Run Module or press F5. A. If you edit the code Steve feels catastrophically compelled to introduce his sword to the TNT. name is Steve) jump. so use that one.net . and look around with the mouse. improbable Open. Click on Start Game and then because of the selfish way the game accesses the GPU. wherein we met the Geany IDE. which you might have heard of. Ultimately. and click on the Raspbian menu. guide to the interface opposite – note that only the press E to bring Interpreter window up a menu. There’s no crafting. T he rationale for favouring an integrated development interface) for hooking it up to Python. There’s a quick used for placing blocks. and double-tapping Space makes you You’ll find Python 2 and 3 versions of IDLE in the fly (or fall. So in no time you can environment (IDE) is discussed in the Mint section be coding all kinds of colourful. After a few seconds. From the Run and it is free. but it does support networked play. You’ll notice that it rather You’ll find Minecraft in the Games menu. The Interpreter window with a comprehensive API (application programming now springs to life with its greeting. opens initially. obsidian and TNT blocks. effect ignoring anything else on the screen and summarily you’ll find yourself in the Minecraft world. Raspbian comes with IDLE – an IDE IDLE hands specifically designed for the Python language – and we’re We’ll put Minecraft aside for the moment as we introduce going to use it to further our programming adventures using a IDLE. It’s actually harmless because it’s not live. code. The Editor window opens to display our enemies and no Nether. This can be changed. It also has another trick up its sleeve – it comes menu. improbable things involving (see page 28). 92 | Coding Made Simple WorldMags. efficient way to work.. In the event “In no time you can be coding all Select File > that you’re already a kinds of colourful.” folder and open the helloworld. You can navigate drawing on top of it.. Press Tab to release the mouse cursor from the game.net Coding in IDLE Make Python coding more convenient and start hacking in Minecraft. you’ve things involving TNT blocks. or put it somewhere out of the way. The Minecraft Python API has been landscape with the left mouse button – the right button is updated to support version 3. You can bash away at the Programming menu. This is as a pre-coding warm-up. it comes down to being a more centralised. com. Add the save it first – you can’t run unsaved code.getPos() offending bit of code is highlighted in red.setPos() to change it. These functions are beyond the scope of this the y direction determines your height. Fortunately. Similar to Geany (see page checks the syntax of your code. and again make sure the Minecraft choosing File > New from the Interpreter window.postToChat(‘Hello Minecraft World’) through your code. primer. we can also tell IDLE to execute visible. Now return to your program and run it does something: once again. The mc step by step. mc (short for minecraft). then executes it. and run your program.Player. it the debugger window. classes or methods of any code we have open appear. worry about going on in the debugger.player.] wander around the variables x . and mc. Python keywords are highlighted. a everything up to this line. It also shows any variables. Now enough) ridding your code of bugs. A few seconds later. the Run Module helpfully asks if you want to current position. so that our program actually Debug > Debugger. The second Catching the bug line sets up a new object. IDLE auto-indents with the output appearing in the shell. Steve doesn’t get from mcpi. presumably a little The first line imports the Minecraft module into our code discombobulated. Next. choose game. using four spaces. The debugger enables you to run step by step mc. We’ll start window is visible before running the module.py file and start a new one by Save this update. There’s a lot of stuff you needn’t program. Notice that in the game will vanish. you get an error message and the x.py. but then we suddenly find ourselves Python talking to our Minecraft game: high in the sky and falling fast. The IDLE interface WorldMags. though… – don’t worry too much about the awkward syntax here. and on our go ahead continue. Now let’s add a third line. Press Go again to initiate left change.player. rather than a tab. And we can do an awful lot more. Output from programs run from the Editor appear here. y. the our new program with the boilerplate code required to get message is displayed. without saving it. Right-click the final setPos() line and choose object acts as a conduit between our code and the Minecraft Set Breakpoint. but from our own far as being sent skyward. y + 50. z) Close the helloworld. arrange windows so that both your code and Minecraft are By defining a breakpoint. unfortunately. If all goes according to plan. y and z from the getPos() line have been Minecraft world. 28). This This is where we edit our code. choose Go. but you’ll be able to find some great The API contains functions for working with the player’s Minecraft tutorials at Martin O’Hanlon’s handy website: position: we can use mc. using the We can use IDLE’s built-in debugger to see this happening create() function that we imported in the first line. in the Interpreter window. z = mc. all you need to know is that setBlock() functions for probing and manipulating the the x and z directions are parallel to the world’s surface.net Coding Made Simple | 93 . You’ll find the Run Module option (F5) here. If your code following lines to your code: contains mistakes. You can access it from the Run menu Editor Window menu. but do worry about getting the capitalisation correct. but not as display messages not from other users. Q WorldMags. Don’t worry if the idea of doing geometry The Minecraft API also contains getBlock() and is terrifying or offensive – for now. and he’ll land somewhere around where mc = Minecraft. and navigates any breakpoints you’ve set up in the Editor.setPos(x. you’ll notice that some numbers in the top. which is incredibly useful for (funnily Save this file in the python/ folder as hellomc.net Debug The built-in debugger helps you to track down any errors in your code. co-ordinate system. From message should appear in the game. mc.minecraft import Minecraft hurt in the game. but notice that the As you [you mean Steve – Ed.getPos() to get the player’s. Interpreter We can use this shell exactly as we did earlier when we ran Python from the command line. Class browser This is where the functions. We’ve manipulated the game’s chat feature to window we get as far as displaying the message.create() he was before the program was run. calculated in the Globals panel. These give your position in terms of a 3D Steve’s catapulting skyward. and environment. As before. From the interpreter. we can get down to some proper coding. for itself. You can override the behaviour by specifying a sep parameter to the function – for example. print() also issues a most suitable for beginners can be debated until the bovine newline character.‘) Having pressed Enter and greeted our surroundings.net Python 3: Go! Learning to program with Python needn’t involve wall-climbing or hair-tearing – just follow our three guides to Python prowess. If the >>> import math previous command indicated that this was the case. then you’ll need to find the python3 the recently defined x is a floating point number (or float for packages from your package manager. but for this calculator. the syntax favours simplicity specifying the end parameter. Either way. by Python code is easy to follow. Learning a new following code uses a dot: programming language can be as daunting as >>> print(‘Greetings’. Your distribution probably Besides welcoming people. but Python is certainly a worthy candidate. while If that doesn’t work. * tutorial we’re targeting the newer version 3. final argument. Exactly which language is separation at all. WorldMags. where we would have to straightforward to locate and install. name.net . on the other hand. as well your Python version by opening up a terminal and typing: as many more advanced maths functions if you use the $ python -V maths module. throughout and its enforcement of indentation encourages depending on the circumstances. which is accomplished as follows: >>> name = input(‘State your name ’) Note the space before the closing quote. command succeeded. Unlike typed languages. It understands + (addition). Note that we don’t need to put spaces around our variable. it is separated from our curt demand. . name. Also. Besides separators. we can use the interpreter as a already has some version of Python installed. which is sometimes desirable. saving us the trouble. the explicitly specify the type of a variable where it is defined. If. We could also have used a print() line to display this prompt. good coding styles and practices. / (division) and ** (exponentiation). see what >>> x = math. ‘enjoy your stay. represented by the string ‘\n’ after the herd returns. we can also use the print function: >>> print(‘Greetings’.’. and here is have fixed types. print separates arguments with a space. This means that when the user starts typing their name (or whatever else they want). They should be short). Python variables do not Here you can execute code snippets on the fly. find yourself at the Python 3 interpreter. as we did with the input function.(subtraction). though. to find the square root of 999 Many distributions ship with both versions installed. but times 2015 and store the result in a variable x: some (including Debian 8) still default to the 2. so we could actually recast x above to an where we will begin this tutorial. all the more so for those embarking On the other hand. by default. then you will. and then instead used a blank input call as follows: >>> name = input() This means that input is accepted on a new line. For example.sep=‘. This can be easily changed. >>> quit() However. ‘enjoy your stay.sqrt(999 * 2015) happens if you do: One of many things that Python helpfully takes care of for $ python3 us is data types. which will appear alongside.’) it is rewarding. using sep=‘’ instead gives no on their maiden coding voyage. It’s useful to accept and work with user input. You can check (multiplication). Our first variable name was a string. we can see the values of any variable just by typing its name – however.’) The print() function can work with as many arguments as you throw at it.7 series. The command prints the given prompt and waits for something to be typed. besides being availed of Python is smart enough to figure out that sort of information version information. each one separated by a comma. so let’s instead do a cheery: >>> print('Hello world. You can exit the interpreter at integer with: any time by pressing Ctrl+D or by typing: >>> x = int(x) 94 | Coding Made Simple WorldMags. your first lines of code really ought to be more positive than that. the A fter the basics let’s delve into Python. the user’s input is stored as a string in a variable called name. 2)) arbitrary example: Negative step sizes are also supported. but Python is not one of them.append(19) We can also get the last character using name[ -1] rather We could also insert the value 3 at the beginning of the list than having to go through the rigmarole of finding the string’s with twostep. such as: Thus we can get the first character of name with name[0]. and omitting x defaults to the end of the list. Similar to slicing. So we could Strings are similar to lists (in that they are a sequence of add 19 to the end of our previous list by using the append() characters) and many list methods can be applied to them. >>> twostep. For example. the range() function returns an iterator (it doesn’t contain any list items but knows how to generate them when given an index). method. Methods in Python are firstList[2].2. There are many other list methods.net Coding Made Simple | 95 . you’ll probably find that any additional steps to get Python working. Omitting x defaults to the beginning of the list. which defines the so-called step of the slice. separate IDLE shortcuts for starting each $ sudo apt-get install python3 Now x has been rounded down to the nearest whole number. It’s included in the Raspbian distribution. or wherever the previous step lands. there are a number of constructs available for defining lists that have some sort of pattern to them. You might pressing F5 or selecting Run Module from the running python3 returns command not found. you get the pleasure of a ready-to-roll out a few lines of code and then run them by don’t have Python 3 installed (in other words development environment called IDLE. Thus slicing our list above like so returns the reverse of that list: >>> firstList[::-1] Besides defining lists by explicitly specifying their members. so we could count >>> firstList = [‘aleph’. Some languages are one-indexed. and omitting y defaults to the end.3). and again it’s something we simply have to get used The IDLE environment is ideal [ha. These are short forms of the more general slicing syntax [x:y]. ha – Ed] for developing larger Python to. 3. Items in our list are zero-indexed. In Python 3. select New Window. the slice [x:y:2] gives you every second item starting at position x and ending at position y. and such things certainly become versions 2 and 3 of Python. because 6 is not in that list.net Raspberry Pi-thon If you’re following this tutorial on a Raspberry Pi IDLE enables you to write and edit multiple lines version. of code as well as providing a REPL (Read only the former. arguments specifying the start value and step size of the We could convert it to a string as well. and this can be a they’ve been defined. and are called by suffixing said people find more intuitive.3. WorldMags. Again. One can even specify a third parameter. fine because they can be redefined. too. witness some rather strange behaviour. length first. so we access the first Items can be inserted into lists – or removed from them – item. Here’s an >>> twostep = list(range(5. which returns the substring starting at position x and ending at position y. copied or reconstructed When you start working with multiple lists. WorldMags. with firstList[0] and the third one with by using various methods. We can get the first two elements of our list by using firstList[:2].4. A list is between 5 and 19 (including the former but excluding the defined by using square brackets and may contain any and all latter) by using: manner of data – even including other lists. but if you’ve done an apt-get there’s good news: you don’t need to perform Evaluate Print Loop) for immediate feedback. range.14159265] down from 10 to 1 with range(10.insert(0. together with two $ sudo apt-get update advantageous when working with larger projects. Again. Help is available for function. this can be abbreviated – if you just want every second item from the whole list – to [::2]. In see this in action.0. we can make the list [0. in which case our starting point x is greater than y. or all but the first item with firstList[1:]. so there is an additional function call to turn it into a list proper.1. object with a dot. Previous Raspbian versions came with (1 or 2) and using the Raspbian distribution. This means that we can get all the odd numbers Another important construct in Python is the list.19. followed by the method name.-1). such as the diagram A particularly useful construct is list (or string) slicing. for which you would have to use the len() which you can peruse using help(list). the range() function can take optional projects. they cannot be changed – but this is very useful resource when you get stuck. ‘beth’. hammer the new version has been pulled in. for example. To dist-upgrade recently. using the str type. which some properties of an object. Negative step sizes are also permitted. find this more fun to work with than the Run menu.5] by using list(range(6)). then you can get it by opening LXTerminal and command-line interpreter we use throughout Newer versions of Raspbian come with both issuing the following commands: this tutorial. you might depending on our purposes. For example. But if you fact. Strings are immutable – which means that once any Python keyword and many other topics. there is potential for 0-based grievances. you must accept the consistency is key. or >>> for count in range(5): the first line of The Wasteland. equal to (>=) operators conjoined with an or statement to wherein a codeblock is iterated over until some condition is test the input. even though it’s awfully handy for checking code snippets. So long as year has an unsuitable value. You may indentation. we met.date. The code still runs if you don’t indent this last even wish to use a development environment such as IDLE line. enter the following listing: There are all judicious use of white space. so many variables can point to just keeps asking you the same thing until an appropriate the same thing. our wily while loop keeps It’s time for us to level up and move on from the interpreter – going over its code block until some condition ceases to hold.net . KDE’s kate or The print statement belongs to the loop. things inside a for 1900. for example. want to iterate over different values for count. import datetime def daysOld(birthday): today = datetime. ‘Saturday’. so (which comes with Raspbian and is designed especially for only gets executed at the end. which we can >>> count = 0 either import into the interpreter or run from the command >>> while count < 5: line. as shown here: save our code to a text file with a . but in Python it’s all colons and Having found such a thing. Fortunately. we’re using the for construct to do keep asking. Other languages delineate code blocks for this introduction.net opposite illustrates. It is initialised to 0. enter their granny’s name. so we are guaranteed to enter the loop. so let’s look at a more involved example: # My first Python 3 code. You need to find a text editor on your system – you can … print(count) always use nano from the command line. it We can easily implement for loop functionality with this is not suitable for working on bigger projects. such as Gnome’s gedit. you were born on a’. birthmonth. the canny coder makes extensive use of loops. by which time the value of the language) but we don’t require any of its many features This Pythonic creed is worth count has reached 5. programming >>> year = 0 # The # symbol denotes comments so anything you put here habits. ‘Wednesday’. form. but in that case the print call is not part of the loop. They could. the prompt changes from >>> to …. That while loop was rather #! /usr/bin/env python3 kinds of bad trivial. count) interpreted as a year. Instead we’ll construct. WorldMags. which is certainly less than some counting. ‘Sunday’] birthyear = int(input(‘Enter your year of birth: ’)) birthmonth = int(input(‘Enter your month of birth: ’)) birthdate = int(input(‘Enter your date of birth: ’)) bday = datetime. then you can ‘1979’ – needs some treatment. If you always returns a string. change 2015 if you want to keep out interpreter. studying. ‘Thursday’. which guarantees that we range iterator. Python (honest) youngsters. so even good input – for example.weekday()] print(‘Hello. string consisting of anything other than digits to an int. Note that the input function issue five print statements in only two lines of code. value is selected. trying to compare a string use a different range or even a list – you can loop over any and an int results in an error. We (alongside many others) like to use possibility that they will enter something not of the required four spaces. objects you like. We use the less than (<) and greater than or Very often. When you start such a block in the program.birthday). using brackets or braces. dayBorn) 96 | Coding Made Simple WorldMags. Another type of loop is the while loop. Rather than Grown-up coding iterating over a range (or a list). thanks to the the lightweight Leafpad. but Whenever you deal with user input. birthdate) dayBorn = weekdays[bday.days return(ageDays) if __name__ == ‘__main__': weekdays = [‘Monday’. The result is that we continue looping the loop. Likewise. so just a simple text editor will suffice.py extension. which comes with Raspbian. so this code variables are really just labels. permits any number of spaces to be used for indentation. ‘Friday’. the last line of our example Enter a blank line after the print statement to see the does a good job of sanitising the input – if we try to coerce a stunning results of each iteration in real time. You could loop (or indeed any other block definition) must be indented. ‘Tuesday’. neither of which can be … print(‘iteration #’. change 1900 if you feel anyone older than 115 might use your otherwise you get an error. not just integers. which we met earlier. Note the indentation here. For our first loop. but you may prefer … count += 1 to use a graphical one.date(birthyear. which >>> while year < 1900 or year >= 2015: doesn’t matter are best to avoid … year = input(“Enter your year of birth: ” ) from day zero.today() ageDays = (today . This seemingly inconsistent behaviour is … year = int(year) all to do with how variables reference objects internally – We met the input statement on the first page. then The variable count takes on the values 0 to 4 from the we end up with the value 0. so using this as an index into our list weekdays in the instructions. ‘Sun’] >>> [j ** 3 for j in range(11)] It’s worth noting at this point that to test for >>> days = [j + ‘day’ for j in daysShort] This returns a list comprising the cubes of equality. Therefore we can apparently command line. anyway – first we must make it executable by running the following command from the terminal. ‘Tues’. you can find some great Python tutorials on the web. we haven’t bothered with list language constructs. which returns a datetime.’) Save the file as ~/birthday. No tutorial can teach this.timedelta spooky action at program or the interpreter.com. j and k. returning the number of days the user has been alive. Python also has a huge number of modules (code libraries). ‘Satur’. example. Be careful. We have written a bona fide object. but hopefully we’ve next line gives the required string.com and www. however.org/3/tutorial/) is datetime. before. WorldMags.date – and our next line (using the input that we quite extensive. as opposed to being import-ed into another subtract two dates. It’s not the if block is ignored. This example uses the datetime module. The final line calls our sufficiently piqued your curiosity that you will continue your function from inside the print() function. You are free to remedy either of these and more exciting project. We’ve actually covered a good deal of the core demons. provide sensible dates. The special variable __name__ takes on the such as weekday() and year(). demonstration of Python’s laconic concision. Our iterator variable j runs we could select only those beginning with ‘Z’ or introduced can join forces to form one of over the beginnings of the names of each day of those which have ‘e’ as their second letter by Python’s most powerful features: list the week. species. To keep things simple.py (Python programs all have the . working with lists. but now we’re making our own. and we trust the user to difficult to develop the ideas we’ve introduced into a larger Python rolls. The first line just tells Bash (or whatever shell you use) to execute our script with Python 3. the numbers from 0 to 10. Due to leap years. which also strive for simplicity. However. And so concludes the first of our Python coding tutorials work of Chthonic The next four lines are similar to what we’ve come across on the Pi. you could try: [‘Herman’. Our function takes one parameter. you can dive straight in and see it in action. ‘Zanthor’] ‘Thurs’. including We also have plemnty more excellent tutorials in this very weekday(). The The datetime module provides a special data type – official tutorial (. which provides all manner of functions for working with dates and times. ‘Wednes’. we use the == operator. date objects also allow for run into this special value __main__ when the code is run from the general date arithmetic to be done on them. These are a great suffixes the string day – the addition operator >>> names = [“Dave”. this would be some pretty fiddly calendrics if we had to work it out manually (though John Conway’s Doomsday algorithm provides a neat trick). which we use next. if we have a list of names. coders use short variable names. then we can call it into action: $ chmod +x ~/birthday. and then our list comprehension using: comprehensions.py $ ~/birthday. but when we import it. Comprehensions can because a single equals sign is only used for commonly i. then the program works out how many days old you are and on which weekday you were born. use all kinds of other constructs as well as for assignment. (+) concatenates (in other words. though. and with a little imagination it’s not it’s just how comprehension for the weekdays. 5: would result in an error. daysOld(bday). Before we analyse the program. for ephemeral variables. because there are a couple of things that we haven’t seen before. joins) strings “Zanthor”] Consider the following example: together. As well as having a simple core language structure.codecademy. This returns an integer publication. learning to code is much more between 0 and 6.py extension). If you want a more arithmetical >>> [j for j in names if j[0] == ‘Z’ or j[1] == ‘e’] >>> daysShort = [‘Mon’. so doing something such as if a = such as those which are used in loops or loops. everything in the or seconds(). Besides methods coding adventures. and uses the datetime module to do all the hard work. and using your newfound skills. which we can then convert to an integer using days() a distance when Python module here. Very often. Date objects have various methods. Help is never far away.net print(‘and are’. Q List comprehensions Lists and the various constructs we’ve just comprehensions.py If you entered everything correctly. Next. with 0 corresponding to Monday and 6 to about experimentation and dabbling than following Sunday. oddly enough. after the comments. Almost. ‘Fri’. “Herman”. The def keyword is used to define a function – we’ve used plenty of functions in this tutorial.‘days old. we import the datetime module and then begin a new codeblock. birthday. and you can find others at http:// have just harvested) sets our variable bday to one of this tutorialspoint. WorldMags. For example.net Coding Made Simple | 97 .python. The strange if statement is one of Python’s uglier You might constructions. We’ll do a quick rundown of the code. “Xavier”. The API. a multicoloured LED matrix and much more.raspberrypi. where they will be run in zero-G. Owing to power requirements aboard the space station.org/files/astro-pi/astro-pi- install. Also worthy of attention. They’re not critical for understanding this tutorial. because many young learners find programming much more intuitive when the results can be visualised three-dimensionally from the point of view of Steve.com. WorldMags. whence comes the code used in this tutorial. e have published a fair few guides to the Python W API for Minecraft:Pi edition for the Raspberry Pi. you can still have a lot of fun playing with the Minecraft Python API. the Pi cannot be connected to a proper display – its only means of visual feedback is the 64-LED array.net Astro Pi and Minecraft We conclude our Python exposition on a recreational note. combining Minecraft and space exploration. so can still provide a fair amount of information.sh --no-check-certificate | bash It takes a while to run on the original. attired with an Astro Pi. and also featuring excellent Minecraft tutorials. will join ESA astronaut Tim Peake for a six- month stay on board the ISS. The lucky winners will have their programs join Tim on his voyage to the ISS. and will very soon be available to the general public. Minecraft. It is available for free for school pupils and educators from the website . This is a Hardware Attached on Top (HAT) expansion board. but you can also download an installer for these. accelerometer. install it from the repositories: $ sudo apt-get update $ sudo apt-get install minecraft-pi If you don’t have an Astro Pi board.If you don’t have it. various environmental sensors.org. Open a terminal and type: $ wget -O . The Astro Pi ships with a Raspbian SD card preloaded with all the required drivers and configs. single-core Pi. which features all manner of cool instrumentation: gyroscope. magnetometer. One of the most exciting Raspberry Pi projects right now is the Astro Pi. While we’re setting things up. further edifies the Pi’s status as an educational tool. see page 108. a Raspberry Pi. and you’ll need to reboot for everything to work properly. enter a new world. but are certainly worth checking out if the idea of programming a voxel-based world appeals. These are installed by default on recent Raspbian versions (there should be an icon on your desktop). The most exciting thing about the project is that in November 2015. A competition is currently underway across UK schools in which entrants must devise Python code utilising the Astro Pi. then Alt+Tab back to the 98 | Coding Made Simple WorldMags. if you can come up with a good coding idea.. the game’s intrepid hero. This is multicoloured. make sure you’ve got Minecraft and the Python 3 API set up too. though. is Martin O’Hanlon’s excellent website. besides being a lot of fun. connecting via the GPIO pins. Just start Astro Pi sits snugly atop Terrestrial Pi. 35. >>> mc.T. 0.setBlocks(-5. O. 1. -2.setBlocks(0. O. X. 3. 13) O.set_pixels(question_mark) The setBlocks() function fills the cuboid given by the first It is probably more desirable to type this code into a text six numbers (the first three are co-ordinates of one corner editor and then import it into Python. O. 42) ] >>> mc.setBlocks(2. -7. -2. O.setBlocks(-6.. O. rather than work in the and the next three are co-ordinates of the other corner). 0. We’ve used the setBlock() function above – this just sets up a single block.setBlocks(-6.“) hand. 42) O. >>> mc. air warmed by the Pi’s CPU won’t join astronaut Major Tim Peake aboard a Soyuz Measurements. too. instead it will just hover around in (glorious nation of) Kazakhstan. As well as text. we’ll turn our attention to coding on the Astro Pi. 11.Minecraft. we don’t need to specify a colour. 35. 0.show_message(“E. >>> mc. X. -2. O. -2. For now. O. desktop and open a terminal window.. 15) >>> mcsetBlocks(0. we can also load images general is referred to as block data. so that our ap 35 stands for wool). Space Radiation here on Earth). 11. 2. -3. -2. >>> mc. O. >>> mc. WorldMags. 11. O. This connects to the Pi via the General Purpose Input/Output (GPIO) pins. O. 0] # Red Python 2.setBlocks(-5. 15) O. O >>> mc. Wool is a special block that comes in 16 object is correctly set up. as well as to provide pupils. O. O. >>> mc. -2. O. O. with the winners having Tim run their anything that is going to be connected to the ISS much needed airflow. -2. but you information there. O. 42) O. 11. we don’t need to worry about coding at the level of individual pins. -2. 42 ) O. though. O. O. O. O. two Raspberry came together to make this exciting outreach electromagnetic interference. O. next number decides the block type (42 stands for iron. -2.setBlocks(-6. You can find a thorough guide to the API at www. O. X. X. we can through an optional eighth parameter. You can use this trick as a slight shortcut if you’re only throughout this change the player and camera position.stuffaboutcode. -9. Space. X. 2. O. O. -2. -4. So you need to put the first two lines from our E. 35. because each LED requires its own colour you use Python 3 The API is capable of much more than this – we can triple. get the ground level going to be working with a few colours.com/p/minecraft- api-reference. 8. -3. 0. O. 35. -6. 35. For example. so only requires one set of co-ordinates. The following draws a rough and ready O = [255. This carefully machined and very strong case (it’s made of 6063 . being hazardous. -2. O. WorldMags. O. O. we can display a suitably space-themed message in an extraterrestrial shade of green using the show_message function: from astro_pi import AstroPi ap = AstroPi() ap. O. >>> mc. The interpreter. From here. including are not allowed to exceed 45°C. and one with the normal Pi-Cam) will identified to inspire junior coders: Space conditions. Satellite dissipate (as happens naturally by convection rocket.html.0]) grade aluminium.create() probably isn’t the type of thing you want to do too much of by We’re assuming >>> mc.setBlocks(7. O. but we’ll describe what everything does as we use it.net Coding Made Simple | 99 . -1. 7. 255. O. -2. O. blasting off from Baikonur cosmodrome Imaging and Remote Sensing. 5. -2. O. though: series.net The mission On Thursday 19 November 2015. 15) O. X. This project still works with at a given set of co-ordinates. 0. text_colour = [0 Space case.postToChat("Hello world. O. -2. The module provides some simple and powerful functions for querying sensors and manipulating the LED array. O. X. 42) O. >>> mc. O. O. and get and set block X = [255. There heatsink for the Pi’s CPU – surfaces on the ISS Station. O. The flight case has been A nationwide coding competition was Getting the Raspberry Pi and Astro Pi precision-engineered to comply with rigorous launched for primary and secondary school approved for cargo is a complex process – vibration and impact tests. using the set_pixels() function. O. -1. 15) ap. 255] # White may need to install representation of a Raspberry Pi (it could be a Pi 2 or a Model the Pillow imaging B+). O. As so. -9. phone home. Spacecraft Sensors. It also acts as a giant code when he arrives at the International Space power supply has to be thoroughly tested. while phone home snippet at the top of the program. 8. 7. and thermal testing – in zero-G module. O. O. which in well as dealing with individual pixels. O.255. 35. plus the block type and optional block data arguments. This tip >>> mc = minecraft. -8. O. O. 8. -2. but if we wish to do interpreter or run it from the command line if you prefer. don’t ya know) will house the Pi on its space odyssey. -2. but thanks to the astro_pi Python module. X. -2. 15) O.T. sharp edges Pis (one with the infrared filtered Pi-Noir camera project possible. -2. and Data Fusion.setBlocks(4. -6. start Python The text_colour parameter here specifies the RGB 3 ($ python3) and enter the following: components of the colour. You can then import it into the colours.setBlock(-6. A number of themes have been assessment. -6.”. X. industry and education sectors are all manner of considerations. component by component: question_mark = [ library with sudo pip install Pillow. we can also work Quick >>> from mcpi import minecraft with the individual LEDs. O. 1. -2. 6. -9. O. if you’ve still got a pixel art and the like. Left-clicking results in Steve hitting stuff Martin O’Hanlon. If $ sudo python3 rainbow. Hitting the sensors. Before we run it. You can also use the $ cd ~ virtual joystick to move the virtual assemblage in three Sword-wielding Steve stands ominously close to a USB port. Normally. To download the code to your sense. Instructions for this are at www. but this one is virtual device.load_image("~/astro-pi-hat/examples/space_invader. but it’s excellent for displaying make sure Minecraft is started. get_ run it through sudo: temperature() and get_pressure(). then displaying 15-bit colour depth (five bits for red. the LEDs are only capable of Python session open from the beginning of the tutorial.com/martinohanlon/ follows: MinecraftInteractiveAstroPi. equipped with the Astro Pi HAT. which is given in terms of the pitch. who submitted the idea to the message telling you to hit the virtual Astro Pi by right-clicking Astro Pi competition. Minecraft allows you to fly by tapping and then The project we’re going to undertake is actually the brainchild holding Space.0. y and z positions. but they are nonetheless at right angles to each other some great examples in the ~/astro-pi/examples directory.php?t=109064. we need to self-explanatory functions get_humidity().md. 100 | Coding Made Simple WorldMags. You can also find out the it. and go in directions parallel to the ground plane. The (extensive) coding was done by it with your sword. Run these with. Also. and explain select parts of pressure.png") This downloads all the required project files into the Bear in mind the low resolution here – images with lots of ~/MinecraftInteractiveAstroPi/ directory. Don’t expect to understand everything in the code right orientation of the Astro Pi. Something about knives and toasters. So fly up to this and you’ll see an introduction of student Hannah Belshaw..raspberrypi. $ cd ~/MinecraftInteractiveAstroPi accelerometer and magnetometer are all integrated into a $ sudo python mcinteractiveastropi. just open up a terminal and issue: forums/viewtopic. it’ll serve as an excellent base calibrated the magnetometer for these readings to make for adding your own ideas. You can explore all the components of the Pi and the Astro Rather than have you copy out the code line by line. The project properly. so colours are dithered accordingly. but you can find all the relevant API of numbers which identify tiles by their x. Now and five for green). the which show off everything from joystick input to displaying a player will start at position 0.git ap.com/astro-pi/ The y co-ordinate measures height.net directly on to the array by using the load_image() function as $ git clone. The gyroscope. for example: co-ordinates in the upper-left corner). detail don’t work very well. You’ll also find define. we’re good to go. Bear in mind that you need to have you get a couple of footholds.0 (you can see your rainbow pattern. Because the Astro Pi libraries need GPIO We can also query the Astro Pi’s many inputs using the access. you will see that this partial eclipse is caused by the appearance of a blocky contraption that our code has The virtual interactive Astro Pi created. to whom we’re ever so grateful. and this in turn requires root privileges. the latter avails you of the local download it straight from GitHub. away – there’s a lot of stuff we haven’t covered – but once roll and yaw angles. in which case you $ cd ~/astro-pi-hat might notice that it suddenly got dark in Minecraft-world. temperature and humidity. calls in the documentation at. WorldMags. We won’t be doing Everything in Minecraft is located by co-ordinates – triples any inertial measuring.py so-called Inertial Measurement Unit (IMU). Also. so don’t do that. six for blue..net .org/ home directory. x and z are harder to astro-pi-hat/blob/master/docs/index. which would destroy the blocks that constitute our draws a Raspberry Pi (like we did earlier).py you look up. we’ll Pi. exit it now (Ctrl+D) so that things don’t get confused. this ensures that “ humidity = {}. 1) there are a few more. y + j + 2.setPos(x. and mad props to Martin command line or just imported. #sleep for a bit query the Astro Pi hardware and display current readings. z = mc. minecraftstuff.setPos(). the resulting mc. def teleport(x=0. 46. For instance. We pass that we may not be interested in. So that the player can keep for allowing us to use his code. teleporting and TNT Even if you don’t have an Astro Pi. mcinteractiveastropi. When a block is hit. which reconciles the 16 colours of wool available with something that the LED array can understand.1) joystick even moves the Pi around. #each time a block is hit pass it to the interactive This probably which is a human-readable string describing the blocks in astro pi isn’t a safe question. try this one) statements and #keep reading the astro pi orientation data otherwise the appropriate action is taken. then use the . zedge_hi.getPos() chain reaction will be very taxing.5 + j between Python and Minecraft). we can move up in-game. if the mcap. We can use curly braces as placeholders for do.format() method to determine how construct usually used in conjunction with an except: for they are displayed. you can catch a glimpse of how things work. series of if and elif (short for else-if – in other words. It’s used to forth and do these things. if you prefer). the player to the coordinates of our choosing their explosions by using some additional block This sets the TNT to be live. But fret not – mature adults can get The magic is all in that final [code] 1 [/code]. Studying the code If you open up the main project file. Rather than using the setBlock() functions. you need to set up arguments takes Steve back to the origin (where xedge_hi = xedge_lo + 10 . then you’re If you’ve had a look at the various blocks zedge_hi = zedge_lo + 10 . the following string (from line catching errors and exceptions.postToChat(). Q Minecraft: Pi Edition API. y. ap. and the Astro Pi is reset. postToChat() and setBlocks() functions. We have already seen the available.net dimensions: the button toggles whether it moves in the horizontal or vertical plane.pollBlockHits(): place to stand. and can in fact be instantiated as many times as you like.2 * j the mc object (which handles all communication the Astro Pi is drawn). either by Because the sensor data often has lots of decimal places pressing Ctrl+C or by killing the Minecraft program.2 * j good to go. This loop runs until it is forcefully interrupted. which in fact deals with all the components that can Bring TNT be hit. Some of the components just it goes out of sync display an informational message using mc.format(round(humidity. Hannah. We’ve already met the slightly odd if __name__ == “__ This is a really great project to explore and extend. y. WorldMags. In our case. you’ll no doubt have discovered TNT mc. we take advantage of the position of each block-hitting event to the interact() Python’s string formatting capabilities to round things function.5 + j you’ve imported the module. Once here. it is followed with 157) formats the readings for the combined humidity and a finally:. for discern whether the program has been executed from the coming up the idea in the first place. which figures out what has happened and what to appropriately.pos) previous condition didn’t hold. This is done in the interact() function. this property is checked using a for blockHit in mc.get_orientation() some. These have a property called tag. Here’s a function that’ll figure out Steve’s click it with your sword (or anything). The main loop is wrapped in try block. in a text editor (or IDLE. so that if you left- with player. so that calling teleport() with no xedge_lo = x . In this case.2). all you need to understand is that the board we draw in Minecraft is an instance of the object whose description begins with the class at line 19. the virtual Pi is round(temp. temperature = {}”. Quite early on is defined a list called LED_WOOL_COL. you ought to migrate to a safe distance. then it write and call a simple teleport function from position and then assemble a substantial begins to flash and pulsate ominously. but (block type 46). it changes colour and the corresponding LED on the array does likewise.setBlocks(xedge_lo. zedge_lo. WorldMags.net Coding Made Simple | 101 . We won’t go into the specifics of object- oriented programming and classes. Also great work. This means that we can data. y+ j + 2.player. zedge_lo = z . z) x.py file). the virtual exploring. y=0. this block of code contains a main loop which to life with the magic of Raspberry Pi is constructed of objects from the custom constantly polls for new events (the player hitting blocks): the Minecraft shapeBlock class (which you can explore in the while(True): Python API. Sadly. The particular instance created by the code is called mcap and is defined way down on line 272. such as the environmental and orientation sensors. When we hit a virtual LED block. At this within the interpreter: pyramid of live TNT above him: point. the sleep(0.interact(blockHit.py. so go main__”: construct in our first tutorial on page 96. which is executed (whether or not an exception temperature sensor rounded to two decimal places: arises) when the try: completes. z=0): def tnt_pyramid(): Also. for the older. This object has its own variables and functions. single-core Pis.events. we kill our running code with Ctrl+C. you can still We’ve given some defaults for the arguments for j in range(5): have a lot of fun with the Minecraft API. For example. 2)) dematerialised. there isn’t a way to blow it xedge_hi. which is a variables.player. sorting things (putting concepts. In theory. but it programs. because searching and indexing course. but this way we have a well-defined order (ascending data is much easier if it is in order.net Sorting lists faster in Python We haven’t got time for this. W ithin the human species. you whatever ordering the user desires. listing tracks with the task (or give up and find something better to do). WorldMags. one could even re-enact Rob dedicated) in their approach. it enables us to show some of them into some kind of order) is perceived as Python’s advantages. albeit described in the purchased them) from the Nick Hornby book High Fidelity. When challenged with the drudgery-filled task of. All should not delve. Pseudocode is a freeform way of expressing code that A workaround Sorting may not be the most glamorous of programming lies somewhere in between human language and the is to add pylab. These enable a modern computer to suit by face value. say. Quick useful would be an unsorted telephone directory. We’ll sum up some of these with pseudocode box displays only a blank window. We’ve actually overlooked a couple of 102 | Coding Made Simple WorldMags. below. Imagine how much less numerical) to aim for. As such. be it lexicographical or Machines obviously need to be more systematic (and might find that chronological. and indeed Python’s built-in sorting methods will programming language. Code-folding and highlighting without the bloat. and eventually complete a new version Rhythmbox) library in a matter of seconds. including its no-nonsense syntax and anywhere between a necessity (things disordered the simplicity by which we can use graphics. Furthermore. albeit several orders of magnitude faster. by comparison. haphazard piling and re-arranging. it’s time to sort out that most fundamental of algorithm classes: sorting (sort of).001) after prove much faster than anything we program here. first by suit and then within each tip of computer science. It’s straightforward enough to the animation Fleming’s autobiographical ordering (the order in which he come up with a couple of sorting algorithms that work. most people will flounder around with some If you’re using happily sort a several thousand-strong iTunes (err. various sorting algorithms were developed early in the history putting 52 cards into order. serves as a great introduction to various programming becomes difficult. topics. Geany is a feature-packed text editor that’s great for editing Python code. of Matplotlib with Gnome. universally of the concepts apply equally well to any other kind of data. not very quickly. but don’t be disheartened when the translation each draw() call. we’re going to work exclusively with lists of integers. It’s a good way to plan your pause(0. To make things cause the most dire distress) and a dark ritual into which one easier. Computers. of prefer things to be sorted.net . is that this algorithm (like Selection lists. and much more exciting than the print selectionsort() and quicksort() too – just add k -= 1 statements we used earlier. we resume the outer loop. constant (which depends on the machine) times n^2. But in each loop iteration we must find a minimum element.set_ydata(a) data is redrawn after each list update). Time complexity notwithstanding.plot(x. Once we get back to Very often. complexity. This is – in other words.‘m. As it proceeds.com. We again we can deduce O(n^2) complexity. Selection places. including Bubble Sort (aka for each position j in list Sinking Sort) and its parallel version Odd-Even Sort. WorldMags. as n gets large. WorldMags. inserting an item would require the whole list to be shunted down between the insertion and deletion points.1] not the fastest way to display graphics (all the function. which can do all manner of import pylab x = list(range(len(a))) plotting and graphing. was quickly swap numbers at positions k and k .net Coding Made Simple | 103 .a. the beginning.set_ydata() and pylab. visit. at the beginning. rightfully. InsertionSort. but is outperform Quicksort for small notation to express the function’s complexity as a function of nonetheless interesting.net minor details here. which is called linear. so the algorithm actually behaves with apparently Here is another naive sorting algorithm.log n) complexity.py so that it can our sorting algorithms can be brought to life. you the input size. and sorting time. but for j in range(1. What is not immediately obvious. In this situation. having trickled down there by a lengthy swap Quicksort initially. This isn’t saying that Selection be swapped in. quickly. we can tell that SelectionSort will loop over items in the list at least once. As such. We’re going to use the #! /usr/bin/env python3 a = list(range(300)) Matplotlib package. sequence. we suppose our list has n items Sort) has sorted the first i entries after that many iterations can create a hybrid and the crude analysis above says that Selection Sort runs of the outer loop. It’s Here we’ve modified our insertionsort() l[k . Insertion Sort: There are a few other naive sorting algorithms that may InsertSort(list): be worthy of your perusal. We swap items that Quick can approximate how long an algorithm takes to run by are not in order.markersize=6) distros. Note that we swap elements here rather than insert them. the most Selection Sort. We met for loops way back on page 50. thanks to its swift O(n. but that will all be sorted out when we write our actual code.1]. The first loop iteration simply finds the smallest element in our list and places it. which proceeds simple algorithms each going over our whole list. which for the first few loops (where j is This time we are upfront about our two nested loops. It can be found in the from random import shuffle shuffle(a) python3-matplotlib package in Debian-based line. In our case. And so it goes on. this is so that we are only modifying two of our list items. the inner while loop terminates Sort gets pretty slow pretty quickly. until the work is done.draw() easy. We then start at the second item and see whether there is a smaller one further down the list. an out-of-order element may sorting algorithm with complexity O(n^2). list items are not too far from their rightful slightly disappointing news – in layman’s terms. l[k] = l[k]. and code. len(l)): Save this file as ~/animsorting. SelectionSort(list): for each position j in list find minimum element after position j if minimum element is smaller than element at j swap them Selection Sort is a fairly simple algorithm.ion() # turn on interactive mode discussed here. while k > 0 and l[k . There isn’t room here to even scratch the def insertionsort_anim(l): insertionsort_anim(a) surface of what’s possible with Matplotlib. the will pretty much have two loops – one nested inside the other. l[k . Here we can see Selection Sort in action.draw() calls after that can help visualise the sorting algorithms each line that modifies the list. Quicksort was developed in 1959 k-1 and. In Selection Sort’s worst case we continuing to swap out-of-order entries. k=j do chmod +x ~/animsorting. and then move backwards down the list tip looking at these details.’. but we k=j have much to get through so it’s time to look at a grown-up while number at position k is less then that at position method called Quicksort. pylab. It is markedly more involved than the algorithms Visualising sorting algorithms Python has some incredibly powerful modules the line. but in simplicity lies beauty.1] > l[k]: be run from the comfort of the command line. divided. and added some boilerplate code to set line. O(n). reverts to What we can say is that the relationship between input size in many situations. but it’s everything up. but by the end of the inner loop it will be in its which uses Sorting a list of one item will take one second (actually it right place. swapping if so. but as the list is takes 0 seconds) or a list of five items will take 25 seconds. will be less than some obvious one being where the list is nearly sorted to begin with for example. We use so-called big O towards the end. outperforms Selection Sort. so small) involves checking most of the list items individually.1 adopted as the default sorting algorithm in Unix and other k=k-1 systems.py and then we can show that with just a couple of extra lines. = pylab. which in the worst case would mean modifying every item in the list – a costly procedure if If you’re looking for an excellent resource for learning and debugging your said list is long. You are encouraged to modify pylab. looks like: work on the two sublists to the left and right of the pivot. rather unimaginatively.net . high) briefly how to define functions in the prequel. so we have to do that manually in the last two lines.1: mostly because the tendency is to imagine some kind of If list[j] <= pivotVal: infinite chain of function calls. once it is complete. we are reduced to O(n^2) complexity. Neglecting the details of the partition operation the partition operation runs in O(n) time. our Quicksort pseudocode looks deceptively the partition operation divides the list into two roughly equal simple (excepting perhaps the recursion element). In an ideal situation. The Python code is quite different from the pseudocode. This is where the log(n) in the complexity comes from. So our partition operation. the base cases are the aforementioned lists of left (not necessarily in order). and for subsequent calls they are either from is possible for Quicksort to perform much slower than Elements the low element to the pivot element or from the pivot stated. If Quicksort had a motto. or if a more systematic dividing first and the conquering after. For is arranging the list so that items less than the pivot are to its Quicksort. It length of the list. Eventually. Typically. For the initial function call. which by definition are sorted. This pivot. (Mergesort. trickle one at a If low < high: time from right p = Partition(list. low. sorted list and always use the last (greatest) element as a Insertion Sort Quicksort(list. a decent recursive algorithm # put the pivot after all the lower entries ought to be good at how (and when) it calls itself. Incidentally. because if the condition is false (which would mean the minimum element was at position j). We saw at night-time as Quicksort(list. Unfortunately. an example of a recursive algorithm – Swap list[pivotPos] and list[high] an algorithm that calls itself. p) It’s time to translate our three algorithms into Python. these can be further condensed to a single 104 | Coding Made Simple WorldMags. that’s one of not terribly many reserved words in Python. to that function. but the rewards shall prove worthy of your choose a pivot. the division pivotVal = list[pivotPos] leads to sublists of size 0 or 1. WorldMags. While it’s entirely possible storePos = storePos + 1 to program such a monster. we of the pivot. it would be “Impera et to do this – ideally one would choose a value that is going to divide” because at each stage it does some sneaky end up about halfway in the sorted list. It takes. We have only one loop here. low. and then indent all the code that belongs counting sheep. for a moment. list. you can often get away with on them in isolation. low. a sublist rather than the whole list) and there are That may seem complicated. whereupon the recursion ceases. these are zero and the results in a singleton list. low. because we apply exactly the same pivotPos = choosePivot(list. Watch it Quicksort(list. And Partition(list. middle and final and divided according to a pivot value – all items less than the elements in the list. so length 0 or 1. In practice. In our pseudocode we referred to our list as. This is a particularly tricky storePos = low subject for the novice programmer to get their head around. so we’ll instead use l (for llama). high) methodology to our two smaller lists. though – for example. Swap list[storePos] and list[high] our recursive function calls involve smaller arguments (for Return storePos example. parts. Unfortunately. For each position j from low to high . Selection sort then looks like: def selectionsort(l): for j in range(len(l)): minelt = min(l[j :]) mindex = l. another algorithm. high) Coding it up to left. box function choosePivot(). then. but much of this is cosmetic. we’re doing an inplace sort here – we’ve modified the original list so we don’t need to return anything. which also returns the index stage is called the partition operation. which returns the index of the and all items greater than the pivot are moved to its right. the median of the first. high): pivot. p + 1. besides an unsorted list. There’s no explicit swap operation. low. does the choosing a random value here.net hitherto explored. start the block an alternative to The first thing that the Partition() operation must do is with a def keyword. since These specify the low and high indices between which we halving a list of size n about log-to-the-base-two of n times should sort.index(minelt) if minelt < l[j]: l[mindex] = l[j] l[j] = minelt For simplicity. The if statement is actually superfluous here (we’ve left it in to better match the pseudocode). We use slicing to find the minimum element on or after position j and then use the index() method to find that minimum’s position in the list. there is no straightforward way attention. so at each stage of the recursion we half the list size. # put the pivot at the end of the list Quicksort is. if we start with an already undergoing element to the high element. but this cannot be rearranging and then divides the list into two sublists and acts achieved a priori.) The list is rearranged approach is preferred. then it would harmlessly swap a list item with itself. We’ll leave the pivot-choosing as a black pivot are moved to its left (nearer the beginning of the list). spiralling into the depths of Swap list[j] and list[storePos] oblivion and memory exhaustion. two extra parameters (low and high). but bear in mind all it’s doing so-called base cases where recursion is not used. high): here begins the real fun. net Coding Made Simple | 105 .net Optional arguments and speed considerations Because our Quicksort() function needs the if high is None: algorithms are possible.shuffle(l) >>> sorting. Of course. l[storePos] = l[storePos]. Smaller elements final swap in the partition() function. which happily sort like quicksort(l. 2. To reload the module and apply the changes. so we don’t need to Python skills.org. l[high]. 4. l[j] at http:// while k > 0 and l[k . unfortunately. 3. l[high] algorithms can def insertionsort(l): for j in range(low. 0]. we can’t use. low.py or similar. l[k] = l[k]. the standard import statement won’t notice changes on already loaded modules. we need to use the importlib module’s reload() function. the initial call looks high = len(l) their own . Save this file as ~/sorting. for example.1).000 items instantly. For ongoing to find more. l[k . The workaround would be to make the seconds. We’ve used our swapping shortcut quicksort(l. simple and as close to the given pseudocode as an =.1] > l[k]: storePos += 1 sortvis. until the list is sorted. In general. particularly variables. low. Or you can just exit (Ctrl+D) and restart the interpreter. into Python code. 9. p . which took about 14 known for its speed. l[mindex]. So add a print(l) statement at the end of the loop.l[mindex] This means that the whole algorithm is done in four lines. high): be visualised as wave diagrams. We also add k > def quicksort(l. though many of its first part of the function look like: list. high): 0 to the while condition because the loop should stop before if low < high: k gets to zero.py file. high): animations. Exact timing depends on the particular when working with lists. 1. 5. Lists in Python have low and high parameters.000 items in about 0. high = None): (much) faster implementations of these through its C API. high) is short for k = k . we translate the pseudocode def partition(l. Python isn’t a language len(l) because we’re not allowed to use internal particularly Insertion Sort. which quicksort(l. possible. so that the pivot are swapped to the beginning of the list one place at a time element is plotted in the correct place. There are many more sorting algorithms. which does not look drastically different. then start the Python 3 interpreter in your home directory. However. for j in range(1. but it’s also worth noting that other functions and modules are implemented def quicksort(l. You should be able to import your module like so: >>> import('sorting') Assuming you didn’t see any error messages or make any typos. add print statements to either the for or while 103 – the pylab.1) from before and in the final line use the -= notation. l[storePos] k -= 1 return storePos We start the outer loop at 1 so that the l[k-1] comparison in the while statement doesn’t break things.draw() function should be called after the loops to see the algorithms progress. Try visualising this using the guide in the box on page Again. low. allow default values for arguments to be Quicksort’s benefits – we discovered that it We’ve tried to use code here that’s at once specified – you simply suffix the argument with could sort 10.1]. We have more fun lessons ahead. Besides Moving on to Insertion Sort. Swapping variables without this neat Pythonic trick would involve setting up a temporary variable to hold one of the values. with the same indentation so it is still within said loop. len(l)): if l[j] <= l[high]: Find out more k=j l[j]. The screenshot on page 103 shows the output for the list [6. l[storePos] = l[storePos].3 seconds. low = 0. low. l[high] = l[high].sort() method. We can see the list becoming sorted from left to right. 8. you can then apply your algorithm to a shuffled list. of course. storePos = low sorting Add this to the sorting. and research is The Quicksort implementation is a bit more involved. Q WorldMags. it’s nice to watch the algorithm progress. Python does You need some reasonably-sized lists to see about 50. len(a) . WorldMags. 7.l[j] = l[j]. We’ll use the random module to shuffle a list from 0 to 9 and test this: >>> import random >>> l = list(range(10)) >>> random. high) beginning of the list. rather than try (and fail) to retreat past the p = partition(l. worry about the first few lines of pseudocode. we’re going to take the bold step of shown you something of sorting as well as increased your just using the first element for the pivot. 0. p + 1. high = whereas the others took much longer.1] l[storePos].1.selectionsort(l) >>> l Voilà – a freshly sorted list. and that the last stage of the loop doesn’t do anything. but hopefully this introduction has the partition operation. l[k . com/techradarpro facebook.net IT INSIGHTS FOR BUSINESS THE ULTIMATE DESTINATION FOR BUSINESS TECHNOLOGY ADVICE Up-to-the-minute tech business news In-depth hardware and software reviews Analysis of the key issues affecting your business . WorldMags.com twitter.com/techradar WorldMags. myfavouritemagazines.co.net .uk WorldMags.net THE EASY WAY TO LEARN WINDOWS 100% JARGON FREE AVAILABLE IN STORE AND ONLINE www. WorldMags. The latter net to your home directory.net . The ‘floor’ doesn’t really have any depth. WorldMags.1. and put all the API stuff in ~/picraft/minecraft. such as lines and polygons from dimensions a little later in this chapter. and we Subtleties arise when trying to translate standard will generalise this classic algorithm to three Isometric projection makes concepts. for instance. In order to service these our first task is to copy the provided library so that we don’t mess with the vanilla installation of Minecraft. have to startx. have a decimal part since you’re able to move continuously within AIR blocks. Minecraft requires the X more blocks than you can shake a stick at. so that’s what we’d recommend – your mileage such lacks any kind of life-threatening gameplay. Empty space has the BlockType AIR. and a few steps in the x and z kind of vector graphics: Say. He can move around of this problem occurs whenever you render any inside that block. whereas the y dimension denotes altitude. Minecraft-world fit on this page. On this rather short journey he will be in more than then unless the line is horizontal or vertical. which will change as you navigate the block-tastic environment. The earliest solution to this was contains most of him. provided by Jack Elton Bresenham in 1965. $ cp -r ~/mcpi/api/python/mcpi ~/picraft/minecraft Dude.tar. so is. 108 | Coding Made Simple WorldMags. to draw a line between two points on the screen. where’s my Steve? Here we can see our intrepid character (Steve) Euclidean space into discrete blocks. then. including such delights as GLOWING_OBSIDIAN and TNT. but all that clicking is hard work.gz and by dint of the edition including of an elegant Python API. See how smoothly it runs? Towards the top-left corner you can see your x. a one block at times. but the Minecraft API’s decision has to be made as to which pixels need to getTilePos() function will choose the block which be coloured in. but includes may vary with other distributions. to use the correct parlance) which makes up the landscape is described by integer co-ordinates and a BlockType. generously provided Minecraft: Pi Edition. Your player’s co-ordinates. $ tar -xvzf minecraft-pi-0. kids… actually do try this at home. $ cd mcpi you can bring to fruition blocky versions of your wildest $ . in contrast to those of the blocks. Open LXTerminal and issue the following directives: $ mkdir ~/picraft Don’t try this at home.net Minecraft: Start hacking Use Python on your Pi to merrily meddle with Minecraft. A rguably more fun than the generously provided Assuming you’ve got your Pi up and running. you want directions will take Steve to the shaded blue block. We’ll make a special folder for all our mess called ~/picraft.minecraft. Start LXTerminal and extract and run the This means that there’s plenty of stuff with which to contents of the archive like so: unleash your creativity. y and z co-ordinates.0. and three types of server to be running so if you’re a boot-to-console type you’ll saplings from which said sticks can be harvested. The x and z axes run parallel to the floor. said to be made of tiles. A 2D version inside the block at (0. and as Raspbian. the first step Wolfram Mathematica: Pi Edition is Mojang’s is downloading the latest version from. The API enables you to connect to a running Minecraft instance and manipulate the player and terrain as befits your megalomaniacal tendencies.0).1. The authors stipulate the use of is a cut-down version of the popular Pocket Edition. Each block (or voxel. and there are about 90 other more tangible substances./minecraft-pi dreams with just a few lines of code. instead. O’Hanlon’s website www. BlockType of what you’re stood on are displayed as you move We can also get data on what our character is standing about. 2 to grass.getTilePos() great examples of calling getBlock() on our current location should always x = posVec.postToChat(curBlock) but these are only any fun when used in conjunction with the Check out Martin Here. 0) while True: Assuming of course that you didn’t move since inputting the playerTilePos = mc.player.z with the mc.net Now without further ado. y .net Coding Made Simple | 109 . dabble with physics. and you can find all we’ll cover a couple of these. Until then.g.1 is rounded down to -2).postToChat(str(x) + ‘ ‘ + str(y) + ‘ ‘ + str(z) + ‘ ‘ + of improbable float to int coercions so we may as well use it. return 0. -1. z + 1.z mc. Go back to your Python session and type: Ctrl+C the Python program to quit. Quick curBlock = mc. Your character’s co-ordinates are available via mc. j. Before we sign off. let’s make our first Minecraftian modifications.player.create() posVec = mc. y – 1. It includes all the terminal and run your program: standard vector operations such as addition and scalar $ python gps. Comparing these with the co-ordinates at the top-left. so in t = mc. and go a bit crazy within the y = playerTilePos. Teleporting is fun! Q WorldMags.z As usual.5.postToChat(str(x)+’ ‘+ str(y) +’ ‘+ str(z)) Behold. We’ll start by running an interactive Python session alongside Minecraft. x + 5) put all your code into a file.setPos() function.y z = posVec. As before start Minecraft and a stuffaboutcode. Create the file ~/picraft/gps. Behold! A 10x5 wall of glowing obsidian has been erected import minecraft.create() obsidian wall like so: oldPos = minecraft.block as block mc = minecraft. z) All manner some ways getTilePos() is superfluous.y confines of our 256x256x256 world. the other block types in the file block.x just what the API is capable of. We subtract 1 from the y set up the mc object: includes some value since we are interested in what’s going on underfoot – posVec = mc.x y = posVec.py mc. y. type: 0 refers to air. import the Minecraft and block modules. so open another tab in LXTerminal. Do the following in the Python tab: import minecraft. a nice class called Vec3 for dealing with three-dimensional Now fire up Minecraft.getBlock(x. We can also destroy blocks import minecraft. So we can make a tiny tunnel in our mc = minecraft. and com.setBlock(k. enter a world.py in the ~/picraft/ Python session. These co-ordinates refer to the current block that your character occupies.py multiplication.getTilePos() previous code. rewrite x = playerTilePos. and so have no decimal point. Once you’ve memorized all the BlockTypes (joke).getPos(). The API has str(t)) structures can be yours.Minecraft.block as block by turning them into air.setBlock(x.getBlock(x. 246) with the following code. but it saves three mc. such as our player’s position.player. z = posVec.y something solid or drowning.player.player.Vec3() mc. start Minecraft and enter a world then Alt-Tab back to the terminal and open up Python in the other tab. WorldMags. as well as some other more exotic stuff that The result should be that your co-ordinates and the will help us later on.minecraft as minecraft adjacent to your current location.Minecraft. since otherwise we would be embedded inside y = posVec. but the grown up way to do things is to for k in range(x .1. our location is emblazoned on the screen for a few moments (if not.minecraft as minecraft import minecraft. z + 1. z) We have covered some of the ‘passive’ options of the API. getBlock() returns an integer specifying the block more constructive (or destructive) options. you will see that these are just the result of rounding down those decimals to integers (e. if playerTilePos != oldPos: In the rest of this chapter. 1 to stone. on. running things in the Python interpreter is great for j in range(5): for playing around.x some of the laws thereof. try playing z = playerTilePos. tip mc. you’ve made a mistake). we’ll see how to build and oldPos = playerTilePos destroy some serious structures. which minecraft folder we created earlier. then open up a vectors.getTilePos() x = posVec. which are selected using the blockData parameter. $ cd ~/mcpi For this tutorial we’re going to use the PIL We’re going to assume you’re using Raspbian. involving importing an image of each wool those giant pixels represented? In this tutorial we hark back colour into Gimp and using the colour picker tool to obtain to those halcyon days from the comfort of Minecraft-world. home directory): your home directory and then copy the api files Install it as follows: $ tar -xvzf ~/minecraft-pi-0.gz you’ll be familiar with the drill. which is old and and that everything is up to date. Remember all those blocky palette. multi. And the Raspberry Pi. but a giant raspberry floating in the sky. Also Python.net . For this tutorial we shall use these exclusively. It can import net. WorldMags. for your Minecraft project.png files. Just another day at the office.1. which involves specifying the Red. of coloured wool. The archive on the disk will extract into a your . In order to perform this T echnology has spoiled us with 32-bit colour. Not some sort of bloodshot cloud.gz in the following way: $ sudo apt-get install python-imaging 110 | Coding Made Simple WorldMags.tar. This would be a something called one’s imagination in order to visualise what tedious process. then open a terminal and unzip the file as there. and to copy the API project’s simple requirements. but you could further develop things to use some other blocks to add different colours to your palette. among others. Green and Blue sprites from days of yore. then from a terminal do: minecraft use in your code. colour quantization we first need to define our new restrictive megapixel imagery. Standard setup If you’ve used Minecraft: Pi Edition before All the files will be in a subdirectory called $ tar -xvzf mcimg.net Minecraft: Image wall importing Have you ever wanted to reduce your pictures to 16 colour blocks? You haven’t? Tough – we’re going to tell you how regardless. The process of reducing an image’s palette is an example of quantization – information is removed from the image and it becomes smaller. so there’s follows (assuming you downloaded it to your directory called mcimg. $ .tar.1. but if not this is mcpi. but fortunately someone has done we show you how to import and display graphics using blocks all the hard work already. You can It is a good idea to set up a working directory deprecated but is more than adequate for this download Minecraft from and . as the component averages. so you can extract it to no need to fiddle around converting images. when one had to invoke components for each of the 16 wool colours. The most colourful blocks in Minecraft are wool (blockType 35): there are 16 different colours available. To run Minecraft you need to have first $ cp -r ~/mcpi/api/python/mcpi ~/mcimg/ how to install Minecraft and copy the API for started X./minecraft-pi (Python Imaging Library). The provided archive includes the file test. The 46. # Green if width > height: 150.62.221.png") 65. Steve can draw anything he wants (inaccurately).0.56. This taking up all that space. so since we will convert one real consequence (phew). # Blue next codeblock proportionally resizes the image to 64 pixels 79.80. To ensure the aspect ratio is accurate we 107.56.0. # Magenta you are not happy. # Purple stack more than 64 high (perhaps for safety reasons). We make a new and compute the new image size. # Red rwidth = maxsize 25. The palette is given as a list single-pixel dummy image to hold this palette: of RGB values.188.110.22. which is in mcPalette = [ fact the Scratch mascot. Padding out the palette in this pixel to one block our image must be at most 256 pixels in its manner does however have the possibly unwanted side-effect largest dimension.size[0] 208.len(mcPalette) / 3) rwidth = int(rheight / ratio) Unfortunately the “/ 3” is missing from the code at If you have an image that is much longer than it is high.quant}ize.png.221. we will list our mcImagePal.31. # Lime Green width = mcImage. 177.141. # Black rheight = int(rwidth * ratio) ] else: rheight = maxsize mcPalette.new("P".22.64. # Cyan As previously mentioned. and blocks cannot be stacked more happens because their value is closer to absolute black (with than 64 high. # Dark Grey ratio = height / float(width) 154. but you are encouraged to replace 221. # Brown in its largest dimension.0) * 256 .22). # White this line with your own images to see how they survive the 219.48.ly/ca2015ref though it is a mistake without any 256 blocks in each dimension. WorldMags.net Coding Made Simple | 111 .0) above to (25.161. You can always TNT the bejesus out of them if 179.137.27. 53.138. so that there this behaviour. with one-line simplicity.52.161.70. However. # Orange {res. but we must first define the palette then the transparent parts will not get drawn.putpalette(mcPalette) colours in order of the blockData parameter. # Pink height = mcImage. To work around this aspect ratio.open("test. A if it is too tall. We also need to resize our image – Minecraft-world is only. WorldMags. blocks in Minecraft-world do not 126.64.net With just 16 colours.extend((0.174.201.1)) of the required 8-bit order. you might not want your image of removing any really black pixels from your image. # Yellow mcImage = Image. which we then pad out with zeroes so that it is mcImagePal = Image. so the provided code resizes your image to 64 which we artificially extended the palette) than the very pixels in the largest dimension.39.166.22.153. but the resultant image will be missing its top are no longer any absolute blacks to match against.181.size[1] 64. maintaining the original slightly lighter colour of the ‘black’ wool.61. (1.132. For convenience. You can modify the maxsize variable to change you can change the (0. # Light Blue use a float in the division to avoid rounding to an integer.50. reasonable hack if you’re working with a transparent image is The PIL module handles the quantization and resizing to replace this value with your image’s background colour.125. # Light Grey maxsize = 64 46. expanding on this idea.player. this strawberry/ cacodemon doesn’t spit fireballs at you.k + y. so as a position that befits your intended image. we will position our image close to Steve’s image file and the desired co-ordinates: location.setBlock(j + x + 5.quantize(palette = mcImagePal) this function some arguments too. rheight .rheight)) following could be useful as it enables you to specify the For simplicity.resize((rwidth.player. using the slow but trusty Just replace the mc.z y = playerPos.py into a function. If Steve is close to the positive x edge of the world. Something like the mcImage = mcImage. 1) If your image has an alpha channel then getpixel() will else: return None for the transparent pixels and no block will be mc. A good start is probably to put the mcImage = mcImage. pixel) achieve precisely this. Then it is a simple question of looping over both then you can use live TNT for the red pixels in your image. so to everyone – it is highly unstable and a few careful clicks on the avoid drawing upside-down we subtract the iterating variable TNT blocks will either make some holes in it or reduce it to k from rheight. rheight . This is good. to obtain an index into our palette.getpixel((j. z. x=None.k + y. To change this behaviour one could add an else mcPaletteBlocks[pixel]) clause to draw a default background colour. but you can have a lot of fun by our operations in lexicographical order. z.setBlock line inside the drawing loop getpixel() method.setBlock(j + x + 5.k + y. but we prefer to keep So that covers the code. 46.0) in the top-left corner.convert("RGB") contents of mcimg.k)) horizontal dimension and fix the height at 64.net then you may want to use more than 64 pixels in the pixel = mcImage. If you have a slight tendency towards destruction. mc.py resize first and the quantization last. then it’s good news.y x = playerPos. You might get better results by doing the $ python mcimg.z is used. Then open a not to confuse the quantize() method with transparency terminal and run: information. playerPos = mc. Image If you don’t like the resulting image. for j in range(rwidth): While Minecraft proper has a whole bunch of colourful for k in range(rheight): blocks. then parts of the image will sadly be lost. You might want to give mcImage = mcImage. z=None): precise. five blocks away and aligned in the x direction to be def drawImage(imgfile.y If no co-ordinates are specified. It depends how red your original image was. including five different types of wooden planks and Unlike in Doom.getPos() Getting Steve’s coordinates is a simple task: x = playerPos. 112 | Coding Made Simple WorldMags. 35. Replacing the if pixel < 16: above block with just the two lines of the else clause would mc. then the player’s position z = playerPos.net .getPos() y = playerPos. To do all the magic. drawn. y=None. co-ordinates start with (0. WorldMags. start Minecraft and move Steve to Now we convert our image to the RGB colourspace. rheight . and then force upon it our woollen palette and $ cd ~/mcimg new dimensions.x playerPos = mc. or if x == None: if he is high on a hill. z. dust. and with the following block: using the setBlocks() function to draw the appropriate if pixel == 14: colour at the appropriate place. dimensions of the new image.setBlock(j + x + 5.x z = playerPos. Let’s see how fast he runs without those! stairs. WorldMags.(22.0).152.(57. You can see the whole presentation world comprising most of Great Britain.. Q More dimensions One of the earliest documentations of displaying counterpart has also done similar. palette. z. If you were to proceed custom images in Minecraft:Pi Edition is Dav of Minecraft-Denmark were sabotaged by with this. water will combine to create obsidian.234.61. There are some ] good candidates for augmenting your palette. use the We have hitherto had it easy insofar as the mcPalette following code inside the for loops: index aligned nicely with the coloured wool blockData pixel = mcImage. but Steve can import .81. rheight . O’Hanlon’s excellent 3d modelling project.201. bType.net Coding Made Simple | 113 .ly/1lP20E5. To use this in the drawing loop. Incidentally. though: mcPaletteLength = len(mcPalette / 3) then we can structure our lookup table as follows: Blockname Block ID Red Green Blue mcLookup = [] for j in range(16): Gold 41 241 234 81 mcLookup. so you could expand this tutorial in including a blockified Simpsons title sequence each block representing 50m.obj files (text files with vertex. Read all about it at. Of course. This is slow and painful.net That’s right.25% more colours [gamut out of here .0).setBlock(j + x + 5. go for the ankles. and 16 colours of stained 116.j)) Lapis Lazuli 22 36 61 126 mcLookup += [(41. though parts to jump around on. we also have a temporal rendered. like so: mc. someone (Henry dimensional images are all very well.k)) parameter. tendency to turn into lava/waterfalls. the Pi Edition is a little more restrictive.244. a ly/1sutoOS . To this end and texture data) and display them in Minecraft: and has written Redstone – a Clojure interface the aforementioned Ordnance Survey team has Pi Edition. Another fine example is Martin everything pretty small – the drawing process Survey maps. face Garden) has already taken things way too far has a whole other axis to play with.0). bData) mcPalette = [ … In this manner you could add any blocks you like to your 241. Two. so we need a lookup table to do bType = mcLookup[pixel][0] the conversion. Its Danish that direction. giving Steve some animated gifs at)] Sandstone 24 209 201 152 Thus the list mcLookup comprises the blockType and Ice 79 118 165 244 blockData for each colour in our palette. emerald. to Minecraft which enables movies to be provided. Steve. And we now have Diamond 57 116 217 212 a phenomenal 31.126. but be careful with the lava and water ones: their 36. for the full version of Minecraft. Naturally.Ed] with which to play.getpixel((j. Now that we’re incorporating different blockTypes if pixel < mcPaletteLength: things are more complicated. six kinds of stone. Assuming we just tack these colours on to the bData = mcLookup[pixel][1] end of our existing mcPalette definition.k + y. Cold.217. hard obsidian. lava and 118.0). pleasing orange and blue hues belie an inconvenient 209.165.(24. then you’d probably have to make Stott’s excellent tutorial on displaying Ordnance miscreants.append((35.212 glass.(79. WorldMags. with dimension. it’s perfect material for the next tip instalment in our Minecraft:Pi Edition series. Granted.3] insert random 2 or 4 tile if no move can be done: game over Our task now is to flesh out the English bits of the above code. always just beyond reach. Now we know what we’re dealing with. so our array tiles is comprised entirely of (small) integers. so we can use the exponent rather than the actual value here – for example. but flying around – but don’t worry. So dutifully read the rules in the box – they might text adventure by seem clumsily worded or overly complex. numbering the rows from top-to-bottom and the columns from left-to-right. You’d want to reset the pseudocode – this way we can see the shape of the program player’s position without getting bogged down in details. WorldMags. like so many hopeless lovers. for each row: like a cheat for Sonic the Hedgehog… 114 | Coding Made Simple WorldMags. The first co-ordinate will be the row number. much of the pleasure comes from the touch interface: there is an innate pleasure in orchestrating an elegant and board- clearing sequence of cascades with just a few well-executed swipes. We can represent empty tiles using 0. Python uses 0-based lists. Non-empty tiles will all be powers of 2.net Build 2048 in Minecraft We show you how to implement a crude 2048 clone in Minecraft. column] for x in column + 1 to 2: tile[row][x] = tile[row. for column 0 to 2: if tile[row. 32 will be represented by 5. for each row: but in principle move tiles left. the game has simple rules and is Quick based on blocks. but to do this we need to state how we’re going to represent the board and tiles. you’ll get a taste of the thrilling addition Minecraft functions to talk to those to do with the board and of successive powers of two and as an addict. We’ve gone for an object-oriented Y ou may have not encountered the opium-like approach here. Sometimes it’s easier to visualise the situation using player moves. Lovely. clearing empty space it’s quite a simple You even get a handy help command. You could make The first challenge is to understand the algorithm underlying this project a bit less of a Zork-esque the game.column + 1] = tile[row. This will be done using a 4x4 array called tiles. and the second the column number. you’ll be powerless to abandon the pursuit of the cherished 2048 tile. x + 1] empty tile[row. We’ll worry about how to draw and move the blocks later. but it kind of looks modification. which means that there will be a lot of self moreishness of the Android/iOS game 2048. so tiles[0][0] will be the the top- left hand tile. As such. Be that as it may. we can set about doing some actual Python. after each move. but rest assured writing a control they have been carefully crafted for easy translation to system based on Python.net .column]: double tile[row. it makes it easier for the once you do. tiles[row][j] == 0 and not row_empty: The 2048 game was written by young for k in range(j. accruing else: over 4 million downloads within a week j += 1 of its release in 2014.uk. The fruits of his isMove = True labour proved hugely popular.boardSize): Veewo Studio’s 1024 and conceptually for column in range(self.myfavouritemagazines. but even if The board is there’s only a single space (which will get filled by a new tile) updated twice for there still may be possible moves.tiles[j][k + 1]: com/files/ later with a very cunning trick.append([j. Let’s look at line 2 of our self.game_over = False value blocks justice: eg 128 is represented by black.boardSize): step animation by for k in range(self.randint(1. functions from the random module to help decide the where before and after and what is of the new tile.tiles[k + 1][j]: # check rest of row non-empty self. WorldMags. self.py.tiles[row][k] != 0: row_empty = False 2048: An Open Source Odyssey if self. isMove = False # check col neighbours com/5zEZUfBS for row in range(self. since it was self.linuxformat.1): the pseudocode. Rather if self.boardSize .boardSize): if self.tiles[j][k] == self.2) the command interpreter. if len(empties) > 1: The standard wool colour numbers don’t really do high self. you empties = [] could use this to self.net Things turn out to be simpler if we split off the third pseudocode block into its own function.drawBoard() any available empty tiles. def newTile(self): If you were feeling adventurous. Cirulli’s \ blog says he “didn’t feel good about and self.choice(empties) rnd_n = random. we can cater for them if self. and we also # check row neighbours need to keep track of whether we actually moved anything for j in range(self.boardSize): spacing out the tiles somehow.tiles[j][k] == 0: We were not feeling empties.tiles[row][self.game_over = True implement a two for j in range(self.tiles[row][column] != 0: keeping [the code] private.tiles[row][k + 1] who wanted to see if he could write a self. if self.1): Italian programmer Gabriele Cirulli.tiles[row][k + 1] spirit of open source. this spurred all self.1): while j < self. self.1: if self.boardSize .zip def leftMove(self): or over at:. return isMove For more great magazines head to. self. Python does have a remove() The drawBoard() function is what will actually place the method for lists.tiles[row][column] == self. the same.boardSize . WorldMags. Numbers soared after mobile versions were released the Now we can deal with the situation in the second block in following May. We first Quick need a list of co-ordinates of all the empty tiles. possible after the tile is added is a little awkward: code! We don’t waste time fiddling with empty rows. finding two horizontally-adjacent tiles are simultaneous players at its peak. The game is described as a clone of for row in range(self.boardSize): j=0 for k in range(self. Honest. occupying self. blocks in Minecraft world.boardSize .tiles[rnd_pos[0]][rnd_pos[1]] = rnd_n pseudocode.game_over = False row_empty = True for k in range(j.co.ly/2048GitHub.tiles[row][column] += 1 heavily based off someone else’s work. any tile merging.tiles[row][column + 1] than profit from his success. with up to 50.game_over = False mine2048.” for k in range(column + 1.boardSize): You can find the code at http:// (through the boolean isMove).1] = 0 kinds of modifications and further isMove = True depleted global productivity.boardSize): for j in range(self.tiles[row][self. newTile(). In the self.1): Thus it is available to all at his GitHub. Checking whether moves are Get the so we’ll clear the zeroes from our row the old-fashioned way. We use a couple of a successful move.1] = 0 game in a weekend.tiles[row][k] = self. if there’s tip more than one then it’s certainly not Game Over. in which we move tiles in the row left.boardSize .tiles[k][j] == self. three other possible moves for now.net Coding Made Simple | 115 .boardSize . but it only works on one element at a time.1): similar to the indie title Threes!.k]) adventurous. rnd_pos = random.boardSize .boardSize .tiles[row][k]= self. Also don’t worry about the for k in range(self. applies with strategic substitution of row with populated. If it is all over. Starting with the tile on the is possible after this then it’s Game Over. the Python API from your Minecraft install (e. If there is still need specifics and exactitude. the same algorithm on it at random locations. for example left. which in turn will add a new tile and the player’s position. and all tiles column and right with left.g. A vague idea won’t cut it: we by moving all the numbered tiles left so that any second. if the tile to its right has the same value For other directions. The do_left() function will check if the left move is valid.net . Now we space then another 2 or 4 tile is added randomly semblance of ambiguity.net frustrating. You may have seen this already in if if __name__ == “__main__”: you’ve ever made a Minecraft cannon and used cmd to command2048(). and sometimes Steve’s temper gets the better of him Amazingly. fait with all this.py file from the download. When you enter a command. including setting up the mc object and using it to get updateBoard() function. Any class you write that instantiates this will inherit all Master and commander of its functionality. Initially two tiles are then the left-most of the pair will double in value. The command2048 class’s __init__() method sets up the and if so update the board. shifting the tiles up. free of any empty tiles are on the right of the row. into errors. Also you’ll need to make sure you’ve copied the page 114). This provides a reference point for Rules of the game A key tenet of programming anything is knowing moves. We start the tiles will change. third and fourth rows. We use the standard boilerplate to start We’ll use the cmd module to provide a simple command line things up when the program is executed: interface to our game. then the this process for the second and third tiles from program should behave in a given set of following algorithm applies: For every row start the left. This function is really part of our But if you’ve been following our Minecraft series you’ll be au board class. We even get a help command for free (see picture. This will instantiate our command interpreter when the We shall have a command for initialising the board. Ctrl-D. then we still need a means by which to input our moves. left or right. down. If no move consider how the game of 2048 works. and of course cheekily use raw_input() as a means to wait for the user to we need to render the results in Minecraft world. press Return.cmdloop() control it (You could always try making an image wall. let’s will look at each tile’s situation and decide how in one of the available empty spaces. Repeat what the rules are – knowing exactly how your Suppose the player chooses left. The player can make one of four the rightmost of the pair will vanish. that’s the guts of the code all dealt with. but we decide whether or not the game is up. hence we have a function do_left() which calls the same directory as the mine2048. four program is run with: directional commands and a command to quit. leftMove() function above. Repeat the whole process for the circumstances. The cmd module works by subclassing its Cmd class. with a 4x4 grid which has some 2s and some 4s left.py end of file (EOF) character or the quick way to end a Python Minecraft must be running when you do this. aka the $ python mine2048. ~/mcpi/api/ cmd module will run the function with that name prefixed by python/mcpi) to a subdirectory called minecraft in the do_. via the imaginatively-titled basics. or you’ll run session. It can be WorldMags. p110). With that in mind. to the right will move one position left. up or down. 116 | Coding Made Simple WorldMags. leftMove() We display only the exponents since (a) we’re lazy and (b) it self. once you figure out how to make a structural copy of Spotting wee tricks like this is great because they don’t our two-dimensional list: only make your program smaller (our provided code is def revTiles(self): about 160 lines long.transposeTiles() is exactly the same as reversing the rows.board. for def transposeTiles(self): example making fancy glowing obsidian blocks for the higher oldTiles = [j[:] for j in self. They also make it much for j in range(self. self.boardSize): the Up move by transposing our tiles array (replacing each for k in range(self.mc. so not having another three very similar self. self. WorldMags. but feel free to add to it. self.z.board. self.board. The leftMove() function is by far the most for k in range(self.tiles[j][k] = oldTiles[j][self.revTiles() works.net Coding Made Simple | 117 . move = self. if move: Change it if you like. moving the tiles to Note that this is the same as transposition.tiles] can sap hours from your life). and plus and minus signs. we also have a printTiles() self. an elephant in the room.board.board.boardSize . Note that our row[0] is the top one. and then reversing the rows again. But that would be silly.tiles[j][k] = oldTiles[k][j] The only way is Left Similarly we can complete our directional command set.leftMove() inefficiency here at Future Towers.board.revTiles() function which draws the board at the command terminal. Q You can change the boardSize variable. going self. right move the left. as everything will be def do_right(self. Make sure you’re not looking So then we can make implement the (ahem) right move. then performing our self.x + k. left move. 35.boardSize): self. observe that moving the tiles to the right self. We still haven’t dealt with making the Down move by a combination of transposition.boardSize): down. subtracting j from our y co-ordinate.y .boardSize): easier to debug.revTiles() looks nicer if most things occupy just a single character.k .setBlock(self.revTiles() up approach. First. which we will arbitrarily decide to be three blocks away in the z direction.transposeTiles() through all the incorrect combinations until we find one that self. But wait.args): backwards. Let us take a more grown. for k in range(self.1] functions is a considerable benefit. and we don’t tolerate such move = self.boardSize): row by its respective column). WorldMags. so we count for j in range(self. We could do this by row reversal. Reversing the rows and transposition. Transposition is tiles[j][k]) almost exactly as easy as row-reversal: This works reasonably.tiles] valued ones.board. self. For convenience.j. but it’s a bit of a different game in a larger arena.net drawing our board. leftMove() and transposing back again. We can construct for j in range(self. not bad for a whole mini-game that oldTiles = [j[:] for j in self.updateBoard() The drawBoard function uses different colours of wool else: (blockType 35) to represent the content of our array tiles: print “No move” def drawBoard(self): But the symmetry does not stop there. in the following way: at the back of the board. 75% of the moves allowed in 2048. is easy. row reversal and transposition: copying the leftMove() function and painstakingly changing def do_down(self.board.args): all the ranges and indices. though.boardSize): complicated. WorldMags.net WorldMags.net WorldMags.net Coding projects Exciting and interesting coding projects for you to write Python 3.0 primer ..................................................120 Build a Gimp plug-in .........................................124 Image filters .............................................................................128 Sound filters ............................................................................134 Twitter scanner .............................................................138 Build a GUI 142 ................................................................................... WorldMags.net Coding Made Simple | 119 WorldMags.net Python: Dive into version 3.0 Join us as we investigate what is probably one of the least loved and disregarded sequels in the whole history of programming languages. Linux Format, certain authors, whether by habit, ignorance or affection for the past, continue to provide code that is entirely incompatible with Python 3. We won't do that in this article. We promise. So let's start with what might have been your first ever Python program: print 'Hello world' Guess what – it doesn't work in Python 3 (didn't you just promise...?). The reason it doesn't work is that print in Python 2 was a statement, while in Python 3 print is a function, and functions are, without exception, called with brackets. Remember that functions don't need to return anything (those that don't are called void functions), so print is now a void function which, in its simplest form, takes a string as input, displays that string as text to stdout, and returns nothing. In a sense, you can pretend print is a function in Python 2, since you can call it with brackets, but a decision was made to offer its own special syntax and a bracketless shorthand. This is rather like the honour one receives in mathematics when something named after its creator is no longer capitalised – for example, abelian groups. But these kind of exceptions are not a part of the Python canon ("Special cases aren't special enough to break the rules"), so it’s brackets all the way. On a deeper level, having a function- proper print does allow more flexibility for programmers – as ay back in December 2008, Python 3.0 (also a built-in function, it can be replaced, which might be useful if W known as Py3k or Python 3000) was released. Yet here we are, seven years later, and most people are still not using it. For the most part, this isn't because you're into defying convention or making some kind of Unicode-detecting/defying wrapper function. Your first Python program should have been: Python programmers and distribution maintainers are a bunch of laggards, and the situation is very different from, for example, people's failure/refusal to upgrade (destroy?) Windows XP machines. For one thing, Python 2.7, while certainly the end of the 2.x line, is still regularly maintained, and probably will continue to be until 2020. Furthermore, because many of the major Python projects (also many, many minor ones) haven't been given the 3 treatment, anyone relying on them is forced to stick with 2.7. Early on, a couple of big projects – NumPy and Django – did make the shift, and the hope was that other projects would follow suit, leading to an avalanche effect. Unfortunately, this didn't happen and most Python code you find out there will fail under Python 3. With a few exceptions, Python 2.7 is forwards-compatible with 3.x, so in many cases it's possible to come up with code that will work in both, but The Greek kryptos graphia, which translates as ‘hidden still programmers stick to the old ways. Indeed, even in writing’, followed by a new line using the correct script. 120 | Coding Made Simple WorldMags.net this will require many UTF-16. Now when you try to print the lowercase character pi. via a system called Punycode. ligature Some of these characters are invisible teletype the problem elsewhere. Instead. Revolution box. forms and more. WorldMags. then plain ASCII wouldn't help. accounts for as many as possible of the set of backwards compatible with ASCII). which just 03c0 in hex notation. even those The PyStone benchmark will likely be slower in Python 3. slicing or reversing a string. To understand them. other languages. This accounts for over 100. it’s fairly common in answer: Unicode. both as a storage used character set (and the related (hence the divergence of codepoints and byte encoding standard and for internally processing Windows-1252) contains almost all the accents encodings). but there are many other. In the past. but it can live happily sharing it with could do the same. by default. end=" ") print ('one line') does just that. above) that covers all the bases.net Coding Made Simple | 121 .000 which gives you 128 characters to play with. Don’t be a Py3k refusenik without first trying your code. although internally these are >>> type(pi) all still encoded as ASCII. Most of the world doesn't speak English. distro. As a result. more than 256 characters. Print in Python 3 A significant proportion of Python programs could be made compatible with 3 just by changing the print syntax. but the same won’t regions that do tend to use different sets of accents to be true for all code. all the wrangling. Obviously. sometimes identically. but doesn't really solve characters. which uses two bytes for some emerged. This widely. You could use one of the The unicode type should be used for textual intercourse – to use Python 3 alternative encodings. most of the world doesn't even use a Latin character set. but in general you needed the Unicode codepoint for the lowercase Greek letter pi is in tandem with to turn to a word processor with a particular font. sometimes called Latin-1. we use the end parameter. bidirectional display order. Currently there are two codes (ASCII originated in the 1960s). things will go wrong. but it's for a greater good. are converted to whichever encodings have emerged. then sad news: this no longer works. of few distributions it.net The Unicode revolution Traditionally. away with one character encoding to one byte has been widely adopted. For example. For any modern tip assigned a byte encoding. The most notorious of these is ISO. things that could go wrong. In fact. if we were to try this on a terminal without modules still won't play nicely with it. which uses one byte for we've counted the familiar alphanumeric encoding (or maybe a couple of them) that common characters (making it entirely characters. and 256-character extensions of the ASCII encoding wish to type. tabulating and its predecessor did not do the latter. as well Fortunately. there isn't really much room left. and we have an each character is encoded as a 7-bit codepoint. We can even have ϖ Unicode in our domain names. but will behave a scenario by starting Python with: unpredictably for codepoints above 127) or they can be of $ LC_ALL=C python type unicode. in which as the characters used in the romanisation of other rigmarole has been done. Thankfully. tests. You can simulate such be of type str (which handles ASCII fine. if you knew the people you were finding the length of. text was encoded in ASCII. As a result. Strings in Python 2 can Unicode support. but its >>> len(pi) handling of it is done fairly superficially (Unicode strings are 1 sneakily re-encoded behind the scenes) and some third-party However. besides the ASCII standard. we now have a the Python console like so. we must first be au fait with what really changed in Python 3. Unicode 8859-1. which by default is a new line. and each codepoint is and LC_* environment variables in Linux). so we'll have to do characters and four bytes for others. far less trivial. So we can define a unicode string from its predecessor moves the problem elsewhere. and up to Because we like things to be bytes. If you were a fan of using a comma at the end of your print statements (to suppress the newline character). several characters anyone on earth might conceivably four bytes for the more cosmopolitan ones. but it's definitely not something Arch Linux is one if you wanted to share a document with foreign characters in you should take for granted. the western hemisphere. this is probably UTF-8. Strings of type str are stored as bytes and. and once The correct solution would be a standard encodings in use: UTF-8. provided our terminal can handle (available in the widely adopted standard: Unicode (see The Unicode Unicode output and is using a suitable font: python2 package). decorate the characters. For example: print ('All on'. and is >>> pi = u'\u03c0' backwards compatible with ASCII and (as far as codepoints >>> print(pi) are concerned) its Latin-1 extension. <type 'unicode'> Python 2 is far from devoid of Unicode support. Each grapheme (an abstraction of encoding your system's locale specified (through the LANG Quick a character) is assigned a codepoint. The main raison d’être of Python 3 is that required for the Latin-scripted languages. you will WorldMags. numerous diverse and incompatible character when printed to a terminal. print ('Hello world') which is perfectly compatible with Python 2 and 3. Python 3. We can escape type entirely. If you're reading Unicode text files. you can no longer use the ugly <> comparison operator to test for inequality – instead use the much more stylish != which is also available in Python 2. Python 3 does away with the old unicode encodes to the two bytes CF 80 in UTF-8. UTF-8 byte representation directly. but it really depends but it will suffice to simply accept that the pi character on your purposes. which could result in need to rewrite from the ground up how the language dealt tears.coding: utf-8 -*- will try and convert strings of type unicode to ASCII (its The main driving force for a new Python version was the default encoding) in these situations.0). the 2to3 tool. Shalom aleikhem. The third line uses the explicit floor arguments is a float (or complex). the numerator is a float and are ints. when printing to a file or a pipe. 1. Also. So we can also get a funky pi character by using its with strings and their representations to simplify this process. and returning an int. 1.7. at. There are rules for Some argue that it fails miserably (see Armin Ronacher's rant converting Unicode codepoints to UTF-8 (or UTF-16) bytes. brings about many other changes besides all this Unicode malarkey.ly/UnicodeInPython3). some of them provide new features. This helpful chap runs a predefined set of fixers The division bell One change in Python 3 that has the potential to two ints. For example. here's an second example. if you have Unicode strings in corresponding to how the string is encoded on the machine.coding decorator above) and the new bytes >>> type(strpi) object stores byte arrays. doesn't need to be compatible with 2. but this is trivial via the str. This means the / operator is now as close to >>> 3. then the >>> 3. In the changed: if both numerator and denominator operator / is different. but the longer cause harm. bottom p120). otherwise a float is returned with the >>> 3/2 returning what you'd intuitively expect half of correct decimal remainder. Python 2 # -*. But wait. however.net run into a UnicodeEncodeError. The str type now stores Unicode understand bytes: codepoints. 122 | Coding Made Simple WorldMags.net . your code. functions can now be passed keyword-only arguments. The latter mathematical division proper as we can hope. you'll need to add the appropriate declaration at This is what you should use if you're writing your strings to the top of your code: disk or sending them over a network or to a pipe. Python is trying So ϖ apparently now has two letters.encode() 2 method. other. thus in this case behaviour of the classic division operator has flummox is that the behaviour of the division the operator stands for integer division. Automating conversion with 2to3 For reasonably small projects. the language's default encoding is UTF-8 (so no >>> type will need to be converted to bytes if it's to be used for >>> len(strpi) any kind of file I/O. beth.decode() method (see the picture for details. even if they use the *args syntax to take variable length argument lists. since everything about Python 3 is now these with an \x notation in order to make Python Unicode-orientated.//2 depending on the arguments. Also. so its and issues involving unexpected ints will no which shows the first command operating on behaviour is the same in Python 3. and catching exceptions via a variable now requires the as keyword. Essentially. gimel… The 2to3 program shows us how to refactor our Python 2 2 code can be automatically made Python 3 compatible using code for Python 3. instead use str. If at least one of the 1 three to be. and some of them force programmers to do things differently. and those that aren't going to encounter any foreign characters. so don't use the unicode type You'll also have to handle your own conversions between str for these operations. Python 2 also tries to need to have all kinds of wrappers and checks in place to take perform this coercion (regardless of current locale settings) account of the localisation of whatever machine may run it. There You can also use the -w option to overwrite your file – don't is another module. using the -f option. says that Python For example. is a version 3. An example is When Python 3. which you can verify the unichr() function is now chr(). This was not These two aren't entirely compatible. or the bottleneck features and syntaxes have already been backported to 2.net Coding Made Simple | 123 . and __future__ doesn't your fingers to add parentheses. module. Using it can be as simple as directive. with the goal of emitting bona fide behave like a standard module – instead it acts as a compiler Python 3 code. and the print line is reworked. because Unicode is now for yourself using the PyStone benchmark. It’s target one specific Python version. Q WorldMags. it drudgerous task.net The popular matplotlib module has been Python 3 compatible since v1. because searching and in order to clean up the code base. But Another option is to create 'bilingual' code that is compatible don't be misled. machine in the office. for all your graphing and plotting requirements.3GHz processor would suggest. p122) shows the changes to a simple three-line program – Unfortunately. implicit. PyStone tests various Python internals. on would be nice if performance had since been improved. WorldMags.5 (which was released in September 2015). Using 2to3 can version and many special-case optimisations were removed save you a whole heap of effort. which isn't part worry. array access).7 will be supported until 2020. so you won't be alone.org) to speed up code that is amenable to new features and learning the new syntax. math. but that's no excuse to using the following: postpone learning the new version now. or unicode_literals to make strings Unicode by default. $ 2to3 mypy2code. this hasn’t been the case. this middle ground is very important to test your code in both versions to get a more useful when you're porting and testing your code. You might accurate picture. because speed was not really a priority for the new be necessary in order to successfully migrate. Many Python 3 C translation (loops. the author of Python. on your Python 2 code. so some tweaking might surprising. Guido van Rossum. and many more can be enabled using the __future__ module. even if it uses % to We tested it (see the screenshot on p121) on an aging format placeholders.py We can likewise import division to get the new style division. confusingly called future. which in this case provides the modern print syntax. for instance. you can get the new-fangled print syntax by 2. Now that we're up to replacing print statements manually. it was generally regarded buffer which will replace all buffer types with memoryviews.0 was released.2. but can help ease transition issues. You can always use Cython (maintained at need to rework a few things in Python 2 while still enjoying the. The pictured example (over on the left. which will output a diff of any changes against the original file. which has now come back from the dead twice and hence possesses supernatural powers far Parlez-vous Python Trois? beyond its dusty 2. specify them explicitly. While you should really only which your code may or may not make extensive use. Half the work is retraining This is used with the from in this way. as being about 10% slower than its predecessor. of with both Python 2 and Python 3.7. Some fixers will only run if you of the standard library. Python 3 adoption is >>> from __future__ import print_function increasing. it will be backed up first. 'Layer0'. If type data. Note that in Python.RGB. ultitude of innuendoes aside. it is there.0) On Linux. since an image without layers is a pretty ineffable object.gimp_context_set_brush('Cell 01') 124 | Coding Made Simple WorldMags. Scheme). then we provide a list of the form [x1. though frankly adjusting colours. though.8. languages.gimp_image_insert_layer(image. height and menu. the hyphens in procedure names are replaced by underscores. gimp_pencil(). Hence our example draws a line from (80. xn. You can look up more information about these procedures in the Procedure Browser – try typing gimp-layer-new into the search box. If it’s not there. which and Mac friends will have these included as standard since requires parameters specifying width. GRAY or INDEXED).gimp_pencil(layer. then go ahead and click on it. there exist them in Python through the pdb object. gimp_layer_new(). You can check everything is ready by starting up (RGB. which works Gimp and checking for the Python-Fu entry in the Filters on a previously defined image and requires width. which is twice the number of points because each point has an x and a y component.gimp_layer_new(image. Then throw the following at the console: pdb. a nicely centred line. The Browse button in the console window will let you see all of these procedures. Mercifully.240. layer = pdb. as well as a name.net .[80.None. Perl or Python.200. takes just the layer you want to draw on. which is probably most accessible of all these then displaying the image. and gimp_display_new(). If you wanted to be hardcore. what they operate on and what they spit out. most packages will ensure that all the required pdb.gimp_display_new(image) Python gubbins get installed alongside Gimp.layer. brushes and so forth are in the PDB too: doing this is unlikely to produce anything particularly useful. you’ll need to check your installation.100. which will display an image. and you will see all the different combine modes available. The syntax specifying the points is a little strange: first we specify the number of coordinates. your Windows So we have used four procedures: gimp_image_new(). so even if you have no prior coding experience you image = pdb. adding a layer to it. and last in this list.100 . since hyphens are reserved for subtraction.200. just like you could draw with the pencil tool. Gimp enables you to can do is registered in something called the Procedure M extend its functionality by writing your own plugins. y1. then you would write the plugins in C using the libgimp libraries. opacity and combine mode. Everything that Gimp You need to add layers to your image before you can do anything of note.4. without even a word about Gimp masks. First select a brush and a foreground colour that will look nice on your background. Tcl. let’s see how to make a simple of your dreams in Gimp’s own Script-Fu language (based on blank image with the currently selected background colour. yn]. with a image.RGB) should still get something out of it. WorldMags. prompt (>>>) hungry for your input. …. The procedures for selecting and You can customise lines and splodges to your heart’s content.gimp_image_new(320. softcore APIs to libgimp so you can instead code the plugin As a gentle introduction.RGB_IMAGE) Get started pdb.100]) Great.320. This tutorial will deal with the This involves setting up an image. pdb. The first parameter. If all goes to plan this gimp_image_insert_layer() to actually add the layer to the should open up an expectant-looking console window.100) to (240. We can access every single one of pretty off-putting or rage-inducing.100). but how do we actually draw something? Let’s start with a simple line. height and image type version 2. Draw the line All well and good. The search box will still understand you if you use underscores there.net Python: Code a Gimp plugin Use Python to add some extra features to the favourite open source image- manipulation app. but that can be Database (PDB). and hue suited to these fancy brushes than the hard-edged pencil. For simplicity. the highlights. reminiscent of lens flare. a more pleasing result may caused by light sources outside of the depth of field. ‘Bokeh’ derives from a Japanese word meaning blur layer remains untouched beneath these two. we have just used the defaults/current settings here.gimp_context_set_foreground('#00a000') in the highlights of the image. The bokeh plugin pdb.gimp_context_set_brush_size(128) effect you get in each case is a characteristic of the lens and has created pdb. one may also see a pleasing If you have the brush called ‘Cell 01’ available. If you don’t. blur radius. WorldMags. and in photography refers to the out-of-focus effects opacities of these two new layers. Download the code pack from ‘bokeh discs’ and another with]) the aperture – depending on design.2. and saturation adjustments.net Applying our pdb. and a advanced plugin for creating bokeh effects in your own layer with a blurred copy of the original image. then the polygonal and doughnut-shaped bokeh effects. It often be achieved. By adjusting the or haze. which we will assume to be single- gimp_brushes_get_list(‘’). a path on their image. you will see that you can configure “Our plugin creates a layer with gradients and fades too.ly/TMS12code and you will find a file linesplodge. a part of the results in uniformly coloured. we’ll stick with just circular ones. disc-shaped artefacts image should remain in focus and be free of discs. For this bokeh effect in above code will draw a green splodge in the middle of your exercise. so it may WorldMags. a blurred copy of the image” py which will register this a fully-fledged Gimp plugin. The paintbrush tool is more layered. replete with a few tweaks. blurred. They will specify disc diameter. then you’ll get an error message.[160. For more realistic bokeh effects. The original pictures. You can Our plugin will have the user pinpoint light sources using get a list of all the brushes available to you by calling pdb. canvas. and if you look in the procedure browser at the function gimp_paintbrush.gimp_paintbrush_default(layer. The result will be two new layers: For the rest of the tutorial we will describe a slightly more a transparent top layer containing the ‘bokeh discs’.net Coding Made Simple | 125 . x1. It is recommended to turn the blur parameter to zero a number of options. This means Having extracted the point information.net . height. 4. Here the second argument stands for the Here are our discs. they are quite handy strokes. The length of the list of points is our script in Gimp. "bokeh".radius. blur_layer. Provided the drawn. None.y0.y and select the average colour. in fact. Layers and channels Python lists start at 0.gimp_image_insert_layer(timg.. then further applications of our as two variables x and y. since it may not be indicative of its surroundings.gimp.gimp_image_insert_layer(timg. but don’t worry – all you need to understand is that modes and other arcana. Details are in the box There are a few constants that refer to various Gimp-specific below. which would rely on more home-brewed RGBA_IMAGE. 5. each describing a section of the path. so that we get require at least an image and a layer to work on. extracting the coordinates of each component point user doesn’t rename layers. 0) our circle by bucket filling a circular selection. They are easily identified by their the main for loop will proceed along the path in the order shouty case. This is slightly non-trivial since a pdb. disc. we use the range() function’s step parameter to things to have around because so many tools We’ll assume a simple path without any curves. 0) we start – somewhat counter-intuitively – by drawing a black For many. Rather than use the paintbrush tool. The PDB function parameters and still have all the flare-effect discs on the same for doing just that is called gimp_image_pick_color().y0. As you can imagine.net be fruitful to erase parts of the blurred layer. For our blur layer. so there is only a single stroke from which to the xs in positions 0.x1. tip pdb. The bokeh layer is created much as in the previous example.x0. It has layer. 8 and the ys in positions So handy.gimp_layer_new(timg.y1. diameter) and changes of direction and allsorts. After initialising a few de rigueur variables. bokeh_layer. x . our next challenge that one can apply the function many times with different is to get the local colour of the image there. Since for j in range(0. Bring a bucket Quick blur_layer = pdb.. None.. we don’t need to mention this stroke as gpoints. CHANNEL_OP_ general path could be quite a complicated object. 100.4): them to your function. the object contains a series of hold curvature information.layers[0]. strokes.1) To draw our appropriately-coloured disc on the bokeh layer. but uniform colour works just fine. Our particular call has the program sample within blurring the already blurred layer. Paths. mirroring the dialog for the Colour after the first iteration. with curves REPLACE. width. original image and add a transparency channel. NORMAL_MODE) all possible users having consistent brush sets. If you’re feeling crazy you could add blends or gradients.gpoints[1]. In the code we refer to 1. a 10-pixel radius of the point x. because in other settings the list needs to and drawable) at the time our function was More specifically. twice. since otherwise the user would just be Picker tool. points. This list takes the form variables timg and tdraw. plugin will not burden them with further layers.gimp_layer_copy(timg. Each point is counted active image and layer (more correctly image much that can be applied equally well to both. the list of points is You will see a number of references to make up the class called drawables – the accessed as gpoints[2].]. WorldMags. many bokeh_layer = pdb. we copy our pixel. we set about This is preferable to just selecting the colour at that single making our two new layers. images and drawables Paths are stored in an object called vectors. 9. To avoid repetition.y1. which is really a tuple bequeathed to us in the second entry of gpoints them – it is assumed that you want to pass that has a list of points as its third entry.radius. vectors. we will make plugins.gimp_image_select_ellipse(timg. check out pdb. diameter. called.org from the user’s chosen path. 126 | Coding Made Simple WorldMags. that when we come to register wrest our coveted points. y . These represent the abstraction is warranted here since there is [x0. The selection is the Gimp Plugin Our script’s next task of note is to extract a list of points achieved like so: Registry at http:// registry. increment by 4 on each iteration. gimp_context_set_foreground(color) After we apply pdb. copyright. blur.gimp_layer_set_mode(bokeh_layer.8/ proc_name.” myplugin.net Coding Made Simple | 127 . true for any Gimp script. The menupath parameter specifies function as it appears in the code.False. date.g. such as in our example. The your plugin will be called in the PDB.0. Q Registering your plugin In order to have your plugin appear in the Gimp params. on some level at least. lightness. The dimensions are specified by giving the top left corner of the box that encloses the ellipse and the said box’s width.0.100. And just in case any black into a single undoable one.plug_in_gauss_iir2(timg. so we black it up first. GRAY*”. blur_layer. and survived the bucket fill. But pdb. WorldMags. #! /usr/bin/env python Python plugins have their own branch in the Finally. softly Finally we apply our hue and lightness adjustments. pdb. 0. since You could add any further scripts you come up with to this otherwise we would just blur our most-recently drawn disc.100.plug_in_colortoalpha(timg. save this file as (say) register( case “<Image>/Filters/Artistic/LineSplodge. image. author.“Draws a line and a splodge” of images the plugin works on. group the operations the bokeh layer to Soft-Light mode. results. we set its menupath to opacity of the that part of the image should stay in focus.0) And now the reason for using black: we are going to draw the discs in additive colour mode.ADDITION_ the filter.’ so that if it registers layer will bring work on this layer later so that it is less opaque at regions of correctly you will have a My Filters menu in the Filters menu. Critics may proffer otiose jibes about the usefulness of saturation) this script.gimp_edit_bucket_fill_full(bokeh_layer. possibly even in a better way.False. things MODE.True. imagetypes specifies what kind plug-ins for Linux (ensure it is executable with blurb. bokeh_layer. We said them. Softly. additive colour doesn’t really do anything on transparency. “python_fu_linesplodge” would suffice. we use the Color-To-Alpha plugin to reset any changed tool settings” squash it out. in a manner which vaguely resembles what goes on in photography.gimp_edit_bucket_fill_full(bokeh_layer. function is just the Python name of our from gimpfu import * taxonomy. and where To ensure that Gimp finds and registers your # code goes here your plugin will appear in the Gimp menu: in our plugin next time it’s loaded.py) or %USERPROFILE help. The trouble is. Once we’ve drawn all our discs in this way. it is necessary to define it as a Python function) # “myplugin” special Python-Fu types here such as PF_ function and then use the register() function. back some detail. In our case general form of such a thing is: is actually automatically prepended so that all (PF_IMAGE. We feather this selection by two pixels. This means that regions of overlapping discs will get brighter. so that lower layers are illuminated beneath the discs.0. but also to the fact that the current selection should be replaced by the specified elliptical one. you may want to ‘<Image>/Filters/My Filters/PyBokeh. In the register() function. and then all the black is undone by our new additive disc.0. and you’d have to be housekeeping to take care of.gimp-2. 0. pdb.gimp_hue_saturation(bokeh_layer. The list params replacing the version number as appropriate. specifies the inputs to your plugin: you can use menus. 2) pdb.py in the plugins folder: ~/.. and restoring to preserve the colour addition. The results list describes in an appropriately laid out Python script.True. WorldMags. Then we bucket fill this new selection in Behind mode so as not to interfere with any other discs on the layer: pdb. We deselect everything before we do the fill. such as “RGB*.0) any tool settings that are changed by the script. chmod +x myplugin. just to take the edge off. 0. You error-prone – you’d have to keep a note of the coordinates will see from the code on the disc that there is a little bit of and colour of the centre of each disc. menupath. 0.BEHIND_ MODE. we do a good to tidy up after yourself and leave things as you found Changing the Gaussian blur – if requested – on our copied layer. ‘python_fu’ what your plugin outputs. imagetypes.. image.8\plug-ins\ for Windows users. The example images show the results of a pdb. interest. “LSImage”) would suffice. main() COLOR and PF_SPINNER to get nice interfaces The tidiest way to do this is to save all the code The proc_name parameter specifies what in which to input them.. and indeed it would be entirely possible to do pdb. SOFTLIGHT_ everything it does by hand. #.0. It is always get a bit blurry.gimp_selection_feather(timg. and then set the foreground colour to black. if anything. MODE) That is. '#000000') this manual operation would be extremely laborious and And that just about summarises the guts of our script. blur) couple of PyBokeh applications.gimp-2. namely grouping the whole incredibly deft with your circle superpositioning if you wanted series of operations into a single undoable one. menu to save yourself from cluttering up the already crowded if blur > 0: Filters menu. def myplugin(params): what kind of plugin you’re registering. or simply “” if it doesn’t operate on any %\. # e..gimp_context_set_foreground('#000000') pdb.0.net number 2. and set “To finish. png") This opens an image file named screenshot.size.resize((int(width/2). let’s doesn’t support Python 3. As with all Python libraries. if you want to see the size of the image. The open() function determines the format of the file based on its contents. we first assign the size and install Pillow . and has evolved to be a better. you can call the ‘format’ attribute. The library has a bunch of modules. To view the new image. remember to open it up first: scripts to act on a disk full of images and carry out extensive >>> newImage = Image. you can use the available attributes to examine the file. >>> newImage. you can open. With Pillow.format) (1366. Note creating images from scratch. The resize method works on an image object on the PIL code. more logically named variables. While it can be done manually. Remember to specify the appropriate path to an image on your system as an argument to the Image.png. Pillow is a fork of PIL that’s based modify them. Many of the existing PIL >>> reducedIM = im.net Pillow: Edit images easily You can save time and effort by using Python to tweak your images in bulk.open("screenshot. it returns an instance of class Image. you need to install the library with sudo pip In the interactive Python shell. was a popular and powerful Python library for handling Basic image manipulation images.jpg”) modifications based on a complex set of rules. Many of width of the image by extracting them from the tuple into the commonly used functions are found in the Image module. But it hasn’t been updated for over half a decade.png’) minimal or even no modifications.show() The Python Image Library. more friendly version of PIL.size similarity of the API between the two. >>> reducedIM. One and height: of the best advantages of Pillow for existing PIL users is the >>> width. The method accepts a two-integer tuple for the new width manipulate and save in all the popular image file formats. height = im. that the resize method accepts only integers in its tuple 128 | Coding Made Simple WorldMags. make sure you replace the following string ython’s multimedia prowess extends to images and with an appropriate path to your image file. im. use the save method of the Image class. 768) RGB PNG The size attribute is a 2-tuple that contains the image’s width and height in pixels. using Python enables you to automate the process by easily writing >>> im. and So now that we know how to open and save images. im. For example.open (“changedformat. >>> print (im. either reduce both values by half. Launch the Python interpreter and type: >>> from PIL import Image >>> im = Image. commonly referred to as PIL. WorldMags. If the file can’t be read.mode.save(‘reduced. int(height/2))) code that you’ll find on the internet will work with Pillow with >>> reducedIM. RGB is the mode for true colour images.open method.jpg”) Use the show method to view the image.show() To get started. an IOError is raised.net . begin your code by importing the Pillow modules you want to use. such as: from PIL import Image You can now open an image with the Image. For saving an image. while calling the resize method.open method. Again. processing other images. We then divide these by 2 to You can create instances of this class in several ways.save(“changedformat. Now when you have an Image object. or The result is an image that’s half the size of the original. P includes mechanisms for manipulating snapshots in a variety of ways. by loading images from files. modern and and returns a new Image object of the specified dimensions. otherwise. them. common trick is to create thumbnails: >>> size=(128.transpose(Image. where green and blue. just like the previous example.0. and a colour these values as integers. together with the adjustments.rotate(90). and the RGB system is the The total number of RGB colour values is coloured pixels.9). you can use the >>> im. which is the number of degrees to rotate the image by and.1) at the lower-right. increase the brightness We start by defining a tuple with the dimensions of the by 20% with: thumbnail.777.FLIP_LEFT_RIGHT). which the display required to represent the two colour values. height . The computer represents white monitors. only a single bit of memory was accessible by (x.Brightness(im).transpose(Image.show() methods in the ImageEnhance module.show() For more advanced image enhancement. Early colour monitors could support the display Image.BLUR).save(‘OnItsSide.rotate(180). for example. (100. WorldMags.strftime(“%A. >>> ImageEnhance. replace the call to an image object and can be used to make various the show method with the save method. equal to all the possible combinations of three (0.rotate(230. 0) at the upper-left corner of an image to RGB stands for the colour components of red.enhance(-1. b). grey is When an image is loaded. the bits from the file into a rectangular area of represents a colour. Another colour balance.show() >>> im. which describe the coordinates of the image you’re interested in contains several enhancement filters.filter(ImageFilter. The display area of the monitor is made an RGB value of 0. We’ve saved ourselves some effort by calling show() directly in the first two statements to view the image.show() >>> im. green is 0. to which the human retina is of its wide range of colours. such >>> top = int(height/4) as blur to apply a Gaussian blur effect to the image: >>> right = int(3 * width/4) >>> im. such as: will first have to import it with: >>> width. Pillow’s crop method can help you with. perhaps reduce contrast and save the results: changes the original image itself.127 and yellow is 255. you should component.5). When rotated at these two angles.right. The rotate method takes a single argument (either integer or float). and save() in the third to save the rotated image.show() >>> from PIL import ImageEnhance >>> im.png’) You can now use it to. you and discard the rest. so lines and shapes on this new image with Pillow.1. without modifying the original image. So black has distinct colour value is 24. You can also create a mirror version of the image.save(‘reducedContrast. The module returns Also.size >>> from PIL import ImageFilter >>> left = int(width/4) You can now use the various filters of the ImageFilter.127. a computer maps up of coloured dots called pixels. >>> newImage=ImageEnhance.show() Remember that unlike the previous methods. %d %B %Y %I:%M%p”) we’ve used Python’s datetime module to timestamp an image. value consists of the tuple (r. To use this module. returns a new Image object. The value 255 represents the represent each colour value. Each pixel 127. WorldMags. Pillow maintains its original dimensions. or 16. to save the flipped image. hardware translates into the colours we see.5 degrees. 200). values: 256 * 256 * 256. using the transpose method: >>> im. Note that if the image is rotated to any angle besides 90 or 270. y) coordinates.jpg’) >>> im. whereas the value 0 represents the the total number of bits needed to represent a understand how computers read and display total absence of that component. Pillow also includes a number of methods and Yet another common image-editing task is cropping modules that can be used to enhance your images. the second by 230.0.save(‘thumbnail. Because (width .enhance(1. including changes to contrast.255.0. so 8 bits were needed to a new white image that’s 100 pixels wide and through 255.net argument. just like resize .filter(ImageFilter.128) Dressing up images >>> im.net Coding Made Simple | 129 . To begin portions of an image.show() >>> bottom = int(3 * height/4) >>> im. swaps its width and height.thumbnail(size) Begin by importing the ImageEnhance module with: >>> im.bottom)).datetime. RGB is known as the width and height are the image’s dimensions in sensitive. unique colour value.show() Image processing 101 To manipulate images effectively.new(‘RGB’. and then use it to create the thumbnail in place. These are mixed together to form a true colour system.png’) The first statement rotates the image by 180 degrees. height = im.5) In addition to the more common image-editing >>> newImage.FLIP_TOP_BOTTOM). the image With datetime.crop((left.Contrast(im). which is why we’ve wrapped the reduced dimensions in an init() call. The coordinates range from most common scheme for representing colour.255.216.0. and the third by 90 degrees. ‘white’) creates Each colour component can range from 0 of 256 colours.now(). You can similarly change the orientation of the image by rotating it by a specified degree with the rotate method. Each colour 200 pixels long. You can now draw all kinds of maximum saturation of a given colour component of an RGB colour requires 8 bits. An image consists of a width and a height. thumbnail Or. >>> im. In the old days of black and pixels. sharpness and name of a new image file.top. g.jpg’) techniques.BLUR).save(‘blurred. let’s take a look at the ImageFilter module. Modify the statement to include other >>> im=Image. (IMwidth . is done via the ImageDraw module.endswith(‘. if not (filename. text function to draw a string at the specified position that points to the top-left corner of the text ( 150x150 in our script). however.ttf”. The last bottom variables to 75.size centre of the original image.join(‘withLogo’. we use the truetype function in the ImageFont module. and the Y axis two arguments that’ll determine the location of the top-left would be the height of the image minus the height of the logo. For ease of use. The above statements help cut logoIm = Image. draw. PIL can use: bitmap fonts or OpenType/TrueType fonts.net . For os.open(‘screenshot. height = im.png’) or filename.text((150. we use the draw. which is the exact centre of the original image.size >>> width.png’) image formats.fill=(128. This.paste(logoIm.jpg.paste(croppedIM.255.size That’s all the info we need to paste the logo and save the >>> left = int(width/4) resulting image in the directory we’ve just created: >>> top = int(height/4) print ('Adding the logo to %s’ %(filename)) >>> right = int(3 * width/4) im. pastes an image on top of another one. You can. In case we want to place the logo in the bottom-left The paste method takes the X and Y coordinates as the corner.show() coordinates of the top-left corner for placing the logo.save(‘croppedImage. So continue it’s best to make a copy of your image and then call paste on The additional if statement ignores files that don’t end that copy: with a . Remember. (0. int() wrapper makes sure the returned values of the Next we’ll loop over all the images in the current directory dimensions are integers and not floats. First. you can paste a from PIL import ImageDraw.logoWidth.path.copy() anything but image files in the directory. To load a OpenType/TrueType font. Simple image editor There are several other uses for the Pillow library. however.crop((left. draw = ImageDraw. Finally. logoHeight = logoIm. and the right and image and extracted its dimensions into a variable.paste(logoIm. with a for loop: Then there’s the paste method.crop((left. IMheight = im. modify the script Perhaps the most popular use of the paste method is to to import additional libraries: Tkinter is a watermark images. corner of the image being pasted (croppedIM) into the main In Python terms.png’) from PIL import Image The crop method takes a tuple and returns an Image object of the cropped image. the left Here we’ve imported the required library. that the paste method doesn’t return jpg’)): an Image object. The cropped image’s dimensions end up being half of the original image’s dimensions. Tkinter 130 | Coding Made Simple WorldMags.makedirs(‘withLogo’.save(os.show() subtract the width and height of the logo image from the real >>> copyIM.save(‘pastedIM.open(‘logo. The font option specifies which font. just like we did in the previous im = Image. you can go a step further and wrap the script in a rudimentary interface cooked up with Python’s de-facto GUI library Tkinter. it’s expressed as: image (copyIM). we can also place a textual watermark over the images.bottom)). use its various functions and methods to modify and apply filters to any image. which is image.truetype(“DroidSans.endswith(‘. for example.Draw(im) a lightweight user import os font = ImageFont.listdir(‘.paste(croppedIM. Now load the image Now that we have a copy of our screenshot. which We’ve used the paste method to place the logo in the we’re going to paste over the copied image: bottom-right corner of the image. 150).png.0)). Thus. The fill option gives the RGB colour for the text. filename)) The cropped thumbnail image is in croppedIM.net >>> im. we’ll first crop and extract its size information: a smaller bit from the image.500)).png’) image. Add a watermark which is useful for annotating images.open (filename) section: IMwidth. Similarly.right. you end up with a 50 x 50 statement creates a directory called withLogo.128)) The first statement creates an object that will be used to draw over the image. WorldMags. After pasting the thumbnails twice at im. (400. leaving you with the logoWidth. With a simple script.top. exist_ok=True) example. 24) interface for your print (“Adding watermark to %s” % (filename)) Python scripts. the coordinates will be 0 for the X axis. IMheight - >>> bottom = int(3 * height/4) logoHeight)) >>> croppedIM=copyIM.’): probably guessed.right. we >>> copyIM. opened our logo and top variables will both be set to 25. if the image you’re cropping is 100 x 100.png’) out the outside edges of the image. IMheight .bottom)) im.top. or perhaps even drop it if you don’t have >>> copyIM=im. The where we’ll house the logo-fied images. (200. which as you have for filename in os.logoHeight)) different locations.png or . and instead modifies the image in place.“All Rights Reserved”. ImageFont wonderful toolkit custom watermark or logo over all the images you’ve ever to quickly cook up shot in a matter of minutes. we save the image as pastedIM. To determine the >>> copyIM. ImageOps. so that we can place it on to the def initUI(self): canvas. The fill option makes sure the widgets fill the l.add_command(label=“Help Index”) def main(): helpmenu. Tkinter menus can The complete script is available on our GitHub at https:// be torn off. column=3) editmenu.parent. Using PhotoImage we convert the PIL image into a The initUI() function will draw the actual interface: Tkinter PhotoImage object..img = photo2 command=self. Q WorldMags. import the required libraries: However. We then create a image being opened and reset the geometry of the window pull-down menu: accordingly.BOTH. we can program self.__init__(self.parent.setImage() package for its superior arithmetic skills.label1. the rotate command with this: menu=editmenu) im = self. so we won’t go into details executes the associated custom function when the menu about it here.Tk() menubar.configure(image=photo2) editmenu. Since we don’t want that feature. manipulation app. filetypes = ftypes) ImageFilter filename = dlg. ImageEnhance.parent.gif')] from PIL import Image.add_command(label=“About.fn) self. We can add menu options as we expand as a framework to flesh out the image editor as you learn new our app. which we do in the next line. as we did in the last line. we have to open the image: import tkinter.PhotoImage(im) editmenu = tk. filemenu.Open(self. command= self.initUI() self. let’s define a custom function to modify it: filemenu.fn = filename Besides Tkinter and PIL.add_command(label=“Exit”.title(“Simple Photo Editor”) reference to the image object.add_command(label=“Save”) two parameters are x and y screen coordinates.rotate(45) ##rotate an image 45 degrees photo2 = ImageTk.pack(fill = tk.config(menu = menubar) root.mainloop() The add_command method adds a menu item to the menu. Remember to keep a self. parent): def setImage(self): tk. Now let’s create the Here we’ve defined the parameters for the Open dialog main class that’ll initialise the graphical interface: box to help us select an image. ‘*.label1 = tk.open(self. geo = str(l)+“x”+str(h)+“+0+0” The expand option is used to ask the manager to assign self. menu=filemenu) im = self.grid(row=1.add_cascade(label=“Help”.png.filter(ImageFilter.geometry(geo) additional space to the widget box. expand = 1) don’t. which tricks and get familiar with the Pillow library.com/geekybodhi/techmadesimple-pillow. before we define the custom functions for import tkinter as tk editing the images. and the add_ if __name__ == ‘__main__’: cascade method creates a hierarchical menu by associating main() a given menu to a parent menu. tearoff=0) name__ == ‘__main__’ trick : helpmenu.label1. The last filemenu.net is covered in detail on page 142.parent = parent photo = ImageTk. as a nice convenience feature.size entire space by expanding both horizontally and vertically. WorldMags. border = 25) Moving on.filedialog..parent) the image we’ve asked it to open. we’ll turn it off by github. we’ve imported the NumPy self.Menu(self.img = Image. self.show() import numpy as np self. to begin execution.geometry(“300x200”) self. Use it setting tearoff=0 . h = self.Frame): function that displays the image in our Tkinter interface: def __init__(self.configure(image = photo) Flip to the Tkinter tutorial on page 142 for a detailed self. This feature can be added filemenu = tk.add_command(label=“Trace Contours”. column = 1) our editor to resize the image window according to the size of menubar = tk. dlg = tkinter. The first two onOpen) parameters are the width and height of the window.add_separator() canvas.label1. add_seperator adds a separator line. ImageTk. window and positions it on the screen.quit) def onRot (self): menubar.img.”) root = tk.Menu(menubar. This will help us resize the Here we’ve used NumPy to help calculate the size of the window to accommodate larger images. menu=helpmenu) ImageEditor(root) root.onCont) You can similarly create the onCont function by replacing menubar. command=self.label1. command=self.label1.add_command(label=“Open”.jpg *.img) and columns. Normally. the image won’t always show up.img.img) self.add_cascade(label=“File”. tearoff=0) self.asarray(self.img. self.PhotoImage(self. self.I = np.image = photo2 onRot) self.image = photo # keep a reference! explanation of the methods and functions we’ve used here. The geometry method sets a size for the filemenu.add_command(label=“Rotate”. If you self. parent) self. To start constructing our basic image item is clicked.grid(row = 1.add_cascade(label=“Simple Mods”.Menu(menubar. Each menu option has a command= option. tearoff=0) by adding the following bit of code in the setImage function The above code gives the app window a title and then uses before placing the image on to the canvas: the Pack geometry manager that helps pack widgets in rows self. we’ll use Python’s if __ helpmenu = tk.net Coding Made Simple | 131 .Frame.Label(self. *.label1.CONTOUR) As usual.Menu(menubar.filedialog def onOpen(self): import PIL ftypes = [(‘Image Files’. Next comes the setImage class ImageEditor(tk.add_command(label=“Close”) Now that we have opened and placed an image on the filemenu. 99 iPAD PRO Worth the upgrade? Master your tablet’s apps and system features EACH ISSUE JUST £2.99 / $2.net JOIN US ON TWITTER: @iPadUserMag . SUBSCRIPTIONS FROM £1.99 / $4. WorldMags.99.gl/fuXZt WorldMags. net . Available from THE ONLY APPLE ACCESSORY YOU’LL EVER NEED! ON SALE NOW! The new & improved MacFormat magazine .com WorldMags. WorldMags.rebuilt from the ground up for all Apple enthusiasts. input= True. The library can help you record audio as well as play RAM.net .open (format=pyaudio. and open and close audio streams. and discard popular cross-platform PortAudio I/O library. rate defines the sampling frequency. Another advantage of reading data in chunks. For one. In a real program. we’ll also define a number of properties that can be altered to influence how the data is captured and recorded. WorldMags.PyAudio() stream = p.Stream class. see later on. The input=True parameter asks PyAudio to use the stream as input from the device. easily installed with a simple pip install pyaudio command. While initialising the stream.1 kHz. instead of a continuous amount because it involves handling a variety of devices.paInt16 parameter sets the bit depth to 16 bits. we use to define the length of the audio buffer. which is usually 44. working with multimedia is fun. It can be the rest. access audio devices. we will also define with the WAV library to capture (or play) audio in the lossless two variables: WAV format: record_seconds = 10 import pyaudio output_filename = ‘Monoaudio. captured in this buffer can then either be discarded or saved. input_device_index = 0. Frames_per_buffer is an interesting parameter. int(rate / chunk * record_seconds)): 134 | Coding Made Simple WorldMags. which A udio is an important means of communication and. you can quickly cobble together the code to open the PyAudio recording stream. which is mentioned with the input_device_index parameter. The data truth be told. rate=44100. PyAudio is generally complemented program as well. channels can be set to 1 for mono or 2 for stereo. which has a limited amount of PyAudio.PyAudio class is used to initiate and terminate PortAudio. reading data in and formats. you’ll want to define these parameters As with all programs. Along with the above. The pyaudio. standards of audio. frames_per_buffer = 1024) The pyaudio.wav’ import wave Now comes the code that does the actual audio capture: print (“ Now recording audio.paInt16. However. as we will back sounds without writing oodles of code. because they’ll be used in other places in the by importing the library. where the stream is opened with several parameters. which indicates that you are reading the data as 16-bit integers.net PyAudio: Detect and save audio Discover how Python can be used to record and play back sound. channels=1. p = pyaudio. Speak into the microphone. you need to begin any PyAudio program in variables. The real audio processing happens in the pyaudio. ”) Capture audio frames = [ ] Once you’ve imported the libraries. and make continuous flow of data from the microphone would just eat interactive apps. Recording a with Python to capture and manipulate sound. is that it enables us to analyse the data and only The PyAudio library provides Python bindings for the save those relevant bits that meet our criteria. There are several libraries that you can use chunks helps use resources efficiently. One of the better platform-independent up the processor and may lead to memory leaks on devices libraries to make sound work with your Python application is such as the Raspberry Pi. for i in range(0. for a couple of reasons. working with audio is a challenging task PyAudio uses chunks of data. which sets evaluates the expression. channels=1. is initialised with the __init__ function. The popular PortAudio documentation to understand the there’s also the is_active() and is_stopped() ones are the sampling rate.writeframes(b‘ ’. rate=44100.setsampwidth(p. and finally terminates the PyAudio session. class Recorder(object): While the above code will work flawlessly and helps def __init__(self. In a real project. the variable given by as .setnchannels(channels) would look something like: wf. and assigns whatever __enter__ returns to the PyAudio’s get_sample_size() function. which the data as 16-bit integers. We discuss Python’s if __name__ == ‘__main__’ trick for Python opens the file in the write-only mode. while get_time() returns the stream’s or both. Moving on. as we’ve done. and setframerate. paInt24. This is followed by a bunch of wave write The above code is executed when the program is run directly. The for loop handles the task of recording the audio.open(‘capture. there are several other parameters that can be or stopped. an output stream other formats include paInt8. paInt32 and paFloat32.read(chunk) frames. which return a Boolean value channels.close() p. exception.Stream class. The Recorder class opens a recording stream and defines you’ll have a 10-second WAV file named Monoaudio. The get_input_latency() list of the other popular ones. Here’s a depth to 16 bits. the code that begins the execution wf. when the with statement is executed. before closing the file. guard object’s __exit__ method. and then define a list variable named frames . ”) stream. value. audio hardware on your machine. Now that we have the audio data as a string of bytes in the frames list. the wave module. After executing the program. In addition to this. it calls the case is named frames. You can safely ignore these because they are the some setup and shutdown code to be executed – for result of PyAudio’s verbose interactions with the audio example. It brings in the data in correctly sized chunks and saves it into a list named frames .open(output_filename. In such a case. depending on whether the stream is active the sampling size and format.close() code and must be ironed out.close() recfile. WorldMags. objects. we’ll transform it and save it as a WAV file using the wave module: break up the tasks into various smaller tasks and write a class wf = wave. and selecting one for their application.wav’.0) This is where the data is actually written to an audio file. and calls the magic __enter__ the frame rate (44. irrespective of what happens in that code. to close the file in our case: hardware on your computer. WorldMags. ‘wb’) for each. What you should watch out for def __exit__(self. The __enter__ and If you run the program. latency.channels = channels how you’d program it in the real world. frames=1024): demonstrate the ease of use of the PyAudio library. Python channels (mono in our case). the number of frames per buffer.join(frames)) with rec. The setsamwidth object method on the resulting value (which is called a context sets the sample width and is derived from the format using guard). you’ll first notice a string of __exit__ methods make it easy to build code that needs warnings.net data = stream. Finally. For managing the stream. function returns the float value of the input can either be an input stream. besides the You can pass several parameters to the stream are advised to spend some time with the start_stream() and stop_stream() functions. the number of nuances of these different formats before functions. traceback): are any Python exceptions that point to actual errors in the self. In our case. you’d self. which in our and.setframerate(rate) rec = Recorder(channels=1) wf. which sets the number of Now. this isn’t self. as defined by writing reusable code in the Tweepy tutorial (see page 138). We will now close the audio recording stream: print (“ Done recording audio. which sets the bit used to fetch information from a sound file while can use with the pyaudio.rate = rate Managing a PyAudio stream We’ve used some of the parameters that you we’ve used paInt16 format. then You can safely ignore all messages (except Exception errors) that appear whenever you run a PyAudio script – it’s simply the library discovering the closes the stream. such as setnchannels. The stream. the number of bytes a recording should have. indicating that you are reading initialising a stream.terminate() The above code first terminates the audio recording. ‘wb’) as recfile: wf.1kHz in our case). The for loop helps determines how many samples to record given the rate.stop_stream() stream. the loop makes 430 iterations and saves the captured audio data in the frames list. Audiophile developers time. In the tutorial. and the recording duration.join() method combines the bytes in a list.net Coding Made Simple | 135 . Python then executes the code body b‘ ’.append(data) We first print a line of text that notifies the start of the recording.wav in its parameters: the current directory.get_sample_size(format)) if __name__ == ‘__main__’: wf.record(duration=10. while creating it. When all the frames have been streamed.argv) < 2: stream. accessing system-specific functions and parameters.rate. We used the wave wide range of multimedia formats including WAV. we’re done. As long as there are chunks For more sys. One of the best features of the Pyglet module to read and write audio files in the WAV MP3. bunch of external ones. OGG.close() level is considered p = pyaudio. OGG/Vorbis and WMA.exit(-1) of data.write(data) print(“ The script plays the provided wav file. 136 | Coding Made Simple WorldMags. simplifying module. self. which multimedia frameworks with Python bindings. self. and contains the code to record data from the microphone into the file after setting up the stream parameters. The script will play any provided WAV file. we’ll use functions to extract details from described earlier. fname. There’s also installation. channels=wf. The GStreamer Python bindings allow as MP3. It enables multimedia and windowing library is that it needs audio format. processing capabilities. the while loop writes the current frame of audio accurate results. decode and nothing else besides Python.frames) If a filename is provided. AVI.open(sys.stop_stream() to decide what wf = wave. the getnchannels Vocalise recordings method returns the number of audio channels. you can also train PyAudio to start recording as soon as it detects a voice. as reading a WAV file.wav” % sys. uses FFMPEG to support formats other than work with AVbin to play back audio formats such you can find the minimum and maximum values WAV. # read data import pyaudio data = wf. output=True) self.net self.frames_per_buffer = frames getsampwidth()). developers to use the Gstreamer framework to formats such as DivX. the above code comes into action and prints the we’ll then terminate the stream and close PyAudio with: of sound frames proper usage information before exiting. Once we have all the details from the file. it’s opened in read-only mode The class defines the necessary parameters and then and its contents are transferred to a variable named wf.readframes(1024) Proper usage: %s filename. MPEG-2. recording. calculate the RMS value for a group provided.wav’) print(“Alrighty. WorldMags. Auto recorder In the scripts above. we’ll import the sys module for audio file.wav”) The record_to_file function receives the name of the file to record the sound data to. return RecordingFile (fname. ‘rb’) stream. when the audio.net . used for manipulating the raw audio encode all supported formats. stream. streaming modules for working with sound. which the PyAudio library is initialised. For example.264. we extract the argv[0]) frames in chunks of 1.argv[1]. def open(self. stream = p.\n data = wf.terminate() to be silence.getframerate().readframes(1024) import wave import sys # play stream (3) while len(data) > 0: if len(sys. which Other popular Python sound libraries Python has some interesting built-in multimedia PyMedia is a popular open source media library playback to video playback. and then writes the files using the for loop.PyAudio() p. Recorded to capture.channels. the getsampwidth method fetches the sample width of the file in bytes. mode. such as: print(“Start talking into the mic”) record_to_file(‘capture. multiplex. Then passes them to another class. DivX.024 bytes. If one isn’t data to the stream. mode=‘wb’): rate=wf. as well as a that supports audio/video manipulation of a and editing. captures we used earlier to define the parameters of the stream. we’ll initiate the script as usual with the if __name__ == ‘__main__': trick to print a message and then call the function to record the audio. WMV and There are also several third-party open source develop applications with complex audio/video Xvid. With a little bit of wizardry. Another popular library is Pygame. Unlike the open() function defines the record function that opens the stream.getnchannels(). In addition getframerate returns the sampling frequency of the wave to pyaudio and wave. which is a high-level audio interface that and other visually rich applications. from simple audio adds functionality on top of the SDL library. It also calls the record() function. and You can easily adapt the code to play back the file. For instance. demutiplex. and video of all the samples within a sound fragment. It’s popular for developing games data. There’s also the built-in audioop you to parse. and keep capturing the audio until we stop talking and the input stream goes silent once again. It can be used to perform several Pydub.get_format_from_width(wf. the file. H. DVD and more. we’ve seen how to use PyAudio to record from the microphone for a predefined number of seconds. Similarly. To do this.open(format=p. It can also operations on sound fragments. named RecordingFile. We next check r. we’ll increment the num_silent variable.extend([0 for i in range(int(seconds*RATE))]) whether this recorded data contains silence by calling the return r is_silent function with silent = is_silent(snd_data) . among other things. if snd_started and num_silent > 100: input=True. we’ll set the snd_started num_silent = 0 variable to True to begin recording sound.read(CHUNK_SIZE)) recording and pad the audio with 1. seconds): r. Adding silence is simple.net Coding Made Simple | 137 .PyAudio() stream = p. elif not silent and not snd_started: def record(): snd_started = True p = pyaudio.5 seconds of blank sound. we’ll call another function to manipulate the snd_data = array(‘h’. defined the is_silent (snd_data) function elsewhere in the com/geekybodhi/techmadesimple-pyaudio/. we’ll then subject it to several other Python libraries for playing sound. Although there are returns a value (either True or False). so have fun num_silent += 1 playing around with your sound! Q WorldMags.byteswap() def add_silence(snd_data.frames_per_buffer=CHUNK_ break SIZE) If the captured data is above the threshold of silence and we haven’t been recording yet. channels=1. Once the is_silent function the end and even from the start. snd_data. [0 for i in range(int(seconds*RATE))]) The function records words from the microphone and r. rate=RATE. checks the captured data for silence. It uses the max(list) method.net Websites such as Program Creek help you find sample code for Python modules like PyAudio. But if we’ve been snd_started = False recording sound and the captured data is below the silence threshold. while 1: Next.extend(snd_data) returns the data as an array of signed shorts. PyAudio is further tests: one of the easiest to use with third-party audio toolkits that if silent and snd_started: you can use to capture and manipulate sound. When you script. This function will return True if the snd_data consequent frames until it detects a period of silence. Moving r = array(‘h’) on. A value lower than the threshold by writing a trim function that’ll trim the silent portion from intensity is considered silence. which returns the execute it. stream. WorldMags.open(format=FORMAT. it’ll save all maximum value. if it exists. From here on. we’ll stop recording if we’ve been recording but it’s been 100 frames since the last word was spoken. The threshold intensity defines The script also contains comments to help you extend it the silence-to-noise signal.extend(snd_data) r = array('h’. We’ve The complete script is on our GitHub at. is below the silence threshold. it will detect and start capturing audio frames but elements from a list (snd_data in this case) with the discard them until it detects a voice. We’ll just read the recorded data into if byteorder == ‘big’: an array and then extend it by adding blank frames. Twitter also offers a set of Quick Tweepy accesses Twitter via the OAuth standard for streaming APIs. You used the items method to iterate through our timeline. take a minute or two.twitter. To can. for example. which raw data passing over the network.items(): what the world is thinking.text) social network is powered by a wonderful API that The code will print all status updates in groups of 20 from enables users to drink from the firehose and capture all the your own timeline. WorldMags. however.Cursor(api. which you the tweets. interacting with Twitter via Python is You can easily install Tweepy with pip install tweepy . strings listed alongside API Key.API(auth) From this point forward.org/ can leave blank.Cursor(api.streaming import StreamListener html) for a list of Access Tokens tab and create an OAuth token. tweepy. We’ll Tweepy’s Twitter credentials. In this tutorial. you can supports several different types of objects. you need to import the following libraries in your Python script: import tweepy from tweepy. find trends related to specific keywords or limit the number of tweets you wish to print. Here we have use this data to mine all kinds of meaningful information. Once captured. Access Token and Access Token Secret. using Tweepy to capture any tweets that mention OggCamp. For that. you can access tip authorisation. we can use the api variable for interacting with Twitter. The public streams work Scroll through. you can tap into the collective consciousness and extract “valuable” information from it.set_access_token(access_token. Tweepy is one of the easiest libraries that you can use to user_timeline). and use these to connect to Twitter. we’ll be recent tweets. app has been created.items(10) . such as: consumer_key = “ENTER YOUR API KEY” consumer_secret = “ENTER YOUR API SECRET” access_token = “ENTER YOUR ACCESS TOKEN” access_secret = “ENTER YOUR ACCESS TOKEN SECRET” auth = OAuthHandler(consumer_key. API Secret. you’ll first have to head over to Twitter’s global stream of tweets. Now press the Create New App button import and modify Tweepy’s StreamListener class to fetch documentation (. This might from tweepy import OAuthHandler supported methods. which will only print the 10 most access the Twitter API with Python. you can read your own time with the following loop: T witter is a wonderful tool if you want to get a feel for for status in tweepy. you can hop over to the Keys and from tweepy. access_secret) api = tweepy. As you can see. reasonably straightforward. For example. To access the tweets. and fill in all the fields except for the Callback URL. consumer_secret) auth.net . change the statement to something like tweepy. We use Tweepy’s Cursor interface. and by using these.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream Next you need to paste in the API and Access tokens. you can also gauge sentiments during events. and then we’ll mine the data to print a list of the most Capture tweets frequently used hashtags. Once the from tweepy import Stream en/latest/api.com and sign in with your regular really well for following specific topics and mining data. Once it’s done. You’re now all set to access Twitter with Python. The visible 140-character print(status.user_timeline). and then click on the Create button.net Tweepy: Create Twitter trends With some Python know-how. make a note of the 138 | Coding Made Simple WorldMags. Once you have discovered the Here we use our stream class to filter the Twitter stream to Twitter ID. You can also filter results by combining Anatomy of a tweet The 140 characters of the tweet that are visible representation of the user who has contributed used (you) has marked the tweet as favourite or on your timeline are like the tip of the iceberg.com. if the Python number of attempts to connect to the streaming API within a interpreter is running the source file as the main program. which lists the UTC time when the tweet Besides these. the connect will error out. your wait time. For example. ‘tuxradar’ information about what to do with the data once it comes or ‘LinuxFormat’. you can modify the above to say twitterStream. Here we begin by creating a class that inherits from StreamListener. Tweepy establishes a streaming session and routes All that gobbledygook is just one tweet! messages to the StreamListener instance.net Coding Made Simple | 139 . We place by @LinuxFormat. information that has been parsed out of the text Also important is the lang field. Then comes the text field. data): print(data) return True def on_error(self. Of this inside an if condition. the stream listener. Boolean fields that indicate fields contain information that points to the id_str fields. fetch only tweets that contain the word ‘oggcamp’. listener) You can modify the above to filter your results based on Once we’ve authenticated with Twitter. warnings. it When you’re interacting with Twitter via its API. and statements in a module can find out the name of data from status to the on_status() method.API(auth) class StdOutListener(StreamListener): def on_status(self. and passes name. It is followed by the id and the retweeted fields. Repeated attempts sets the special __name__ variable to have a value “__ will only aggravate Twitter and it will exponentially increase main__” . The modified StreamListener class is filter(track=[‘LXF’. This contains the that contain any of the three words specified: ‘LXF’. If you exceed the limited defines a few special variables. use Tweepy’s on_ __name__ is set to the module’s name. number of times the tweet has been favourited the tweet itself. or for creating a live feed using a site stream or user stream. such as URLs and hashtags. The if __name__ == “__main__”: these. it window of time. ‘LinuxFormat’]) will get tweets used to create a listener instance. For instance. if __name__ == ‘__main__’: you’ll first have to find out its Twitter ID using a web service twitterStream. back from the Twitter API call.OAuthHandler(consumer_key.net auth = tweepy. A to the tweet. contains the two-character language identifier of field.filter(track=[“oggcamp”]) such as Twitterid. which will display any new tweet parameter is an array of search terms to stream. When the Python interpreter reads a source file. it to be mindful of rate limiting. Similarly. The track filter(follow=[‘255410383’]) . on_data() . ones will help you extract the relevant data. we can now start multiple keywords. WorldMags. which contains and retweeted respectively. which contain the more information and attributes in addition to contains the actual text of the status update. A knowledge of the important We’ve also use the entities field. twitterStream = Stream(auth. on_status() and on_error() are the most trick exists in Python. direct messages and so on. status): print(status) return False The Twitter streaming API is used to download Twitter messages in real time. its module. using twitterStream. which The JSON string begins with the created_at of the tweet. Every module has a statuses. if you wish to follow a particular Twitter account. ‘tuxradar’. so our Python files can act as reusable useful ones. To avoid such a situation.set_access_token(access_token. is being run standalone by the user and we can do listener = StdOutListener() corresponding appropriate actions. you have executes all the code found in it. It is useful for obtaining a high volume of tweets. Before executing the code. The place and geo was created. which are the integer and string whether the user whose credentials are being geographic location of the tweet. consumer_ secret) auth. In our case. such as en or de. as the error() method to print the error messages and terminate defined __name__ is ‘__main__’ it tells Python the module execution. Then there are the favorite_count complete tweet in its JSON form contains a lot we’ve used extensively in the tutorial – this and retweet_count fields. WorldMags. StreamListener has several methods. there’s the favorited and the tweet. If this file is being imported from another module. The on_data() method handles replies to modules or as standalone programs. which retweeted it.access_secret) api = tweepy. It opens the output file.argv[1]) else: print(‘Usage: python top_tweets. you can simply redirect the output of class StdOutListener(StreamListener): the StreamListener to a file. Else the script prints the proper usage information if the user has forgotten to point to the JSON file.12775829999998223].tweet_data. self.tweet_data)) The StreamListener will remain open and fetch tweets saveFile.net various parameters. (. Begin by importing the relevant libraries: import sys import json import operator Now we’ll pass the .com and register a new app to get yourself def main(tweetsFile): some API keys and access tokens. After installing the connector. writes the Before you can process the tweets. just like we have done in the connect.twitter. tweets_file = open(tweetsFile) Save tweets to database Instead of collecting tweets inside a JSON file. and also print the values on the screen. For example. We’ll then scan each tweet for text. WorldMags.tweet)) store the username and the tweet. USE tweetTable.json file to the script from the command line. tweet in the stream. The large blobs of text on your screen return True are the tweets fetched by the streamlistener in the JSON Instead of printing the tweets to the screen. import io and closes the document. host=‘localhost’.open(‘oggcampTweets.write(u‘[\n’) parameters.connector.com/streaming/overview/request. block will import the io library and use it to append the data flowing from the StreamListener into a file named Process tweets for frequency oggcampTweets.tweet_data=[] We can now use the oggcampTweets.loads(data) provides a connector for Python 3 that you can import json if ‘text’ in all_data: easily install by using pip3 install mysql. use the following code to import the required class StdOutlistener(StreamListener): you can also directly connect to and save them Python libraries and connect to the database: def on_data(self. Head over to. If it finds a pointer to the JSON containing the tweets file. Take a look at Twitter’s official API documentation saveFile = io. CREATE TABLE tweets (username Once we’re connected.-0.connector all_data = json. connect = mysql. with a table named tweets that has two fields to and extract the tweet along with the username print((username.cursor() db. writes the JSON data as text to a file.json’. encoding=‘utf-8’) parameters) for a list of all the supported streaming request saveFile. we’ll create a tweet) VALUES (%s. The MySQL database import mysql. then inserts a closing square bracket. track=[‘linux’]) def on_data(self.json will save all tweets with def __init__(self): the word ‘oggcamp’ to a file named oggcampTweets.json.net . db=connect.%s)”. Alternatively.5073509. username = all_data[“user”][“screen_name”] you can create a database and table for saving connect(user=‘MySQLuser’. You can now and screen name from the tweets: return True 140 | Coding Made Simple WorldMags. data): inside a MySQL database. python fetch_ oggcamp. StreamListener.json.tweet VARCHAR(140)). For example. ‘w’.json file to mine all kinds of data.write(‘.commit() This creates a database called tweetTable main tutorial.join(self. database=‘tweetTable’) table. twitterStream. you will have to save them opening square bracket.(username. Once we’ve extracted the information from a the tweets with: password=‘MySQLpassword’.’. tweet = all_data[“text”] connector-python .close() terminating the script.append(data) word ‘linux’. data): will fetch any tweets that originate in London and contain the self. For example. saveFile. the above format (see box below). it’s forwarded to the main() function.twitter. tweet)) VARCHAR(15). we can write these to the CREATE DATABASE tweetTable. let’s analyse this data to list the 10 most frequently used hashtags.py file-with-tweets.json’) The following code analyses the number of parameters passed from the command line.filter (location=[51.write(u‘\n]’) based on the specified criteria until you ask it to stop by saveFile. separated by commas. if __name__ == ‘__main__’: if len(sys.py > oggcampTweets.argv) == 2: main(sys.execute(“INSERT INTO tweets (username. loads(tweet_line) key=operator. you can install over 200 packages.sh system is called Conda. that people used if tweet_line.strip(): sortedHashTags = dict(sorted(tweets_hash.encode(“utf-8”) in tweets_hash. we’ll check whether the hashtag is GitHub repository at:. and save it in a variable named the descending order of their occurrence.keys(): print(“#%s .encode(“utf-8”)] += 1 You’ll need to familiarise yourself with data structures and else: dictionaries in Python to make sense of the above code. if “entities” in tweet. WorldMags.net These are the tweets_hash = {} increment its occurrence frequency. we’ll extract the results. To access tweetsFile variable. Each tweets_hash[ht[“text”]. You can use Miniconda to and install it with: extensions.org/miniconda. you can use the familiar square brackets variable.items().kv[0]). grab the installer from ships with a package management system. Python also Of the two distributions. The code block will filter the top 10 tweets based on into a dictionary object. and print the tweet .net Coding Made Simple | 141 . WorldMags. Miniconda. Then close and re-open the terminal window for installing multiple versions of software packages. Next.value in sorted(sortedHashTags. includes Conda.keys(): hashtags = tweet[“entities”][“hashtags”] print(“\nHashtag . libraries and also installs Python. We then initiate a loop for every through the entire JSON file and scavenged data from all the individual tweet in the file. In case it is. Python. and it can be used for dependencies with the conda install command.com/geekybodhi/ already listed in our dictionary. we’ll just techmadesimple-tweepy. Python’s package management install over 200 scientific packages and their bash Miniconda3-latest-Linux-x86_64. Q Python’s package management Just like your Linux distribution. Anaconda.pydata. and. the JSON file is received as the curly braces.reverse=True): if ht[“text”].Occurrence\n”) for ht in hashtags: for count. while tweeting tweet = json. and it includes Conda and Conda-build. reverse=True)[:10]) about privacy. if ht != None: key=lambda kv: (kv[1].html helps install complex packages.items(). such as Anaconda and Miniconda. Keys are unique within a dictionary.decode(“utf-8”). Else. and the whole thing is enclosed in simple.%d times” % (count. and also over 100 packages list command to list the installed packages.itemgetter(1). we’ll add it to the top hashtags for tweet_line in tweets_file: dictionary and record the occurrence. Miniconda is the smaller install Miniconda. tweets_hash that will house the hashtags and their The above code comes into play after we have gone occurrence frequencies. on the other hand. the changes to take effect. Like can now install packages such as matplotdb distributions. which one. value)) tweets_hash[ht[“text”]. You application and instead ships with all Python and libraries that it installs automatically. To start with. the items are The above might look like a mouthful but it’s actually really separated by commas. If the tweet has a tag named ‘entities’. We then define a dictionary variable named along with the key to obtain its value.encode(“utf-8”)] = 1 key is separated from its value by a colon (:). The complete code for this tutorial is available in our hashtag value. We’ll first convert the JSON string tweets. which is then read by the tweets_file dictionary elements. To with conda install matplotdb . Now use the conda Conda isn’t available as a standalone Conda-build. which states that ‘explicit is tip used to create the graphical app’s main window. it goes Quick We begin by first importing the Tkinter module.Tk() app = App(master=root) app. it’s important to note that we’ve interface to Tk. including an editable display. Tk was developed explicitly created an instance of Tk with root = tk.Button(self. # Insert code to add widgets used to correct mistakes and to enter symbols and com/h3eotvf).hi = tk. listed import tkinter as tk to write our graphical calculator.pack() self. before entering the main event loop to Graphical calculator vegaseat’s Updated take action against each event triggered by the user.hi[“text”] = “Hello World” self. which can be ((side=“top”) self.hi. JPython app.mainloop() and Tkinter.com window = tk.Frame.EXIT. which is then against the spirit of Python.createWidgets() def createWidgets(self): self. Tkinter is the Python build our calculator. window. as a GUI extension for the Tcl scripting language in the early Tkinter starts a Tcl/Tk interpreter behind the scenes.__init__(self.EXIT = tk. and both are required in order for a Tkinter the Tk GUI toolkit. master=None): tk. create your first widget. Creating an instance of Tk initialises code. text=“EXIT”. such as wxPython. to learn than other toolkits.Tk() our calculator.title(‘Sample Application’) P ython provides various options for developing app. it doesn’t take much effort to drape a Python Tiny Tkinter example. explicitly initialise it. We’ll use the same principles Calculator. For now.net Tkinter: Make a basic calculator Why not use Python’s default graphical toolkit to build a simple – yet easily extensible – visual calculator? Here’s a more practical example that creates a window with a title and two widgets.net . One of the reasons for its popularity is that it’s easier then translates Tkinter commands into Tcl/Tk commands. one or more of the supported widgets (see box on page 143) The code in this tutorial is based on to the main window.Tk() . master) self. For example. because Tkinter is a set of wrappers that implement the this interpreter and creates the root window. you don’t need to write Tcl application to work. While this is perfectly fine. For As you can see. Tkinter is the standard GUI We’ll explain the individual elements of the code as we library that ships by default with Python. command=root.master.mainloop() hexadecimals not on our calculator’s keypad. We’ll add various widgets to on DaniWeb. If you don’t Tk widgets as Python classes. the GUI toolkit for Tcl/Tk. the following code will display a window: app with a graphical interface. WorldMags. Next we add better than implicit’. one of which quits the application when clicked: import tkinter as tk class App(tk. which 1990s. one will be implicitly created when you Creating a GUI application using Tkinter is an easy task. The main window of an application and this interpreter are Tkinter provides a powerful object-oriented interface to intrinsically linked.pack(side=“bottom”) root = tk. fg=“red”.geometry(“250x70+550+150”) graphical user interfaces. if 142 | Coding Made Simple WorldMags.master. To use Tkinter. Of these.Label(self) self.Frame): def __init__(self.destroy) self. we initialise the instance parameters for the positioning and appearance of our Commonly used Tkinter widgets The Tkinter toolkit supports over a dozen types multiline and non-editable object that displays scrollbars on Entry widgets. The partial function from the functools module helps us write reusable Define the layout code. In other and trigonometric functions.Tk. The the user clicks on it. our calculator will words. automatically when you click the button. ( bg ). You have to declare it explicitly. The Menu widget can create such as the ones to define background colour Checkbutton widget is used to display a number different types of menus. Most object-oriented languages pass this as a hidden parameter to the methods defined on an object. such as Listbox. the math library to handle the calculations. is automatically called when an object of that class is created. So when you call Calculator() . You can associated with a Menu widget. It is important to use We begin by importing the various libraries and functions the self parameter inside an object’s method if you want to for our calculator. a list of all the options supported by each of options. it’ll print the decimal equivalent. top. WorldMags. Every menubutton is w = <widgetname> (parent. we’ll also need persist the value with the object.. and can level and pull-down. which creates graphics.edu/ Listbox widget is useful for displaying a list of controller that is used to implement vertical tcc/help/pubs/tkinter/web/index. that is 170.. We’ll explain how we’ve used it later in the tutorial. the __init__ method is the constructor for a class in also have the ability to temporarily store and retrieve a result Python. In this section we define different Calculator class. the The Scrollbar widget provides a slide documentation (. such as the logarithmic argument. method. it will be passed automatically.nmt. they also share several options. . The Canvas widget of controls or widgets that you can use in your texts. variables with the __init__ method in the class body. The basic idea is that it is a special method. but class Calculator(tk. the border ( bd ). the editable display can also be used to manually method is executed automatically when a new instance of the type in functions that aren’t represented on the keypad but class is created. and then passes it as the first parameter to the __init__ Tkinter library and its interactions with Python. import tkinter as tk The self variable and the __init__ method are both OOP from math import * constructs. the part of a drop-down menu that stays on the All these widgets have the same syntax: The Button widget is used to create buttons screen all the time. ) define a function for a button. WorldMags.Tk): Python does not. Refer to the Tkinter also display images in place of text. The Message widget provides a Text and Canvas. and the size of of options to a user as toggle buttons. including pop-up. Python creates an object for Let’s dissect individual elements to get a better grasp of the you. Besides the Tkinter toolkit.net Tkinter makes it relatively easy to build a basic graphical calculator in Python. To begin with.html) for items from which a user can select multiple scroll bars on other widgets. Furthermore. When you def __init__(self): create an instance of the Calculator class and call its tk. You can also create horizontal these widgets. text or other widgets. you enter 0xAA.net Coding Made Simple | 143 . The first order of business is to create the graphical interface After importing the libraries. Here are some of the most Then there’s the Menubutton.__init__(self) methods. the type of border ( relief ). Similarly. creates an area that can be used to place graphical application. Python passes the instance as the first are defined in Python’s math module. that can display either text or images. which is called display the choices for that menubutton when Similarly. This Similarly. option1=value. commonly used ones. which can option2=value. and it is a convention to name it self. The self variable represents the instance of the from functools import partial object itself. The complete code for the calculator is available online. we begin defining the for the calculator. which from its memory bank. and rotation. We use the geometry function to define the size and After creating the button. geometry managers. we increment the position of the position of the calculator’s window – it accepts a single string column and check if we’ve created four columns. we use the implement various kinds of buttons. ‘*’. By default. It includes hierarchy and comes with support for scaling websites.Entry(self. we use several Entry widget The Button widget is a standard Tkinter widget used to methods. The ‘4’. the entry. They are result = eval(self.calculate. Then functions from OpenGL. notebooks.tix there’s the TkZinc widget. and draw the next row of buttons. Else. also known as Pmw. editable display. display the result whenever the equal to (=) key is pressed. such used to implement items for displaying graphical distributions. You can also just the label and move on to the next button. Grid. which is pretty the passed expression as a Python expression. self. ‘3’.get()) listed in the order they’ll appear on the keypad. we implement a plain button. column=c) Calculator class with MyApp(). The calculation is handled by the eval function. In simpler straightforward to use. The btn_list array lists if key == ‘=’: the buttons you’ll find in a typical calculator keypad.create_widgets() around the boundaries of the button. such as anti-aliasing most popular Tkinter extension is the tkinter.title(“Simple Demo Calculator”) with one or more arguments already filled in.entry. If they aren’t available in your as a ComboBox and more. but the geometry manager always has which is part of the functools module. we call the partial Widgets can provide size and alignment information to function to pass the button number. it also provides be extended to provide even more widgets.calculate function. we just print have been added here for easier readability.entry. text=label. self. label)). self. offset coordinates. The r and c elif key == ‘C’: variables are used for row and column grid values. In our code. it can several widgets such as buttonboxes. r += 1 which does the actual calculation but hasn’t been defined yet. The partial function makes a new version of a function self. To add a value to the widget. The comboboxes. as the argument in the format: width x height + xoffset + then we reset the column variable and update the row yoffset . this means that the eval function makes a string with button contents (text from the array.entry. Once we’ve defined the look of the calculator window.geometry(“350x140+550+150”) the new version of a function documents itself.END. When the button is pressed. relief=‘ridge’. Within the self. In the next line. a button While Tkinter supports three geometry managers – appears raised and changes to a sunken appearance when it namely. Entry widget is a standard Tkinter widget used to enter or ‘1’. buttons.grid method helps us place the widget in r=1 the defined cell and define its length. key): create the layout for the calculator. columnspan=5) btn_list = [ The last bit of the calculator’s visual component is the ‘7’.Button(self. which we create using the Entry widget. The real string doesn’t contain any spaces. ‘5’. and you can associate a Python function or current value. Tkinter automatically calls that function or method. ‘Mem >’.delete(0. ‘/’. The c=0 command parameter refers to the self.’.Button function. distro. a mathematical equation. don’t forget to remove if c > 4: the command parameter from the tk. column=0. WorldMags. above code defines and creates the individual calculator you can define the calculate function. The create_widgets() method contains code to def calculate(self. 144 | Coding Made Simple WorldMags. ‘6’. Buttons can contain text insert method. in our case) and what integers in it. ‘+’. the Once you’ve perfected the look and feel of your calculator.net . display a single line of text. width=33. helps write reusable the final say on positioning and size. function or method to call when the button is pressed using the command parameter.grid(row=r.grid(row=0. unlike the Canvas widget. while the get method is used to fetch the or images. bg="green") def create_widgets(self): self. ‘> Mem’. Because this setting doesn’t suit our calculator.entry = tk. Furthermore.entry.memory = 0 The relief style of the button widget defines the 3D effect self. If you call on the command=partial(self. width=5. If we have. we’ll first create a button using the Button function. The partial function. ‘2’. ‘8’. Pack and Place – we’ll use the Place manager. All you have to do is to specify the terms. Furthermore. The return value is the Popular Tkinter extensions While the Tkinter toolkit is fairly extensive. ‘. In the above calculation code. This process is set the position of the window by only defining the x and y repeated until the entire keypad has been drawn. Our calculator is now visually complete. which is very similar and more. grab and compile them following the Another popular toolkit is the Python the TkZinc widget can structure the items in a straightforward instructions on their respective megawidgets. We use a combination of these to calculate and method with each button. c=0 for label in btn_list: Define the special keys tk. components. ‘C’. However. which provides several modern widgets to the standard Canvas widget in that it can be extensions in the repositories of popular that aren’t available in the standard toolkit. ‘Neg’ ] length of the display and bg its background colour. ‘=’. which parses In our code.insert(tk. You can find some of these widget library.mainloop() it draws the c += 1 keypad of the calculator. “ = ” + str(result)) Next we create all buttons with a for loop.END) loop. Arranging widgets on the screen includes determining the size and position of the various components. dialog windows and more. tk. ‘9’. code. self. ‘-’. The width option specifies the ‘0’. which variable. is pressed.net calculator. which is the simplest of the three and allows precise we’ve used the ridge constant. However. boundary around the individual buttons. which creates a raised positioning of widgets within or relative to another window. the eval command.memory = self. The __import__ function accepts a module name ( os in this case) and imports it. if there’s an equal to (=) sign the square root of a number. after the following code block: calculator so committing a value to the memory. First add a key labelled ‘sqrt’ in in the Entry widget.entry. This means we calculate function and enter the following just above the final can now clear the entry and start a new calculation as soon else condition: as a number is punched. When the button labelled ‘> Mem’ is make the code compatible with the older Python 2. the code scans the equation and only saves the replace the lines at the top to import the Tkinter library with functions to your numbers after the equal to (=) sign.entry. To clear the current entry. you can can add more pressed.END.END) execute this command on the web server and print the self.entry.memory = self. you complete equation.entry. The risk with eval() is well documented and has to self.insert(tk. If this if ‘=’ in self. tk. self. schmuck! Stick to negative number. For example.END) import the library with its Python 3 name. The good can similarly extend the calculator by implementing other thing about Python and Tkinter is that they make it very easy maths functions as well. key) current working directory. then Python will attempt to self.insert(0. if ‘=’ in self. Q WorldMags. elif key == ‘sqrt': result = sqrt(eval(self. Instead of passing the contents of the field to beginning of the value. If there’s an equal to calculate function: (=) sign in the display.get())) Add more functionality self.“sqrt= “+str(result)) The above code implements a functional graphical calculator.”) negative sign.memory) elif key == ‘Mem >’: self.get()[0] == ‘-’: function.END. you can easily add a key to calculate conditions are met.delete(0. import Tkinter as tk more advanced Conversely.net Coding Made Simple | 145 . When you press the = key. the eval() function will self. when the code detects that the key labelled ‘Mem except ImportError: calculations.insert(tk. You purposes.insert(tk.delete(0) do with the fact that it evaluates everything passed to it as else: regular Python code.entry.memory: val = self. which is how it was referred to in Python 2.entry. In this case.get(): getcwd() .memory. then the key will insert a negative sign to the the display field.END. WorldMags.get(): operation throws an ImportError. We use these to clear the contents of the editable display at the top whenever the C button is pressed. This code block will first attempt to import the Tkinter elif key == ‘Neg’: library. If the value already contains a self. Then scroll down to where you define the completed and the result has been displayed. elif key == ‘ > Mem’: self. it copies the number saved in its buffer import tkinter as tk to the editable display.get() if ‘=’ in self. however. then that means a calculation has been the btn_list array. pressing the ‘Neg’ button will remove the calculations. it’ll be executed on the server and can except IndexError: wreck havoc. Another way to extend the calculator is to add more which is triggered when none of the previously mentioned functions. Secondly.title(‘Memory =’ + self.find(‘=’) self. pressing the key labelled ‘Neg’ will clear if ‘_’ in self.entry. This brings us to end of our code and the Else condition.insert(tk.memory[val+2:] self. “Nice try. write __import__('os'). try: Another weak point in the code is its use of the eval() if self. For better control. For instance.entry. tk. run the calculator and in else: the display field.net result of the evaluated expression. both the above two conditions This code is triggered when it detects an underscore (_) in aren’t met. So if the user enters a valid Python shell self. we use the delete method.mainloop() operating system.entry.entry.entry. it changes the title of the try: it’s capable of calculator window to reflect the contents of the memory. instead of a number. the Entry widget also allows you to specify character positions in a number of ways.delete(0. When the code is triggered. tricky. if you wish to extensibility.entry. The conditions in the above listed code block are a little To prevent such exploitations of the eval() function.get(): the contents of the display. pass To get an idea of what happens. We then use app = Calculator() the imported module to run commands on the underlying app. there’s always scope for improvement. If. >’ has been pressed. The current value in the buffer is the to extend and improve the code.entry. END corresponds to the position just after the last character in the Entry widget. ‘-’) string into the function. it’ll calculate the square root But as it is with every piece of code written for demonstration of the number in the display field and print the results. The code at the top of this code block comes into play you can insert the following code while defining the when the key labelled ‘Neg’ is pressed. the code displays a warning.END. we define the actions for saving Thanks to and retrieving a calculated value from the calculator’s Tkinter’s memory banks.entry.memory) In this part of the code. 146 | Coding Made Simple WorldMags.net . then ‘How do I download my reward?’ and enter the voucher code WQBA7 *Requires an iPad or iPhone and the Apple App Store.ag/1zvbh9s and tap Help on the bottom menu bar. Offer ends 18 June 2017.net GET YOUR FREE * DIGITAL EDITION Experience this great book on your iPad or iPhone completely free! To get your digital copy of this book simply download the free Linux Format app from. WorldMags. net .net WorldMags.WorldMags. Visit myfavouritemagazines.co.net 9000 .. t Pick up the basics with Python tricks and t Teach kids code on the Raspberry Pi tutorials t Hack Minecraft! Build a GUI! Scan Twitter! Learn as you code with stacks of Get to grips with hacking and coding Take coding concepts further with our example-packed guides with the amazing Raspberry Pi exciting and easy-to-follow projects 9001 Like this? Then you’ll also love. WorldMags.uk today! WorldMags..net Build essential programming skills from the ground up Everyone can code with these plain-English guides – you’ll learn core programming concepts and create code to be proud of! Dozens of expert tutorials 148 pages of tips.
https://www.scribd.com/document/345403750/Coding-Made-Simple-2016-pdf
CC-MAIN-2018-51
en
refinedweb
Due by 11:59pm on Tuesday, 9/17. Instructions. We have provided a hw2.py starter file for the questions below. See the online submission instructions. Readings. Section 1.6 of the online text. Several doctests refer to the square function, which we define as: def square(x): """Return x squared.""" return x * x """ "*** YOUR CODE HERE ***" def factorial(n): """Return n factorial for n >= 0 by calling product. >>> factorial(4) 24 """ "*** YOUR CODE HERE ***" Q2. Show that both summation and product are instances of a more general function, called accumulate, with the following signature: def accumulate(combiner, start, n, term): """Return the result of combining the first n terms in a sequence.""" "*** """ "*** YOUR CODE HERE ***" def product_using_accumulate(n, term): """An implementation of product using accumulate. >>> product_using_accumulate(4, square) 576 """ "*** YOUR CODE HERE ***". f -- a function that takes one argument >>> double(square)(2) 16 """ "*** YOUR CODE HERE ***" Q4.. f -- a function that takes one argument n -- a positive integer >>> repeated(square, 2)(5) 625 >>> repeated(square, 4)(5) 152587890625 """ "*** YOUR CODE HERE ***" Hint: You may find it convenient to use compose1 from the lecture notes: def compose1(f, g): """Return a function h, such that h(x) = f(g(x)).""" def h(x): return f(g(x)) return h Q5. (Optional extra for experts).
http://www-inst.eecs.berkeley.edu/~cs61a/fa13/hw/hw2.html
CC-MAIN-2018-51
en
refinedweb
Hi, I am creating an app that search through a large json (250 000 rows), stored locally. Each page is pretty much the same on each page. I made a service, and import the json file in every page. I always need the full json file. However it takes couple of seconds to charge a page. How to avoid it and charge it only once when the app is launching? (Am I clear?) My service: import {HTTP_PROVIDERS} from 'angular2/http'; import {Injectable} from 'angular2/core'; import {Http, Response} from 'angular2/http'; import 'rxjs/Rx'; @Injectable() export class Page1Service { public dataDic : any; public constructor(private _http: Http) { this.dictionary(); } public dictionary(){ this._http.get('theJsonFile.txt') .map((response: Response) => response.json()) .subscribe(data=>{ this.dataDic=data; console.log("I am loaded"); }); } } How I Import i on eachpage: public constructor(private _DicoctionaryService: Page1Service) { } And then I access “dataDic” to do what I need to do. Should I bootstrap the json? Thanks, Stéphane.
https://forum.ionicframework.com/t/how-to-handle-a-large-json-without-re-loading-it-for-each-page/52662
CC-MAIN-2018-51
en
refinedweb
Enable data upload #include <curl/curl.h> CURLcode curl_easy_setopt(CURL *handle, CURLOPT_UPLOAD, long upload); The long parameter upload set to 1 tells the library to prepare for and perform an upload. The CURLOPT_READDATA(3) and CURLOPT_INFILESIZE(3) or CURLOPT_INFILESIZE_LARGE(3)(3) as usual. If you use PUT to a HTTP 1.1 server, you can upload data without knowing the size before starting the transfer if you use chunked encoding. You enable this by adding a header like "Transfer-Encoding: chunked" with CURLOPT_HTTPHEADER(3). With HTTP 1.0 or without chunked transfer, you must specify the size. 0, default is download Most TODO Always Returns CURLE_OK
https://www.carta.tech/man-pages/man3/CURLOPT_UPLOAD.3.html
CC-MAIN-2018-51
en
refinedweb
® Simulations Featuring Petrofac Webinar Q&A This document summarizes the responses to questions posed before and during the webinar. Additional questions should be directed to AspenTech Support. Questions Submitted Prior to the Event: Q: Please show the fundamental equations used to compute the overall coefficient. A: The equations used by Aspen Plate Fin Exchanger are documented on the Aspen HTFS Research Network. You will need to subscribe in order to view our Design Handbook and Research Reports. ____________________________________________________________________________________ Q: Can Aspen EDR be used with Aspen HYSYS Dynamics? A: Currently, Aspen EDR can only be used in steady-state simulation. ____________________________________________________________________________________ Q: Is there anything about modeling "core in kettle" in this webinar? Can you model “core in kettle” type exchangers using Aspen EDR? A: Yes, you can model core in kettle with Aspen Plate Fin Exchanger. Select plate-fin kettle as the Exchanger type in the Application Options, Figure 1. Then, specify the Kettle geometry on the plate-fin Kettles form, Figure 2. Figure 1: Select plate-fin kettle Figure 2: Specify the kettle geometry ___________________________________________________________________________________ Q: Is it possible for Aspen EDR to calculate a plate-fin heat exchanger operating as a reflux condenser? A: We do not currently have this capability in our plate-fin program. It is available in a Shell & Tube heat exchanger. ____________________________________________________________________________________ Questions Submitted During the Webinar: Q: What is EDR? A: EDR is an acronym for Exchanger Design & Rating and is AspenTech’s software family for designing Shell & Tube, Air Cooled, Plate, Plate Fin, and Fired Heater equipment. ____________________________________________________________________________________ Q: Is Aspen EDR is separate tool or an Aspen HYSYS module? A: Aspen EDR is a separate suite of products from Aspen HYSYS. Aspen EDR can be used as a stand- alone for heat exchanger fabricators, or it can be utilized in conjunction with Aspen HYSYS or Aspen Plus to simulate exchanger performance in the context of the flow sheet. ____________________________________________________________________________________ Q: What is the difference between MUSE and EDR Plate Fin? Is one better to use in certain applications? A: Plate-fin was released in 2009 and was designed to replace MUSE. It has a more advanced integration structure to handle different geometries of plate-fin exchangers more readily than MUSE could. We also greatly improved the integration with Aspen HYSYS. ____________________________________________________________________________________ Q: What versions of Aspen Plus and Aspen HYSYS can incorporate Aspen EDR designs? A: The integration has been possible for many years; however, V7.3 and higher shows that the integration is much easier to use. Notably, in V8.0 the full Aspen EDR console was accessible from the simulators for multiple types of heat exchangers. Q: If we have an existing plate-fin exchanger configuration, can we change the rating method from end point or weighted to EDR Plate Fin and run the model as usual to achieve the same results as going into the Aspen EDR environment? A: No, changing the model type to Aspen EDR will not run the Aspen EDR sizing optimization automatically. Once you change the model type to EDR Plate Fin in Aspen HYSYS, you will need to import the Aspen EDR file to specify the rigorous design. Once the file has been imported into Aspen HYSYS, the Aspen EDR model will run in simulation mode in the flowsheet, which means that the design will be fixed but the process conditions will be set by the Aspen EDR model. ____________________________________________________________________________________ Q: At the design stage of a new exchanger, we input the fouling factor. In debottlenecking, do we need to perform "fouling factor adjustment" to match actual exchanger performance, then perform the debottleneck? A: Typically, many clients would do this. In this case study, Petrofac tried to match the information from the client in the original case and then use the same fouling factors. ____________________________________________________________________________________ Q: Can you change Aspen EDR to select the smallest exchanger dimensionally or the lightest exchanger? A: Two different demonstrations were done during this webinar—one on Rigorous Shell & Tube sizing from within Aspen HYSYS and the other for designing a plate-fin exchanger and importing the model into Aspen HYSYS. The Shell & Tube design can be calculated to find the minimum area or the minimum cost (typically what customers use). The plate-fin exchanger is good for quickly and accurately finding the configuration of a multi-stream exchanger. This also designs on the basis of minimizing the area of the exchanger. The weights are calculated as a result of the design found. ___________________________________________________________________________________ Q: Some plate-fin manufacturers have Fin Codes with geometric information of fin size, height, thickness, pitch, etc. Does Aspen HYSYS have a database with those Fins Codes? What about Aspen EDR? A: Aspen EDR finds the best geometry of fins to meet the process requirements. It looks at fin height and fin frequency, as well as fin type and whether it’s plain, perforated, or serrated fins—then finds the best optimum. Our correlations are generally accepted in the industry and our single-phase, boiling, and condensing coefficients for these fin types are widely accepted. You can introduce fabricators coefficients into the system if you’d like to use those correlations, but ours are typically used as the baseline. ____________________________________________________________________________________ Q: How important was the hydraulic model for the design within Aspen EDR? A: The hydraulic model helped with the line drop, as well as the equipment drops. ____________________________________________________________________________________ Q: Could you use a better solvent to reduce to the minimum of the Mercaptan in the sweetening unit and respect the sales gas spec? A: In this specific case, the licensor had to be contacted and the client was reluctant to make any changes to the licensor processes. Also, this was an existing plant; therefore to make changes or suggest new systems was very difficult. For additional information, please contact AspenTech Support. Q: How do you properly design the layer patterns for a plate-fin? Does Aspen EDR do it by itself? A: You can directly specify layer patterns in Aspen Plate Fin Exchanger and look at interlayer effects. Many of the leading fabricators use our tool that way. When you’re designing and simulating the exchanger, for most purposes, the stream simulation used is more than adequate. If you want to get into the details of the design and ensure that the design will not be subject to high thermal stresses for example, then you can impose the layer pattern—but this is not an output of the first-shot design. This tends to be a detail that a plate-fin exchanger fabricator will specify to minimize the risk of damaging thermal stresses. It will have some impact on overall thermal performance, but usually this isn’t too significant. ____________________________________________________________________________________ Q: Is AspenTech currently working with vendors to have some standard products available as selectable models, similar to what has been done with plate frame models within Aspen EDR? A: Plate-fin exchangers are typically custom designed for each process application. Our design optimization suggests the appropriate geometry for each set of process conditions. ____________________________________________________________________________________ Q: Which fouling factors are used for all 3 streams on PFHX? A: In this design example, we didn’t specify any fouling resistance. Typically, fouling resistances in Plate- fin heat exchangers are very low because they are made for clean stream applications. If you want to specify fouling resistances for each stream, you can enter values on the Process Data form in the program input as shown below in Figure 3. Figure 3: Enter values on the Process Data form Q: Lauren ran the case after updating the geometry in Aspen EDR. What was that case for? A: In the recording, Lauren performs a demo of this and shows the value behind it. In Aspen Plate Fin Exchanger, if you go to the Application Options, you can see the drop down menu for Calculation Mode. The first option is Design which takes the inlet and outlet stream conditions and finds the appropriate exchanger area and geometry needed to achieve the desired heat transfer. When you update the file geometry, it takes the exchanger design found in Design mode and it makes it fixed—meaning you have the inlet stream conditions and the plate-fin geometry. Then, in Simulation mode it calculates the outlet stream conditions which gives you more accurate outlet conditions than your Aspen HYSYS flowsheet, because you’re using a rigorous model rather than a simple model. ____________________________________________________________________________________ Q: What are the recommended UA values for PFHX? A: This value is highly dependent on process conditions and will very in each case. ___________________________________________________________________________________ Q: Inside LNG exchangers in Aspen HYSYS, there is the possibility to simulate Wound Coil exchangers. Does Aspen EDR have this capability? A: There is a wound coil model in Aspen HYSYS, but it is not fully rigorous. ____________________________________________________________________________________ Q: What is the approach temp min/max for PFHX? A: Plate-fin exchangers can take advantage of very small temperature differences—sometimes as low as 1 degree Kelvin. The maximum temperature approach is determined by thermal stress limitations of the equipment and with large temperature differences, another exchanger type might be more suitable. ____________________________________________________________________________________ Q: Do the costs in Aspen EDR come from Aspen Capital Cost Estimator (ACCE)? A: The costs developed by Aspen EDR can be fine-tuned to increase estimate accuracy and ultimately be consistent with ACCE outputs, including major cost drivers such as material costs. Typically, the costs output by Aspen EDR are used as relative costs to compare one heat exchanger design to another. Later on, you may do rigorous costing for the entire project using one of the products from the Aspen Economic Evaluation suite, which includes stand-alone tools such as Aspen In Plant Cost Estimator or Activated Economics which is a feature in Aspen Plus and Aspen HYSYS. ____________________________________________________________________________________ Q: What is the Area Ratio and its significance? A: When you look at the sales gas exchanger, it stated that the area ratio was less than one—meaning that the area was inadequate to give you the outlet temperatures. In other words, the outlet temperature couldn’t be achieved with the existing configuration. ____________________________________________________________________________________ Q: Regarding hydraulics, how do you account for the equipment inlet/outlet nozzle elevation differences in Aspen HYSYS? A: In Aspen Plate Fin Exchanger and all of the other Aspen EDR programs, you can specify that gravitational pressure drop be taken into account. This can be very important in two phase applications, particularly if the exchanger is operating in thermosiphon mode. All of the Aspen EDR programs can factor in gravitational pressure drops and you can specify the elevations where necessary. See Figure 4. Figure 4: Take pressure changes into account __________________________________________________________________________________ Q: Does operation warning allow integration between Aspen EDR and simulation mode? A: Yes, operation warnings will be active when the Aspen EDR model is run in simulation mode. You can view them by opening the EDR Browser from the EDR Plate Fin tab. Figure 5: Operate the EDR Browser ____________________________________________________________________________________ Q: In a first analysis, constant UA need not be assumed, if flow rates increase because of increased heat transfer coefficients for sensible heat steams, can these increase at the 0.6 power of flow and translate into a higher U? A: Yes, if you can separate “U” and “A”, you can allow “U” to vary with process changes. You have to be careful about apportioning changes to the specific hot or cold streams. For single-phase exchanger applications, this may be adequate for limited changes in process flow rates. In any 2-phase applications—such as the exchangers in the gas process models we discussed during the Webinar on October 8 th —this approach will not work. In addition, for processes where we are using a lot of compressor power in a self-refrigerated process, exchanger pressure drop is very important. For both of these reasons, rigorous exchanger modeling is extremely valuable.
https://www.scribd.com/document/244383697/11-4477-Petrofac-Webinar
CC-MAIN-2018-51
en
refinedweb
Interesting. Im actually building something similar. A fullblown SQL implementation is bit overkill for my particular usecase and the query API is the final piece to the puzzle. But ill definitely have a look for some inspiration. Thanks! On Fri, Jun 28, 2013 at 3:55 AM, James Taylor <jtaylor@salesforce.com>wrote: > Hi Kristoffer, > Have you had a look at Phoenix ()? > You could model your schema much like an O/R mapper and issue SQL queries > through Phoenix for your filtering. > > James > @JamesPlusPlus > > > On Jun 27, 2013, at 4:39 PM, "Kristoffer Sjögren" <stoffe@gmail.com> > wrote: > > > Thanks for your help Mike. Much appreciated. > > > > I dont store rows/columns in JSON format. The schema is exactly that of a > > specific java class, where the rowkey is a unique object identifier with > > the class type encoded into it. Columns are the field names of the class > > and the values are that of the object instance. > > > > Did think about coprocessors but the schema is discovered a runtime and I > > cant hard code it. > > > > However, I still believe that filters might work. Had a look > > at SingleColumnValueFilter and this filter is be able to target specific > > column qualifiers with specific WritableByteArrayComparables. > > > > But list comparators are still missing... So I guess the only way is to > > write these comparators? > > > > Do you follow my reasoning? Will it work? > > > > > > > > > > On Fri, Jun 28, 2013 at 12:58 AM, Michael Segel > > <michael_segel@hotmail.com>wrote: > > > >> Ok... > >> > >> If you want to do type checking and schema enforcement... > >> > >> You will need to do this as a coprocessor. > >> > >> The quick and dirty way... (Not recommended) would be to hard code the > >> schema in to the co-processor code.) > >> > >> A better way... at start up, load up ZK to manage the set of known table > >> schemas which would be a map of column qualifier to data type. > >> (If JSON then you need to do a separate lookup to get the records > schema) > >> > >> Then a single java class that does the look up and then handles the > known > >> data type comparators. > >> > >> Does this make sense? > >> (Sorry, kinda was thinking this out as I typed the response. But it > should > >> work ) > >> > >> At least it would be a design approach I would talk. YMMV > >> > >> Having said that, I expect someone to say its a bad idea and that they > >> have a better solution. > >> > >> HTH > >> > >> -Mike > >> > >> On Jun 27, 2013, at 5:13 PM, Kristoffer Sjögren <stoffe@gmail.com> > wrote: > >> > >>> I see your point. Everything is just bytes. > >>> > >>> However, the schema is known and every row is formatted according to > this > >>> schema, although some columns may not exist, that is, no value exist > for > >>> this property on this row. > >>> > >>> So if im able to apply these "typed comparators" to the right cell > values > >>> it may be possible? But I cant find a filter that target specific > >> columns? > >>> > >>> Seems like all filters scan every column/qualifier and there is no way > of > >>> knowing what column is currently being evaluated? > >>> > >>> > >>> On Thu, Jun 27, 2013 at 11:51 PM, Michael Segel > >>> <michael_segel@hotmail.com>wrote: > >>> > >>>> You have to remember that HBase doesn't enforce any sort of typing. > >>>> That's why this can be difficult. > >>>> > >>>> You'd have to write a coprocessor to enforce a schema on a table. > >>>> Even then YMMV if you're writing JSON structures to a column because > >> while > >>>> the contents of the structures could be the same, the actual strings > >> could > >>>> differ. > >>>> > >>>> HTH > >>>> > >>>> -Mike > >>>> > >>>> On Jun 27, 2013, at 4:41 PM, Kristoffer Sjögren <stoffe@gmail.com> > >> wrote: > >>>> > >>>>> I realize standard comparators cannot solve this. > >>>>> > >>>>> However I do know the type of each column so writing custom list > >>>>> comparators for boolean, char, byte, short, int, long, float, double > >>>> seems > >>>>> quite straightforward. > >>>>> > >>>>> Long arrays, for example, are stored as a byte array with 8 bytes per > >>>> item > >>>>> so a comparator might look like this. > >>>>> > >>>>> public class LongsComparator extends WritableByteArrayComparable { > >>>>> public int compareTo(byte[] value, int offset, int length) { > >>>>> long[] values = BytesUtils.toLongs(value, offset, length); > >>>>> for (long longValue : values) { > >>>>> if (longValue == val) { > >>>>> return 0; > >>>>> } > >>>>> } > >>>>> return 1; > >>>>> } > >>>>> } > >>>>> > >>>>> public static long[] toLongs(byte[] value, int offset, int length) { > >>>>> int num = (length - offset) / 8; > >>>>> long[] values = new long[num]; > >>>>> for (int i = offset; i < num; i++) { > >>>>> values[i] = getLong(value, i * 8); > >>>>> } > >>>>> return values; > >>>>> } > >>>>> > >>>>> > >>>>> Strings are similar but would require charset and length for each > >> string. > >>>>> > >>>>> public class StringsComparator extends WritableByteArrayComparable { > >>>>> public int compareTo(byte[] value, int offset, int length) { > >>>>> String[] values = BytesUtils.toStrings(value, offset, length); > >>>>> for (String stringValue : values) { > >>>>> if (val.equals(stringValue)) { > >>>>> return 0; > >>>>> } > >>>>> } > >>>>> return 1; > >>>>> } > >>>>> } > >>>>> > >>>>> public static String[] toStrings(byte[] value, int offset, int > length) > >> { > >>>>> ArrayList<String> values = new ArrayList<String>(); > >>>>> int idx = 0; > >>>>> ByteBuffer buffer = ByteBuffer.wrap(value, offset, length); > >>>>> while (idx < length) { > >>>>> int size = buffer.getInt(); > >>>>> byte[] bytes = new byte[size]; > >>>>> buffer.get(bytes); > >>>>> values.add(new String(bytes)); > >>>>> idx += 4 + size; > >>>>> } > >>>>> return values.toArray(new String[values.size()]); > >>>>> } > >>>>> > >>>>> > >>>>> Am I on the right track or maybe overlooking some implementation > >> details? > >>>>> Not really sure how to target each comparator to a specific column > >> value? > >>>>> > >>>>> > >>>>> On Thu, Jun 27, 2013 at 9:21 PM, Michael Segel < > >>>> michael_segel@hotmail.com>wrote: > >>>>> > >>>>>> Not an easy task. > >>>>>> > >>>>>> You first need to determine how you want to store the data within a > >>>> column > >>>>>> and/or apply a type constraint to a column. > >>>>>> > >>>>>> Even if you use JSON records to store your data within a column, > does > >> an > >>>>>> equality comparator exist? If not, you would have to write one. > >>>>>> (I kinda think that one may already exist...) > >>>>>> > >>>>>> > >>>>>> On Jun 27, 2013, at 12:59 PM, Kristoffer Sjögren <stoffe@gmail.com> > >>>> wrote: > >>>>>> > >>>>>>> Hi > >>>>>>> > >>>>>>> Working with the standard filtering mechanism to scan rows that > have > >>>>>>> columns matching certain criterias. > >>>>>>> > >>>>>>> There are columns of numeric (integer and decimal) and string > types. > >>>>>> These > >>>>>>> columns are single or multi-valued like "1", "2", "1,2,3", "a", "b" > >> or > >>>>>>> "a,b,c" - not sure what the separator would be in the case of list > >>>> types. > >>>>>>> Maybe none? > >>>>>>> > >>>>>>> I would like to compose the following queries to filter out rows > that > >>>>>> does > >>>>>>> not match. > >>>>>>> > >>>>>>> - contains(String column, String value) > >>>>>>> Single valued column that String.contain() provided value. > >>>>>>> > >>>>>>> - equal(String column, Object value) > >>>>>>> Single valued column that Object.equals() provided value. > >>>>>>> Value is either string or numeric type. > >>>>>>> > >>>>>>> - greaterThan(String column, java.lang.Number value) > >>>>>>> Single valued column that > provided numeric value. > >>>>>>> > >>>>>>> - in(String column, Object value...) > >>>>>>> Multi-valued column have values that Object.equals() all provided > >>>>>> values. > >>>>>>> Values are of string or numeric type. > >>>>>>> > >>>>>>> How would I design a schema that can take advantage of the already > >>>>>> existing > >>>>>>> filters and comparators to accomplish this? > >>>>>>> > >>>>>>> Already looked at the string and binary comparators but fail to see > >> how > >>>>>> to > >>>>>>> solve this in a clean way for multi-valued column values. > >>>>>>> > >>>>>>> Im aware of custom filters but would like to avoid it if possible. > >>>>>>> > >>>>>>> Cheers, > >>>>>>> -Kristoffer > >>>>>> > >>>>>> > >>>> > >>>> > >> > >> >
http://mail-archives.apache.org/mod_mbox/hbase-user/201306.mbox/%3CCADSBNAjAWgQkt2xinwL9Tcb=K3MRs9h_92_iZKyG9bU6k+QQ6Q@mail.gmail.com%3E
CC-MAIN-2018-51
en
refinedweb
Current Version: Linux Kernel - 3.80 Synopsis #include <stdio.h> extern FILE *stdin; extern FILE *stdout; extern FILE *stderr; Description. Conforming To Notes Colophon License & Copyright From dholland@burgundy.eecs.harvard.edu Tue Mar 24 18:08:15 1998 This man page was written in 1998 by David A. Holland Polished a bit by aeb. %%%LICENSE_START(PUBLIC_DOMAIN) Placed in the Public Domain. %%%LICENSE_END 2005-06-16 mtk, mentioned freopen() 2007-12-08, mtk, Converted from mdoc to man macros
https://community.spiceworks.com/linux/man/3/stdin
CC-MAIN-2018-51
en
refinedweb
Other Factory Notes¶ other notes: The following works:extern "C" void Af(void); void (*Af_fp)(void) = &Af; For those that want a self-contained preprocessor macro to encapsulate this:#if defined(_WIN32) # if defined(_WIN64) # define FORCE_UNDEFINED_SYMBOL(x) __pragma(comment (linker, "/export:" #x)) # else # define FORCE_UNDEFINED_SYMBOL(x) __pragma(comment (linker, "/export:_" #x)) # endif #else # define FORCE_UNDEFINED_SYMBOL(x) extern "C" void x(void); void (*__ ## x ## _fp)(void)=&x; #endif Which is used thusly:FORCE_UNDEFINED_SYMBOL(Af) ----MSVC #pragma comment(linker, "/include:__mySymbol") gcc -u symbol ---- There is a better way to write that FORCE_UNDEFINED_SYMBOL macro. Just cast that function pointer to a void*. Then it works with any function - or data for that matter. Also, why bother with MSVC pragmas when the gcc part of your macro will work for MSVC as well. So my simplified version would be:#define FORCE_UNDEFINED_SYMBOL(x) void* __ ## x ## _fp =(void*)&x; Which is used thusly:FORCE_UNDEFINED_SYMBOL(Af) But it must be used in the program that includes the library that is having its symbols stripped. I believe (to be tested) that this export or extern might only work if these are in the main program ... which doesn't solve the problem for Geant4 (the point of the factory is that user code shouldn't need to explicitly name physics processes or lists they want to use). That said, other suggested "solutions" revolve around __pragma(comment (linker, "/include:_mySymbolName"))
https://cdcvs.fnal.gov/redmine/projects/g4/wiki/Other_Factory_Notes
CC-MAIN-2021-21
en
refinedweb
I require the m4 preprocessor macro command, but it has just gone missing from both the gold and plat* nodes in the Intel DevCloud. The CMake "find_program (M4EXISTS m4)" no longer works. Can you please reinstall it? Link Copied Hi Davis, Thanks for reaching out to us. Could you please tell the node in which you tried out. We couldn't find m4 in any gold nodes.However,we were able to find that m4 is installed in s001-n142 which is a platinum node.Could you please try requesting that particular node and see if it works. Please find the below commands: qsub -I -l nodes=s001-n142:ppn=2 m4 --help Screenshot attached for your reference. Hopes this resolve your issue. This is not a good solution. I can't assume that any given platinum node is available. I don't know which plat* node I tried. I used this script, and it failed: #PBS -l nodes=1:ppn=2:plat8153 #PBS -l walltime=24:00:00 cd $PBS_O_WORKDIR cd GraphBLAS make CC=gcc CXX=gcc JOBS=24 This has worked before, on any plat* node, but yesterday I got this error: % cat myjob_compile_plat_gcc.e506549 CMake Error at CMakeLists.txt:117 (message): m4 not found, but is required. Install via your system package manager, or download at or for Windows which is the output of this part of my GraphBLAS/CMakeLists.txt script: find_program ( M4EXISTS m4 ) if ( NOT M4EXISTS ) message ( FATAL_ERROR "m4 not found, but is required. Install via your system package manager, or download at or for Windows" ) endif ( ) I've been compiling my code on the DevCloud for months, on the gold nodes, with this script (which picks any gold node at random) and it has never failed: #PBS -l nodes=1:ppn=2:gold6128 #PBS -l walltime=24:00:00 cd $PBS_O_WORKDIR cd GraphBLAS make CC=gcc CXX=gcc JOBS=24 but it failed: cat myjob_compile_gold_gcc.e506799 CMake Error at CMakeLists.txt:117 (message): m4 not found, but is required. Install via your system package manager, or download at or for Windows This used to work, on any gold node. Why was m4 uninstalled? Can you please reinstall it on all gold and platinum nodes? Also, I cannot compile on the login nodes. It is a large program and the login nodes timeout. Also, n142 is not a node I can use. The Intel-led benchmark effort is using the "plat8153" nodes, which are nodes n145 to n156. Node n142 may have a platinum CPU, but it does have the "plat8153" designation. The m4 macro processor is a POSIX standard component that has been around for decades. The build systems for many applications rely on m4. It's on the login node, so please make sure it's available on the compute nodes too. Dear Davis, We understand your concern, we are working on this internally, will get back to you at the earliest. Hi Davis, We had informed the concerned admin team regarding this issue and they are working on this, will get back to you soon. Hi Davis, We are forwarding this case to Devcloud admin team. Hi Davis, Could you please let us know more details about the use case which you are trying to achieve by getting m4 macro preprocessor installed on Devcloud. Are you trying to do anything related to oneAPI using this? Hi - we are going to be implementing this request. We will let you know when it is finished. Hi Davis, Sorry for the delay in reply. We have installed the m4 macro preprocessor in plat8153 nodes(n145 to n156). We could able to verify this in nodes n145, n149, n150 & n153. Could you please also verify the same and let us know whether you are able to find it so we can close the case. Thanks. Hi Davis, We haven't heard back anything from you. So, we are closing this case. Please feel free to raise a new thread if you have any further issues. Thanks.
https://community.intel.com/t5/Intel-DevCloud/m4-macro-preprocessor-has-gone-missing/td-p/1128261
CC-MAIN-2021-21
en
refinedweb
PlatformNotSupportedException using .NET Speech Recognition So I am trying to recognize voices in C #, I am using System.Speech.Recognition and I have searched the internet trying a few snippets of code for some basic speech recognition, the best one I found was this: using System; using System.Text; using System.Windows.Forms; using System.Speech.Recognition; namespace SpeechRecognition { public partial class MainForm : Form { SpeechRecognitionEngine recognitionEngine; public MainForm() { InitializeComponent(); Initialize(); } private void Initialize() { recognitionEngine = new SpeechRecognitionEngine(); recognitionEngine.SetInputToDefaultAudioDevice(); recognitionEngine.SpeechRecognized += (s, args) => { foreach (RecognizedWordUnit word in args.Result.Words) { // You can change the minimun confidence level here if (word.Confidence > 0.8f) freeTextBox.Text += word.Text + " "; } freeTextBox.Text += Environment.NewLine; }; } private void startButton_Click(object sender, EventArgs e) { try { recognitionEngine.UnloadAllGrammars(); recognitionEngine.LoadGrammar(new DictationGrammar()); RecognitionResult result = recognitionEngine.Recognize(new TimeSpan(0, 0, 20)); if (result != null) { foreach (RecognizedWordUnit word in result.Words) { freeTextBox.Text += word.Text + " "; } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void startAsyncButton_Click(object sender, EventArgs e) { recognitionEngine.UnloadAllGrammars(); recognitionEngine.LoadGrammar(new DictationGrammar()); recognitionEngine.RecognizeAsync(RecognizeMode.Multiple); } private void stopButton_Click(object sender, EventArgs e) { recognitionEngine.RecognizeAsyncStop(); } private void startAsyncGrammarButton_Click(object sender, EventArgs e) { try { recognitionEngine.UnloadAllGrammars(); Grammar cg = CreateSampleGrammar(); recognitionEngine.LoadGrammar(cg); recognitionEngine.RecognizeAsync(RecognizeMode.Multiple); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private Grammar CreateSampleGrammar() { Choices commandChoices = new Choices("Calculator", "Notepad", "Internet Explorer", "Paint"); GrammarBuilder grammarBuilder = new GrammarBuilder("Start"); grammarBuilder.Append(commandChoices); Grammar g = new Grammar(grammarBuilder); g.Name = "Available programs"; return g; } } } Now I tried this and some others and they all resulted in the same error - PlatformNotSupportedException, in the error message: "No resolver installed". Is there a way to get around this? I have Windows 7 64-bit. source to share Speech Runtime 11 and Speech SDK 11 do not include speech recognition or speech synthesis (TTS or text-to-speech) Runtime languages. You must install them separately. The Runtime Language includes the language model, acoustic model, and other data necessary to provide a speech engine to perform speech recognition or TTS in a particular language. There are separate runtime languages for speech recognition or speech synthesis. The version of Runtime Languages that you download (for example, version 11.0) must match the version of the speech platform runtime you set. You can download the Runtime Languages using this link . From . I think you are using the version that comes with .NET, but several versions have been released since then. Microsoft Speech Services v11 is the current version as of today. If you install the SDK, add a link and change your namespace to Microsoft.Speech (instead of System.Speech), you should be updated. source to share What version of Windows 7 are you using? What language? Can you use the built-in dictation features of Windows 7? Are you using the Speech Recognition Control Panel app? See I thought that all versions of Windows 7 should come with a recognizer preinstalled. However, if you are using an unsupported language, this may not be the case. From fooobar.com/questions/83526 / ... : You can use APIs to query and define your installed recongizers Desktop: System.Speech.Recognition.SpeechRecognitionEngine.InstalledRecognizers () I found that I can also see which recognizers are installed by looking at the registry keys: Desktop recognizers: HKEY_LOCAL_MACHINE \ SOFTWARE \ Microsoft \ Speech \ recognizers \ tokens If you want to try a very simple program that might help, see fooobar.com/questions/639529 / ... source to share
https://daily-blog.netlify.app/questions/1892947/index.html
CC-MAIN-2021-21
en
refinedweb
import Koa from "koa"; import Router from "koa-router"; import request from "supertest"; const app = new Koa(); const router = new Router(); const client = request.agent(app.listen(3000)); router .get("/", async (ctx, next) => { try { let cv = ctx.cookies.get('temp'); if (cv) { The console.log(cv)// the second request did not get the value of the cookie, and the cookie was not stored, possibly because the content-type is set incorrectly. ctx.type = 'image/jpeg'; ctx.body = '233'; //Originally it was a buffer type data, which is brief here. ctx.status = 200; } else { await ctx.cookies.set('temp', '123456', {maxAge: 99999}); ctx.type = 'image/jpeg'; ctx.body = '233'; ctx.status = 200; bracket } catch (e) { console.log(e) ctx.status = 400; bracket }) app .use(router.routes()) .use(router.allowedMethods()); describe("test", () => { it("1", done => { client .get('/') .expect(200, (err, res) => { if (err) { done(err) } else { //The first request is that header inside has a set-cookie cookie = res.header["set-cookie"][0]; console.log(cookie); done() bracket }) }); it("2", done => { client .get('/') .expect(200, done) }); }) However, after I changed the content-type to another type, it can be stored correctly. Is there a problem with setting the content-type to image/jpeg? I checked that there is the content-type image/jpeg. Different browsers have different treatments for different content-type. It was found that these treatments were customized by the browser manufacturer after customization of the browser. So I guess it is possible that you gave image. His logic inside thinks there will be no cookie addition. Try a different browser?
https://ddcode.net/2019/04/20/why-cant-i-store-cookie-after-setting-content-type-to-image-jpeg/
CC-MAIN-2021-21
en
refinedweb
Matplotlib: custom projection for hemisphere / wedge I am looking at custom projection in matplotlib gallery - I am trying to change it should only plot the southern hemisphere. I adjusted the required [-pi / 2, pi / 2] limits to [-pi / 2.0]. Now I am looking at: def _gen_axes_patch(self): """ Override this method to define the shape that is used for the background of the plot. It should be a subclass of Patch. In this case, it is a Circle (that may be warped by the axes transform into an ellipse). Any data and gridlines will be clipped to this shape. """ #return Circle((0.5, 0.5), 0.5) return Wedge((0.5,0.5), 0.5, 180, 360) def _gen_axes_spines(self): return {'custom_hammer':mspines.Spine.circular_spine(self, (0.5, 0.5), 0.25)} As you can see, I replaced the Circle patch with a wedge. This is what the projection plot looks like now: The spine still follows the circle / ellipse - how can I indicate that I want the spine to follow the wedge border? I'm not sure what is the best way to change the spine, so any help would be much appreciated! Thank, Alex source to share Just for the record, you are sure to jump straight to the deep end of the pool if you are still new to python. (And you, luckily, right now!) What you are doing requires a fairly detailed knowledge of the inner workings of matplotlib, which is a fairly complex library. That being said, this is a good way to learn quickly! For something like this, you need to understand the internal architecture of how things are structured, not just "public" apis. For most of this, you need to dig in and "source". For any project, the internal processing documentation is the code itself. That was said, for a simple case, it's pretty straight forward. import numpy as np from matplotlib.projections.geo import HammerAxes import matplotlib.projections as mprojections from matplotlib.axes import Axes from matplotlib.patches import Wedge import matplotlib.spines as mspines class LowerHammerAxes(HammerAxes): name = 'lower_hammer' def cla(self): HammerAxes.cla(self) Axes.set_xlim(self, -np.pi, np.pi) Axes.set_ylim(self, -np.pi / 2.0, 0) def _gen_axes_patch(self): return Wedge((0.5, 0.5), 0.5, 180, 360) def _gen_axes_spines(self): path = Wedge((0, 0), 1.0, 180, 360).get_path() spine = mspines.Spine(self, 'circle', path) spine.set_patch_circle((0.5, 0.5), 0.5) return {'wedge':spine} mprojections.register_projection(LowerHammerAxes) if __name__ == '__main__': import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, projection='lower_hammer') ax.grid(True) plt.show() Dig in the method a bit _get_axes_spines : def _gen_axes_spines(self): """Return the spines for the axes.""" # Make the path for the spines # We need the path, rather than the patch, thus the "get_path()" # The path is expected to be centered at 0,0, with radius of 1 # It will be transformed by `Spine` when we initialize it path = Wedge((0, 0), 1.0, 180, 360).get_path() # We can fake a "wedge" spine without subclassing `Spine` by initializing # it as a circular spine with the wedge path. spine = mspines.Spine(self, 'circle', path) # This sets some attributes of the patch object. In this particular # case, what it sets happens to be approriate for our "wedge spine" spine.set_patch_circle((0.5, 0.5), 0.5) # Spines in matplotlib are handled in a dict (normally, you'd have top, # left, right, and bottom, instead of just wedge). The name is arbitrary return {'wedge':spine} Now there are several problems with this: - Things are not centered within the axis correctly - The axes patch can be scaled a little more to properly tackle the room within the axes. - We draw the grid lines for the full globe and then crop them. It would be more efficient to just draw them inside our "bottom" wedge. However, when we look at the structure HammerAxes , you will notice that many things (especially centering the axis patch) are effectively hard-coded in the transforms. (As they note in the comments, this means a "toy" example, and, assuming you're always dealing with a full globe, makes the math in transformations much easier.) If you want to fix this, you will need to configure several different transforms in HammerAxes._set_lim_and_transforms . However, it works well enough as it is, so I'll leave this as an exercise for the reader. :) (Be careful, this part is a little more complicated, as it requires detailed knowledge of matplotlib transforms.) source to share
https://daily-blog.netlify.app/questions/1891945/index.html
CC-MAIN-2021-21
en
refinedweb
Can't reach instances by floating IPs; can ping router Hi, I have an interesting problem I've not encountered before. I have recently created a new OpenStack environment that is functional in every respect but networking. I can instantiate instances and associate floating IPs, but when I attempt to ping or ssh, I receive no response from the nodes. I can ping the router from my external network. I have configured my external network as a flat network with network address 10.247.1.0/24 and gateway 10.247.1.1, according to my physical network. I then created a local internal network with address 10.10.0.0/24 and gateway 10.10.0.1. I created a router and added the two networks (10.247.1.5 and 10.10.0.1 as interfaces). I can ping the router: $ ping -q -c 3 10.247.1.5 PING 10.247.1.5 (10.247.1.5) 56(84) bytes of data. --- 10.247.1.5 ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 1999ms rtt min/avg/max/mdev = 0.153/0.171/0.200/0.023 ms I can also associate floating IPs with my instances. However, I cannot reach the instances themselves: $ ping -q -c 3 10.247.1.7 PING 10.247.1.7 (10.247.1.7) 56(84) bytes of data. --- 10.247.1.7 ping statistics --- 3 packets transmitted, 0 received, +3 errors, 100% packet loss, time 2015ms pipe 3 If I try to add instances to the external network itself, I cannot ping them, which leads me to believe there is some issue with my network configuration. Is there some configuration file or any more information I could provide that could help with this? I appreciate any information. Thanks! First thing to check: Does the instance's security group allow ping/ssh. Next, use console to see if the instance has received its fixed IP address. Can you ping the router from the instance. Can you ping external addresses from the instance. Can you ping the fixed IP from the DHCP namespace. Dear Bernd, when you answer questions, could you please do it with the "Add answer" functionality instead of "Add comment"? That would make it easier to see which questions already got answered. Thanks a lot! David I didn't consider it an answer, as I don't know exactly where the problem is.
https://ask.openstack.org/en/question/110749/cant-reach-instances-by-floating-ips-can-ping-router/?answer=120415
CC-MAIN-2021-21
en
refinedweb
Filter Elements in a NumPy Array - Filter Elements Using the fromiter()Method in NumPy - Filter Elements Using Boolean Mask Slicing Method in NumPy - Filter Elements Using the where()Method in NumPy Often, we need values from an array in a specific, usually in either an ascending or descending order. Sometimes, we also have to search elements from an array and retrieve them or filter some values based on some conditions. This article will introduce how to filter values from a NumPy array. Filter Elements Using the fromiter() Method in NumPy fromiter() creates a new one-dimensional array from an iterable object which is passed as an argument. We can apply conditions to the input array elements and further give that new array to this function to get the desired elements in a NumPy array. The syntax of the fromiter() method is below. fromiter(iterable, dtype, count, like) It has the following parameters. iterable- An iterable object that the function will iterate over. dtype- This parameter refers to the data type of the returned array. count- This is an optional integer parameter, and it refers to the number of elements that will be read in the iterable object. The default value of this parameter is -1, which means that all the elements will be read. like- This is an optional boolean parameter. It controls the definition of the returned array. The way to filter elements using the fromiter() method in NumPy is as follows. import numpy as np myArray = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) newArray = np.fromiter((element for element in myArray if element < 6), dtype = myArray.dtype) print(myArray) print(newArray) Output: [1 2 3 4 5 6 7 8 9] [1 2 3 4 5] First, we initialize a NumPy Array from which we wish to filter the elements. Then we iterate over the whole array and filter out the values that are less than 6. Then we cast this new array into a NumPy Array with the same data type as that of the original array. To learn more about this method, refer to its official documentation here Filter Elements Using Boolean Mask Slicing Method in NumPy This method is a bit weird but works like a charm in NumPy. We have to mention the condition inside the square or box brackets [] after the array. Then NumPy will filter out the elements based on the condition and return a new filtered array. This concept might not be clear and even seem tricky to some, but don’t worry. We have some examples below to explain it a little better. import numpy as np myArray = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) newArray1 = myArray[myArray < 6] # Line 1 newArray2 = myArray[myArray % 2 == 0] # Line 2 newArray3 = myArray[myArray % 2 != 0] # Line 3 newArray4 = myArray[np.logical_and(myArray > 1, myArray < 5)] # Line 4 newArray5 = myArray[np.logical_or(myArray % 2 == 0, myArray < 5)] # Line 5 print(myArray) print(newArray1) print(newArray2) print(newArray3) print(newArray4) print(newArray5) Output: [1 2 3 4 5 6 7 8 9] [1 2 3 4 5] [2 4 6 8] [1 3 5 7 9] [2 3 4] [1 2 3 4 6 8] As mentioned above, we add some conditions between the square brackets, and the target array was filtered based on those conditions. The variable storing the array, which is in this case myArray, represents a single element of the array inside the square brackets. To apply multiple conditions and use logical operators, we use two NumPy methods, namely, logical_and() and logical_or() for the logic and or or respectively. myArray < 6- It filters the values that are less than 6 myArray % 2 == 0- It filters the values that are divisible by 2 myArray % 2 != 0- It filters the values that are not divisible by 2 np.logical_and(myArray > 1, myArray < 5)- It filters the values greater than one and less than five. np.logical_or(myArray % 2 == 0, myArray < 5)- It filters the values that are either divisible by two or less than five. Filter Elements Using the where() Method in NumPy Here is the last method, which uses the where() method from the NumPy library. It filters the elements from the target array based on a condition and returns the indexes of the filtered elements. You can also use this method to change the values of elements that satisfy the condition. The syntax of the where() method is shown below. where(condition, x, y) It has the following parameters. condition- It is the boolean condition for which each element of the array is checked. x- It is a value given to elements satisfying the condition or a computation carried on the satisfying elements. y- It is a value given to elements not satisfying the condition or a computation carried on the unsatisfying elements. Let’s see how to use this function to filter out the elements. import numpy as np myArray = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) newArray1 = myArray[np.where(myArray < 7)[0]] newArray2 = myArray[np.where(myArray % 2 == 0)[0]] newArray3 = myArray[np.where(myArray % 2 != 0)[0]] print(myArray) print(newArray1) print(newArray2) print(newArray3) Output: [1 2 3 4 5 6 7 8 9] [1 2 3 4 5 6] [2 4 6 8] [1 3 5 7 9] In the above snippet, all the elements that satisfy the condition were returned as an array. The where() function returns a tuple of NumPy arrays. So we only consider the first array, which is our answer. As I mentioned above, you can also assign custom values and perform custom actions over elements when they satisfy the specified condition and when they not. Below is an example of that. import numpy as np myArray = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) newArray1 = np.where(myArray < 7, 5, -1) newArray2 = np.where(myArray % 2 == 0, myArray ** 2, 0) newArray3 = np.where(myArray % 2 != 0, myArray, -1) newArray4 = np.where(myArray % 2 != 0, myArray, myArray) newArray5 = np.where(myArray % 2 != 0, 0, myArray) print(myArray) print(newArray1) print(newArray2) print(newArray3) print(newArray4) print(newArray5) Output: [1 2 3 4 5 6 7 8 9] [ 5 5 5 5 5 5 -1 -1 -1] [ 0 4 0 16 0 36 0 64 0] [ 1 -1 3 -1 5 -1 7 -1 9] [1 2 3 4 5 6 7 8 9] [0 2 0 4 0 6 0 8 0] Have a look at the output. See how the elements are changing based on conditions and based on values and calculations you provided to manipulate the elements to the where() function.
https://www.delftstack.com/howto/numpy/numpy-filter-elements-in-array/
CC-MAIN-2021-21
en
refinedweb
asn1_find_structure_from_oid - API function #include <libtasn1.h> const char * asn1_find_structure_from_oid(ASN1_TYPE definitions, const char * oidValue); ASN1_TYPE definitions ASN1 definitions const char * oidValue value of the OID to search (e.g. "1.2.3.4"). Search the structure that is defined just after an OID definition. NULL when oidValue not found, otherwise the pointer to a constant string that contains the element name defined just after the OID. Copyright © 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.. Copying and distribution of this file, with or without modification, are permitted in any medium without royalty provided the copyright notice and this notice are preserved. The full documentation for libtasn1 is maintained as a Texinfo manual. If the info and libtasn1 programs are properly installed at your site, the command info libtasn1 should give you access to the complete manual.
http://huge-man-linux.net/man3/asn1_find_structure_from_oid.html
CC-MAIN-2021-21
en
refinedweb
I installed the ncsdk 1.12 version on a fresh RPi model 3 with Raspbian stretch. I could run /ncappzoo/apps/hello_ncs_py with no issue.I could run /ncappzoo/apps/hello_ncs_py with no issue. When I am running the following script: from mvnc import mvncapi as mvnc # grab a list of all NCS devices plugged in to USB print("[INFO] finding NCS devices...") devices = mvnc.EnumerateDevices() # if no devices found, exit the script if len(devices) == 0: print("[INFO] No devices found. Please plug in a NCS") quit() # use the first device since this is a simple test script print("[INFO] found {} devices. device0 will be used. " "opening device0...".format(len(devices))) device = mvnc.Device(devices[0]) device.OpenDevice() # open the CNN graph file print("[INFO] loading the graph file into RPi memory...") path = '/home/pi/ssd_on_pi/graph' with open(path, mode="rb") as f: graph_in_memory = f.read() # load the graph into the NCS print("[INFO] allocating the graph on the NCS...") graph = device.AllocateGraph(graph_in_memory) I have this error: [INFO] finding NCS devices... [INFO] found 1 devices. device0 will be used. opening device0... [INFO] loading the graph file into RPi memory... [INFO] allocating the graph on the NCS... Traceback (most recent call last): File "allocate_graph.py", line 25, in <module> graph = device.AllocateGraph(graph_in_memory) File "/usr/local/lib/python3.5/dist-packages/mvnc/mvncapi.py", line 203, in AllocateGraph raise Exception(Status(status)) Exception: mvncStatus.ERROR So initially I installed the API-only mode, I received this error when I ran the above file. Then, I uninstalled API-only and tried the full SDK, still the same error :( I think the problem is that somehow I am not able to allocate the graph onto the device. I generated the graph using a separate ubuntu vm, and I was able to successfully run the above code in the vm.I think the problem is that somehow I am not able to allocate the graph onto the device. I generated the graph using a separate ubuntu vm, and I was able to successfully run the above code in the vm. Any clue what could be wrong here? Link Copied I just tried generating the graph from ncsdk/examples/caffe/GoogLeNet in the vm and copied it to the Pi. When running run.py in Pi, the same error shows up :( pi@raspberrypi:~/workspace/ncsdk-1.12.00.01/examples/caffe/GoogLeNet $ python3 run.py Device 0 Address: 1.4.1 - VID/PID 03e7:2150 Starting wait for connect with 2000ms timeout Found Address: 1.4.1 - VID/PID 03e7:2150 Found EP 0x81 : max packet size is 64 bytes Found EP 0x01 : max packet size is 64 bytes Found and opened device Performing bulk write of 865724 bytes... Successfully sent 865724 bytes of data in 2788.732941 ms (0.296055 MB/s) Boot successful, device address 1.4.1 Found Address: 1.4.1 - VID/PID 03e7:f63b done Booted 1.4.1 -> VSC Traceback (most recent call last): File "run.py", line 66, in <module> graph = device.AllocateGraph(blob) File "/usr/local/lib/python3.5/dist-packages/mvnc/mvncapi.py", line 203, in AllocateGraph raise Exception(Status(status)) Exception: mvncStatus.ERROR HALP… @ama @PINTO @ama Does "~/workspace/ncsdk-1.12.00.01/examples/caffe/GoogLeNet/cpp/run_cpp" work? @ama Have you tried using a powered USB hub? @Tome_at_Intel Yes I am indeed using a USB hub to connect the Movidius stick to the Pi. The only thing that is connected to the hub is the Pi. It is mainly because if I directly plug in the stick to the Pi, I will not have access to the other 3 USB ports :(, so essentially I am using the hub as a usb extension cable. @Tome_at_Intel @PINTO Issue resolved. It is because that I am using a USB hub as an extension cable to connect the stick to the Pi. Everything works as expected when I am using an actual USB extension cable. I strongly suggest to have this added as a reminder in the RPi installation guide @ama Glad you figured it out and narrowed it down to your USB hub. The brand of the USB hub I've been using is a 7 port powered Anker USB hub and they seem to work well with the NCS so far. We do recommend using a powered USB hub whenever you can, although its not required. I have this listed in my Troubleshooting guide at.
https://community.intel.com/t5/Intel-Distribution-of-OpenVINO/Having-issues-with-loading-a-graph-onto-the-NCS/td-p/659534
CC-MAIN-2021-21
en
refinedweb
So, I've just unveiled my new open-source UI library called Isotope. It's fast, lightweight, modular and overall - I think it's pretty good. Anyway, if you're interested in trying something new and fresh, maybe consider giving Isotope a try? You can go straight up to the docs or bear with me, as we're going to make a simple TODO app, allowing us to learn the basics of Isotope. Setup Isotope is written in TypeScript that's transpiled down to pure JS, which requires no additional tooling to get you up & running. To set up our project, we'll use npm (but yarn is also an option). We'll start by running run npm init to create our base package.json file. Then, install the Isotope and Bulma - a CSS-only library that will make our app look slightly prettier! npm install @isotope/core bulma Now, you can use Isotope with any bundler you want (or go buildless), but here, we'll use the Parcel - a zero-config bundler that doesn't require any setup whatsoever, and thus it's great for any kind of playground-like scenario! npm install --dev parcel-bundler With the bundler installed, we can start writing some code, or more specifically, the HTML! <!DOCTYPE html> <html> <head> <title>Isotope Playground</title> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <script src=""></script> </head> <body> <script src="src/index.js"></script> </body> </html> Aside from the basic boilerplate, we also load the Font Awesome icon library through its CDN and include our main JS file, which is where the whole magic will happen. And that's it for HTML! Parcel will take care of the rest. Just make sure you've got all the files in correct places and run npx parcel index.html to start the dev server. Container So, now that we're all set up, let's get right into making our app. First, we have to create the a container that will house all our TODOs, as well as a form to add them. import { createDOMView } from "@isotope/core"; import "bulma/css/bulma.min.css"; const view = createDOMView(document.body); const container = view .main({ classes: ["container", "fluid"], }) .div({ classes: ["columns", "is-centered", "is-vcentered", "is-mobile"], }) .div({ classes: ["column", "is-narrow"], styles: { width: "70%", }, }); In the snippet above we create our main container. We start by importing the createDOMView() function from the Isotope library, which is responsible for creating a view - a top-level node, that attaches to the specified DOM element to render its content. Here, we attach our view to the <body> element, making Isotope effectively take control of the entire website. It's a nice solution for our current situation, but keep in mind that Isotope's progressive nature, allows it to attach to any element to control even the smallest pieces of your UI. So, we've got our top-level node attached to the <body> element. This is a great start for our application. In Isotope a node is the most important entity and having access to even a single one, grants you the power to create more. That's essentially what we do in the next line. // ... const container = view.main({ classes: ["container", "fluid"], }); // ... We use the view reference we've got to create a new node - a child node that will append a new element to the DOM. For that, we use the main() method - a method from the Isotope's HTML node pack. Isotope's node packs are essentially bundles of shortcut methods that get applied directly to the node's prototype. main() is one of such methods. It simplifies the creation of the <main> element, which would otherwise require a bit longer syntax ( child("main")). To configure our new node, we have to use a configuration object. Here, we make use of the classes config property, to add some CSS classes to the element. So, to summarize, we create a new node which represents a <main> element - child to <body> - that has "container" and "fluid" CSS classes applied to it. On a side note - all of the used class names come from Bulma, which we import at the top of our JS file thanks to Parcel CSS imports support. The main() like all other methods from the HTML node pack, returns the newly-created node. In this way we get the ability to add new child nodes to this node, effectively building our UI. const container = view .main({ classes: ["container", "fluid"], }) .div({ classes: ["columns", "is-centered", "is-vcentered", "is-mobile"], }) .div({ classes: ["column", "is-narrow"], styles: { width: "70%", }, }); As you can see, when setting up our container, we put this chainability of Isotope to a good use. In the end, it's the last node in the chain that gets assigned to the container variable. Also, notice how we use another configuration property - styles - to set CSS styles of the underlying element. At the moment our HTML structure should look somewhat like this: <body> <main> <div> <div></div> </div> </main> </body> Basic elements Now that we've got the container, it's time to add some real elements to our app! // ... container .h1({ classes: ["has-text-centered", "title"], }) .text("Isotope TODO"); container.form(); container.ul(); Here we're adding 3 new child nodes to the container: header, form, and list. Apart from the usual stuff, notice how we use a special text() method to set the text of the created <h1> element. Now, after the header, we create two more elements - <form> and <ul>. These 2 elements are where the rest of our app will be placed. With this in mind, it's easy to see how our code can become bloated over time pretty easily. To prevent that, we'll move both of these elements into separate components, which themselves will be placed within separate modules. Creating components In Isotope things are meant to be simple - and so are the components, which themselves are nothing more than simple functions. Take a look: // src/form.js const Form = (container) => { const form = container.form(); return form; }; export { Form }; Here, in a new file (src/form.js), we create a new Isotope component - Form. As you can see, it's a function that accepts a parent node, and optionally returns a new node. Such a component can then be used through the $() method: // src/index.js // ... import { Form } from "./form"; // ... container.$(Form); If the component function returns a node, then the same node is returned from the $() method. Otherwise, the $() method returns the node it was called upon (in our case it would be the container) for easier chaining. As you can see, Isotope components are really easy to use. Let's now set up our List component as well. // src/list.js const List = (container) => { const list = container.ul(); return list; }; export { List }; // src/index.js // ... import { Form } from "./form"; import { List } from "./list"; // ... container.$(Form); container.$(List); Building form With our components set up, it's time to build our form for accepting new TODOs! // src/index.js const Form = (container) => { const form = container.form({ classes: ["field", "has-addons"], styles: { justifyContent: "center" }, }); const input = form.div({ classes: ["control"] }).input({ attribs: { type: "text", placeholder: "TODO" }, classes: ["input"], }); form .div({ classes: ["control"] }) .button({ classes: ["button", "is-primary"] }) .span({ classes: ["icon", "is-small"] }) .i({ classes: ["fas", "fa-plus"] }); return form; }; export { Form }; So, above we create our form layout. As you can see, there's not much new when compared to what we already know. There's only the attribs configuration property that's used to set attributes of the node's DOM element. Apart from that, you can also notice how helpful Isotope's method chaining capabilities can be when creating the submit button. Reactivity With our form ready, we now need to make it reactive. Isotope is a statically-dynamic UI library, which (apart from sounding cool) means that it has a bit different approach to reactivity. Instead of making the entire UI reactive out-of-the-box, Isotope requires you to specifically mark certain nodes as dynamic by either creating their own state or by linking them to other dynamic nodes. For the purpose of our TODO app, we'll explore both of these ways. First, we have to identify what kind of data should be made reactive. In our case - it's the list of TODOs that we'll operate on, and the current user input for creating new TODOs. So, we've got 2 properties to create in our state - input and todos. The state should be accessible by both the Form (to write to input), as well as List (to display TODOs) component. Thus, I think it'll be best to initialize our state on the container node. // src/index.js // ... const container = view .main({ classes: ["container", "fluid"], }) .div({ classes: ["columns", "is-centered", "is-vcentered", "is-mobile"], }) .div({ classes: ["column", "is-narrow"], state: { input: "", todos: [], }, styles: { width: "70%", }, }); // ... So, we go back to our index.js file and set up our state on the last node (the one that's assigned to the container variable. To do this, we make use of the state property, supplying it with our state object, containing initial values. And that's it! - Now our container is reactive! Event handling Let's get back to the src/form.js file and put this reactivity to good use. First, we'll handle the <form> element itself. // src/form.js const Form = (container) => { // ... form.on("submit", (event) => { const input = container.getState("input"); const todos = container.getState("todos"); if (input) { container.setState({ input: "", todos: [ ...todos, { text: input, id: Math.random().toString(36).substr(2, 9), }, ], }); } event.preventDefault(); }); // ... }; // ... On the form node, we use the on() method to listen to the submit event of the <form> element. Isotope provides a set of event-related methods ( on(), off() and emit()), which are universal and can be used to handle all kinds of events - DOM, custom, and Isotope-related ones. In our handling function, we first access the input and todos properties from the container's state. Remember that Isotope doesn't handle data passing on its own - you need to do that by having a reference to a stateful node, through custom events or in any other way you find suitable. In our case, because the container that holds the data is also the direct parent of our component, we can use that reference to access its state. Isotope provides 2 methods to work with the state - getState() and setState(). To access one of state properties, you have to pass its key to the getState() method. That's what we do to access the input and todos properties. After that, we check whether the user has entered anything in the form (i.e. if the input isn't empty) and if so, we transform it into a new TODO. In our case, a TODO is an object with text and id property, where text contains TODO's actual content, and id is a random string, to help us identify a given TODO later on. We use the setState() method to update the container's state. The method accepts an object that should be applied on top of the previous state. It doesn't have to include all the properties the original state object had, but we assign both anyway. input gets assigned an empty string to clean the value of <input> element, while todos is assigned a new array. Know that because arrays are passed by reference in JavaScript, you can as well use the push() method on the todos variable that we've got from the getState() call. It's just a matter of personal preference as to which way you prefer. Just know that you'll eventually have to call the setState() method (even with an empty object), to let Isotope know that it should update the node. Lifecycle events Now we'll move to our input node to get it set up as well. // src/form.js const Form = (container) => { // ... const input = form .div({ classes: ["control"] }) .input({ attribs: { type: "text", placeholder: "TODO" }, classes: ["input"], }) .on("input", ({ target }) => { container.setState({ input: target.value }); }) .on("node-updated", ({ node }) => { node.element.value = container.getState("input"); }); // ... }; // ... Here, we once again use Isotope's chainability ( on() method returns the node it was called upon) to listen to 2 events one after another. First, we handle the input event, which is native to HTML <input> element. Inside the listener, we use the setState() method, to set the value of input property to the current input. Next up, we listen to one of Isotope's node lifecycle events - node-updated. This event is emitted every time a node updates - either via a change in state or in the result of a link. The listener is passed an object with node property, giving it access to the node the listener is connected to. We use that reference to access the node's underlying HTML element through the element property and set it's value to the value of input property from the container's state. Through the code above, we've gained complete control over the <input> element. It's value is completely reliant on the value of the container's state. Linking With the event listeners in place, our form is almost done. The last issue we have to solve is related to the node-updated event our input node is listening to. The problem is that it'll never be triggered as the node neither has its own state, nor it's linked to any other nodes. To fix that issue, we have to write one magic line: // src/form.js // ... container.link(input); // ... With the use of the link() method, we link the input node to the container. Linking in Isotope allows us to let one node know that it should update when the other one does so. What we do with the line above is letting input know that it should update (thus triggering the node-updated event) every time the container's state is changed. It's important to remember that linking can happen between any 2 nodes - no matter where they are in the hierarchy. A single node can have multiple nodes linked to itself, but it can be linked only to a single node. Displaying TODOs Now that our form is ready and can accept new TODOs, we have to take care of displaying them. Let's get back to our List component and start our work: // src/list.js const List = (container) => { const list = container.ul({ classes: () => ({ list: container.getState("todos").length > 0, }), }); container.link(list); return list; }; export { List }; First, we make a few changes to our base list node. We use the classes configuration property, but in a bit different way than usual. Instead of passing an array of CSS class names, we pass a function, which returns an object. In this way, we let Isotope know that it should rerun the function and update CSS classes every time the node updates. The value that the function returns gets later applied like usual. An object that the function returns is an alternative way of applying CSS class names. The object's keys represent certain CSS class names and their values - booleans that indicate whether the given CSS class should be applied or removed. As a side note, other configuration properties ( attribs and styles) also accept a similar function configuration. So, we apply the "list" CSS class name only when our TODOs list contains at least one TODO. But, in order for our dynamic classes to work, we also have to link the list node to the container, which we do in the next line. List rendering Now that we've got our <ul> element set up, we only need to display our TODOs. In Isotope, this can be done with a special map() method. // src/list.js // ... list.map( () => container.getState("todos"), ({ id, text }, node) => { const item = node.li({ classes: ["list-item"] }); const itemContainer = item.div({ classes: ["is-flex"], styles: { alignItems: "center" }, }); itemContainer.span({ classes: ["is-pulled-left"] }).text(text); itemContainer.div({ styles: { flex: "1" } }); itemContainer .button({ classes: ["button", "is-text", "is-pulled-right", "is-small"], }) .on("click", () => { const todos = container.getState("todos"); const index = todos.findIndex((todo) => todo.id === id); container.setState("todos", todos.splice(index, 1)); }) .span({ classes: ["icon"] }) .i({ classes: ["fas", "fa-check"] }); return item; } ); // ... map() takes 2 arguments - the list of items to map and a function used to map them. The items list can have multiple forms. For static lists it can be an array of unique strings, numbers or objects with an id key. For dynamic lists, where items get modified on the way, you can pass parent's state property key, or a function that determines the items, as we do above. Because todos is a property of container's state - not the list's, a function is the only solution we have. Inside the mapping function, we get access to the current item (in our case items are objects with text and id properties), the parent node ( list) and the index of the current item. We only use 2 of those values. Overall, the rest of the code is nothing new - we create nodes, set their CSS classes, styles, attributes and text, and listen to the click event on the button, to remove a certain TODO when needed. What do you think? So, with that, our TODO app is ready. You can check out the finished results through the CodeSandbox playground, right here: To summarize, through making this very simple app, we've learned pretty much most of the Isotope API. That's right - it's that simple. Remember that although the API and the library itself is small and simple, it can still be used to create really incredible and very performant apps and websites! If you like what you see, definitely check out Isotope's documentation, and drop a star on its GitHub repo! For more content about Isotope and web development as a whole, follow me on Twitter, Facebook or right here on Dev.to. Discussion (0)
https://dev.to/areknawo/making-a-todo-app-in-isotope-pm
CC-MAIN-2021-21
en
refinedweb
Hamburger menu icons for React, with CSS-driven transitions. Created to be as elegant and performant as possible. This means no JavaScript animations, no transitions on non-cheap properties and a small size. npm install hamburger-react When using one hamburger, ~1.5 KB will be added to your bundle (min + gzip). Visit the website for full documentation, API and examples. A basic implementation looks as follows: import Hamburger from 'hamburger-react' const [isOpen, setOpen] = useState(false) <Hamburger toggled={isOpen} toggle={setOpen} /> Or without providing your own state: <Hamburger onToggle={toggled => ...} /> Yes. Since the creation of these burgers in 2015 a lot of similar ones have appeared, with one or more of the following downsides:). You can use the label property to supply an ARIA label for the icon. The icons are hooks-based, and will work with React 16.8.0 ('the one with hooks') or higher.
https://awesomeopensource.com/project/luukdv/hamburger-react
CC-MAIN-2021-21
en
refinedweb
In the VB.NET code below, A.B. is reported as a redundant qualifier, when it clearly is not. -TC Class A Public Shared B As Object End Class Class B End Class Public Class C Dim D As Object = A.B.ToString End Class In the VB.NET code below, A.B. is reported as a redundant qualifier, when it clearly is not. A follow-up: The consequences of this bug are significant. Essentially, if you have a shared member that shares a name with a class, you are likely to get inappropriate "Qualifier is redundant" warnings. Several dozen appear in my code, and they are frustrating because they prevent me from clearing away all Resharper warnings. For instance, I'm currently getting the warning because I have a class which exposes a shared property called "DataSet", and I'm using that class in a file which imports System.Data, which has a "DataSet" class. When I refer to the property, I often get an invalid "Qualifier is redundant" warning. The obvious workaround is to rename things until the error goes away. I consider this to be an unsatisfactory solution because in some situations it prevents me from using the best and most obvious name for a member or a class. I would be grateful if someone at JetBrains would attend to this and let me know if a fix is in the pipeline. -TC i think you should generally avoid to use variable or property names are equal to class names. This always leads to confusion. Regards Klaus Perhaps, but that is beside the point. Resharper reports "Qualifier is redundant" when there is no redundant qualifier. -TC Sorry to revive a ghost, but I am also getting false positives, and this doesn't seem to be resolved. In this case, I've linked to somebody else's code, so it is not quite as easy for me to give a minimal example which I can be confident is the same, but here are the short details: It is in VB (not my choice!) If I call A = B.Create(param) I am told 'Qualifier is redundant' with respect to B. It isn't, because if I remove B, as occurs on an automatic code cleanup, I am then told 'Create' is ambiguous. Create is a function with overloads. B is a module in a namespace which is imported.
https://resharper-support.jetbrains.com/hc/en-us/community/posts/206651645--Qualifier-is-redundant-False-Positive?page=1
CC-MAIN-2021-21
en
refinedweb
If we have two unrelated sequences of DNA, how long would we expect the longest common substring of the two sequences to be? Since DNA sequences come from a very small alphabet, just four letters, any two sequences of moderate length will have some common substring, but how long should we expect it to be? Motivating problem There is an ongoing controversy over whether the SARS-CoV-2 virus contains segments of the HIV virus. The virologist who won the Nobel Prize for discovering the HIV virus, Luc Montagnier, claims it does, and other experts claim it does not. I’m not qualified to have an opinion on this dispute, and do not wish to discuss the dispute per se. But it brought to mind a problem I’d like to say something about. This post will look at a simplified version of the problem posed by the controversy over the viruses that cause COVID-19 and AIDS. Namely, given two random DNA sequences, how long would you expect their longest common substring to be? I’m not taking any biology into account here other than using an alphabet of four letters. And I’m only looking at exact substring matches, not allowing for any insertions or deletions. Substrings and subsequences There are two similar problems in computer science that could be confused: the longest common substring problem and the longest common subsequence problem. The former looks for uninterrupted matches and the latter allows for interruptions in matches in either input. For example, “banana” is a subsequence of “bandana” but not a substring. The longest common substring of “banana” and “anastasia” is “ana” but the longest common subsequence is “anaa.” Note that the latter is not a substring of either word, but a subsequence of both. Here we are concerned with substrings, not subsequences. Regarding the biological problem of comparing DNA sequences, it would seem that a substring is a strong form of similarity, but maybe too demanding since it allows no insertions. Also, the computer science idea of a subsequence might be too general for biology since it allows arbitrary insertions. A biologically meaningful comparison would be somewhere in between. Simulation results I will state theoretical results in the next section, but I’d like to begin with a simulation. First, some code to generate a DNA sequence of length N. from numpy.random import choice def dna_sequence(N): return "".join(choice(list("ACGT"), N)) Next, we need a way to find the longest common substring. We’ll illustrate how SequenceMatcher works before using it in a simulation. from difflib import SequenceMatcher N = 12 seq1 = dna_sequence(N) seq2 = dna_sequence(N) # "None" tells it to not consider any characters junk s = SequenceMatcher(None, seq1, seq2) print(seq1) print(seq2) print(s.find_longest_match(0, N, 0, N)) This produced TTGGTATCACGG GATCACAACTAC Match(a=5, b=1, size=5) meaning that the first match of maximum length, ATCAC in this case, starts in position 5 of the first string and position 1 of the second string (indexing from 0). Now let’s run a simulation to estimate the expected length of the longest common substring in two sequences of DNA of length 300. We’ll do 1000 replications of the simulation to compute our average. def max_common_substr_len(a, b): # The None's turn off junk detection heuristic s = SequenceMatcher(None, a, b, None) m = s.find_longest_match(0, len(a), 0, len(b)) return m.size seqlen = 300 numreps = 1000 avg = 0 for _ in range(numreps): a = dna_sequence(seqlen) b = dna_sequence(seqlen) avg += max_common_substr_len(a, b) avg /= numreps print(avg) When I ran this code I got 7.951 as the average. Here’s a histogram of the results. Expected substring length Arratia and Waterman [1] published a paper in 1985 looking at the longest common substring problem for DNA sequences, assuming each of the four letters in the DNA alphabet are uniformly and independently distributed. They show that for strings of length N coming from an alphabet of size b, the expected length of the longest match is asymptotically 2 logb(N). This says in our simulation above, we should expect results around 2 log4(300) = 8.229. There could be a couple reasons our simulation results were smaller than the theoretical results. First, it could be a simulation artifact, but that’s unlikely. I repeated the simulation several times and consistently got results below the theoretical expected value. I expect Arratia and Waterman’s result, although exact in the limit, is biased upward for finite n. Update: The graph below plots simulation results for varying sequence sizes compared to the asymptotic value, the former always below the latter. Arratia and Waterman first assume i.i.d. probabilities to derive the result above, then prove a similar theorem under the more general assumption that the sequences are Markov chains with possibly unequal transition probabilities. The fact that actual DNA sequences are not exactly uniformly distributed and not exactly independent doesn’t make much difference to their result. Arratia and Waterman also show that allowing for a finite number of deletions, or a number of deletions that grows sufficiently slowly as a function of n, does not change their asymptotic result. Clearly allowing deletions makes a difference for finite n, but the difference goes away in the limit. Related posts [1] Richard Arratia and Michael S. Waterman. An Erdős-Rényi Law with Shifts. Advances in Mathematics 55, 13-23 (1985). One thought on “Expected length of longest common DNA substrings” Réndi -> Rényi
https://www.johndcook.com/blog/2020/04/18/expected-length-of-longest-common-dna-substrings/
CC-MAIN-2021-21
en
refinedweb
Hi All, I know many threads are there for this query, but I am not able to find the exact solution to my problem. I want to pull the files which starts with A5_Work_Orders_* from SFTP server and I want to pull them from /5060/A5toSAP folder on SFTP server. In the directory I have given as ~/5060/A5SAP/ in the filename what details I should give so that it will pick all the files that starts with A5???? Also I have ticket the ASMA attributes and I am using the namespace - and I have ticked the filename parameter. Now my another query is I need to archive the files on PI server, so I have ticked the option and I want to archive the file as it is (with the same name) so I have added only the archive name - /A5/inbound/5060/A5toSAP/archive directoy. Do I need to enter any other details? Please let me know on above points. Thanks in advance.
https://answers.sap.com/questions/10561582/sftp-sender-channel-configuration-query.html
CC-MAIN-2021-21
en
refinedweb
MXRT1050 FlexSPI module have LUT which support up to 16 sequences which is equivalent to 16 Flash commands. Many NOR Flash chips today support much more than 16 commands. 1. Is there a way to support NOR Flash devices with more than 16 flash commands ? 2. Is there a way to work with FlexSPI module without the LUT ? Hi Ronen Avihav, Yes, the LUT just can support up to 16 sequences, the LUT table have the size limit. So, from my own viewpoint, I think if you think 16 sequences is not enough, after you finish the 16 sequences code, you can configure the LUT table again, just add the other command sequence, then update the LUT table and run the code. I think the FlexSPI module need to use the LUT table to work, but more details, I will help you to check it with according department, then give you feedback. Please waiting patiently.. ------------------------------------------------------------------------------- Thank you Kerry for the quick reply . if you already going to ask the R&D guys about this, Can you please also add client request for the next chips to have more than 16 sequences ? (i.e: 32) Waiting for your reply, Ronen Hi Ronen Avihav, You can use the method which I recommend you in the above reply. About your request, I will record it, but I don't make sure it can be accepted by the according department. Thanks a lot for your understanding.. ------------------------------------------------------------------------------- Hello, I am having the same issue regarding the 16 sequence max limit. I need more than 16 sequences. I have tried to create a second LUT table to use after the Flexspi configuration, but when I try to update the LUT using FLEXSPI_UpdateLUT, it does not appear to work. What are the complete steps for updating the LUT with different sequences? Do I need to reinitialize the Flexspi? Hi Here's the LUT reconfiguration from the uTasker project (I think that the NXP SDK has something similar). The use is fnEnterLUT(pointer to the new look up table, reference to the bus - 0 for FlexSPI1 and 1 or FlexSPI2). It works for QSPI or hyper flash. static void fnEnterLUT(const FLEXSPI_LUT_ENTRY *ptrTable, int iBus) { int iLUT = 0; volatile unsigned long *ptrLUT; iMX_FLEX_SPI *ptrFlexSPI = (iMX_FLEX_SPI *)FLEX_SPI_BLOCK; #if FLEX_SPI_INTERFACES > 1 if (iBus != 0) { ptrFlexSPI = (iMX_FLEX_SPI *)FLEX_SPI2_BLOCK; } #endif // Update look-up table // while ((ptrFlexSPI->STS0 & (FLEX_SPI_STS0_ARBIDLE | FLEX_SPI_STS0_SEQIDLE)) != (FLEX_SPI_STS0_ARBIDLE | FLEX_SPI_STS0_SEQIDLE)) {} // wait until the bus is idle ptrFlexSPI->LUTKEY = FLEX_SPI_LUTKEY_KEY; ptrFlexSPI->LUTCR = FLEX_SPI_LUTCR_UNLOCK; uMemset((void *)&ptrFlexSPI->LUT0, 0x00, (FLEX_SPI_LUT_ENTRIES * sizeof(unsigned long))); // ensure all non-used entries are clear while (ptrTable[iLUT].ulReference != NOR_CMD_LUT_SEQ_IDX_END_OF_TABLE) { ptrLUT = &ptrFlexSPI->LUT0; ptrLUT += ((ptrTable[iLUT].ulReference & 0x0f) * 4); // move to the LUT entry if (*ptrLUT != 0) { _EXCEPTION("Overlapping LUT indexes being used!!!!"); } *ptrLUT++ = ptrTable[iLUT].ulEntrySequence[0]; // enter the sequence(s) *ptrLUT = ptrTable[iLUT].ulEntrySequence[1]; #if defined BOOT_HYPER_FLASH *(++ptrLUT) = ptrTable[iLUT].ulEntrySequence[2]; *(++ptrLUT) = ptrTable[iLUT].ulEntrySequence[3]; #endif iLUT++; } ptrFlexSPI->LUTKEY = FLEX_SPI_LUTKEY_KEY; ptrFlexSPI->LUTCR = FLEX_SPI_LUTCR_LOCK; ptrFlexSPI->MCR0 |= FLEX_SPI_MCR0_SWRESET; // perform a reset of the module _WAIT_REGISTER_TRUE(ptrFlexSPI->MCR0, FLEX_SPI_MCR0_SWRESET); // wait for reset to complete } Note that a SW reset is made to the module before using the new table.
https://community.nxp.com/t5/i-MX-RT/Usage-of-FlexSPI-LUT-in-i-MXRT/m-p/1209113/highlight/true
CC-MAIN-2021-21
en
refinedweb
Solved! Go to Solution.> Your mock-response should be a groovy script. There you can read in your file (filename based on the submitted ordernumber) and then you have to set an internal variable like this: def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context ); def holder = groovyUtils.getXmlHolder(mockRequest.requestContent); String sInputOrderNumber = holder.getNodeValue("//<... here you need the tag from incomming request>"); lUtil.log(LogUtil.LogLevel.INFO, " Incomming ordernumber: " + sInputOrderNumber); ... // read correct file based on ordernumber String sResult = ... getOrderNumberResult( sInputOrderNumber ); // set context variable context.setProperty("result", sResult); Then, in your mock-response, you only put something like this: ${result} That means, whatever you read in from your file will be returned to the caller. That also means tha you should have your complete returnmessage in your mock-file. ( P.S.: Of course, you can have your retunr message in the response and only put the return variable there it belonged in the message.) Hi, Sorry to hop in, but assuming you're happy to extract the file name from the mockRequest (using Groovy), then does the following give you what you need: 1. In your mock action, create a new Mock MockResponse with dispatch type 'SEQUENCE' e.g. called 'default' 2. In the MockResponse (default) add a script e.g. def fileName = "1234.txt" //Extract this value from the request (ask if you need help) def responseFileContent = new StringBuilder() File testDataFile = new File("/Users/test/$fileName") //Load file containing test data response testDataFile.eachLine {content, lineNumber -> responseFileContent.append(content) //Add each line of test data file to a String } mockResponse.responseContent=responseFileContent //Populate response body mockResponse.responseHttpStatus=200 //set status code (can also be done in UI) def headers = mockResponse.responseHeaders headers["Content-Type"]=["text/xml"] mockResponse.responseHeaders=headers //Headers can also be set in the UI Here is a screen shot: This should load and despatch the contents of the file /Users/test/1234.txt as the body of the mock response. All that should then be needed is for you to add some script before my script to set fileName to the value you want to extract from the mockRequest object (let me know if you need any help with this). Setting the responseHttpStatus and responseHeaders is optional, as it can be set in the Mock Response UI - I added it as it can be useful in the case where you want to conditionally simulate error / 404 / 500 statuses or respond with different content types! Hope this helps, Rupert Hi, Ok, sorry, in that case I'm not totally sure what you need.. Where you say compare order number, compare file names, load the matching file - I take that to mean something like: 1. Request is made to your mock 2. You extract the ordernumber from the request 3. Build a file path to load the ordernumber.txt file (shown in the sample I provided) Is this what you mean? Then what do you want to do? Since the title of the post says 'get soap mock response from external file' - I was thinking you would then want to despatch the loaded file contents as the mock's response? Just to clear myself again. I have ordernumber tag in request . it can have multiple input values (dynamic) say $ordnb. All the time I need to check if ($ordnb).txt file is present in the path C:Users/test path or not. If present I need to load mock response from ($ordnb).txt file. Else throw an error as Response not found in response.
https://community.smartbear.com/t5/SoapUI-Open-Source/How-to-get-soap-mock-response-from-external-file/m-p/110919/highlight/true
CC-MAIN-2021-21
en
refinedweb
The Unity MLAPI (Mid level API) is a framework that simplifies building networked games in Unity. It offers low level access to core networking while at the same time providing high level abstractions. The MLAPI aims to remove the repetitive tasks and reduces the network code dramatically, no matter how many of the modular features you use. Getting Started To get started, check the Multiplayer Docs Site. Community and Feedback For general questions, networking advice or discussions about MLAPI, please join our Discord Community or create a post in the Unity Multiplayer Forum. Compatibility The MLAPI supports all major Unity platforms. To use the WebGL platform a custom WebGL transport based on web sockets is needed. MLAPI is compatible with Unity 2019 and newer versions. Development We follow the Gitflow Workflow. The master branch contains our latest stable release version while the develop branch tracks our current work. This repository is broken into multiple components, each one implemented as a Unity Package. . ├── com.unity.multiplayer.mlapi # The core netcode SDK unity package (source + tests) └── testproject # A Unity project with various test implementations & scenes which exercise the features in the above package(s). Contributing The MLAPI is an open-source project and we encourage and welcome contributions. If you wish to contribute, be sure to review our contribution guidelines Issues and missing features If you have an issue, bug or feature request, please follow the information in our contribution guidelines to submit an issue. Example Here is a sample MonoBehaviour showing a chat script where everyone can write and read from. This shows the basis of the MLAPI and the abstractions it adds. public class Chat : NetworkBehaviour { private NetworkList<string> ChatMessages = new NetworkList<string>(new MLAPI.NetworkVariable.NetworkVariableSettings() { ReadPermission = MLAPI.NetworkVariable.NetworkVariablePermission.Everyone, WritePermission = MLAPI.NetworkVariable.NetworkVariablePermission.Everyone, SendTickrate = 5 }, new List<string>()); private string textField = ""; private void OnGUI() { if (IsClient) { textField = GUILayout.TextField(textField, GUILayout.Width(200)); if (GUILayout.Button("Send") && !string.IsNullOrWhiteSpace(textField)) { ChatMessages.Add(textField); textField = ""; } for (int i = ChatMessages.Count - 1; i >= 0; i--) { GUILayout.Label(ChatMessages[i]); } } } }
https://unitylist.com/p/1414/com.Unity-.multiplayer-.mlapi
CC-MAIN-2021-21
en
refinedweb
Versions used - Rails(5.2+) - Google Maps API (v3) In this tutorial, I’ll be teaching you how to strictly integrate a static google map into your rails project. I will also show you how to change the color of the marker and how to add more if need be. This tutorial will assume you have some previous background information on rails. Don’t worry, this is still a very basic beginner level tutorial and not complicated at all. Examples used in this tutorial will be from my mod 2 project at Flatiron School that uses Ruby 2.6.1 and Rails 6.0 (a basic setup that wasn't generated with scaffold). Step 1: Set up You will need to create a rails project. To get started, In your terminal, you will input: rails new “your_project_name" After creating your new rails project you now will need to generate some models, controllers, and views. This part is all up to you on how those files will be generated. I personally used: rails g resource ExampleName again this is solely dependent on you. Make sure you have these columns in your table: t.float “latitude” t.float “longitude” t.string “address” Step 2: Geocode Gem We will not explicitly define what latitude and longitude is (unless you want to) because the geocode gem will do that for us. Geocode will take your address and turn it into latitude and longitude coordinates and google will take that information and display a map of those coordinates. In your terminal run: gem install 'geocoder’ or in your gem file include: gem ‘geocoder’ now you will need to: bundle install After successfully installing the geocode gem you will then need to go to your model that has the address/latitude/longitude columns and insert: geocoded_by :address after_validation :geocode, if: :address_changed? - (the if conditional will run the geocode if the address has changed as there is no point in running the gem if the address is the same.) Step 4: Obtaining Google API You will now need to obtain your own Google API key to be able to use the map. This is not as hard as it may seem. Please read on how to do so here! A couple of tips while doing this: - Make sure to add an active billing account (don't worry unless you get 25,000+ visits to your website you will not be charged. Google also gives you credit towards your account.) - Only request Static Maps API as you won't need anything else. - Restrict your API to only be used on a certain website page. If someone gets ahold of your API they will not be able to use it on any other website. Step 5: Custome Credentials(optional but not really) The reason this is “optional but not really” is because you don't have to hide/secure your API key to run a map but if you don't anyone can inspect your website HTML and see/copy your Google API. Skip this step if you don't want to make a custom credential for your Google API. In your terminal inside your rails project insert: rails credentials:edit Quick note: If your text editor is not set to default or you just want to open this up into a specific text editor you will need to run: EDITOR="name_of_editor --wait" rails credentials:edit This line of code will tell your editor to wait before closing the file you need to add your credentials to. If you run the first code that doesn't include the wait command and the file that opens up is blank, you will need to run the wait command. You should see that a “credentials.yml.enc” file and a “master.key” file should have generated if you didn't have one already and the file you will need to edit. Insert the master key into your “.gitignore” file so you don’t push your master.key to GitHub(rails does this automatically but to be safe). Like I said before, if this file is blank then you need to tell your editor to wait. Delete the “credentials.yml.enc” and “master.key” file and start this step over. Now we will add our Google API by inserting name_you_choose: "your_api_key" Make sure to save and close this file after inserting your credentials. To see if this worked you can run this command in your rails console(rails c). Rails.application.credentials.name_you_chose This should return your API key. If you get nil then either the file your edited wasn't saved/closed or you edited the blank page(maybe other issues as well). Vist this rails doc for more information on custom credentials. Step 6: Methods Assuming you’ve done everything correctly we will now need to add our method to our model file(or anywhere you want that its ability to be called on appropriately). Insert this code: def google_map(center)"{center}&size=500x500&zoom=17&key=#{Rails.application.credentials.name_you_chose}"end - Notice, the end of the code is interpolating your API key. Do not forget to insert the name you made for your API key inside of your custom credential. The above code snippet assumes you followed the custom credential step but if you did not; insert this code instead: def google_map(center)"{center}&size=500x500&zoom=17&key=[YOUR_API_KEY]"end - You can manipulate the size of the Map itself or the zoom inside of the map as well by changing those factors inside of the URL. With this done, you will now go to the view file that you’d like the Static Google Map to appear and insert: image_tag google(center: model_name.address) or image_tag google(center: [model_name.latitude, model_name.longitude].join(',')) You should now see your static map appear in your browser! Step 7: Markers In the google_map(center) method you will want to add a marker directly into the Google Map URL. - “size:” manipulates the size of the marker. - “color:” manipulates the color of the marker. - “label:” manipulates the label of the marker. - “%7C” Pipe symbol: separates each property from one another. markers=size:small%7Ccolor:red%7Clabel:C%7C You will add this snippet after the “/staticmap?” and before “center=”. "?--><--center=#{center}&size=500x500&zoom=17&key=[YOUR_API_KEY]" - arrows inside URL represent where to add the markers snippet; do not include arrows. Conclusion: Integrating a Google Map API to your rails project is not as hard as it seemed before actually doing so. I tried to be as transparent as possible so you can avoid making the same simple mistakes I made; the internet lacks simple direct solutions to most of the issues I ran into. Below will be linked to other articles and videos that helped me through my issues.
https://brodrick-george.medium.com/how-to-integrate-a-google-static-map-api-in-your-rails-project-80be28b99e0c?source=post_internal_links---------7----------------------------
CC-MAIN-2021-21
en
refinedweb
INET6 Internet protocol version 6 family Synopsis: #include <netinet/in.h> struct sockaddr_in6 { uint8_t sin6_len; sa_family_t sin6_family; in_port_t sin6_port; uint32_t sin6_flowinfo; struct in6_addr sin6_addr; uint32_t sin6_scope_id; }; Description: Protocols The INET6 family consists of the: - IPv6 network protocol - Internet Control Message Protocol version 6 (ICMP ) - Transmission Control Protocol (TCP ) - User Datagram Protocol (UDP ). TCP supports the SOCK_STREAM abstraction, while UDP supports the SOCK_DGRAM abstraction. Note that TCP and UDP are common to INET and INET6. A raw interface to IPv6 is available by creating an Internet SOCK_RAW socket. The ICMPv6 message protocol may be accessed from a raw socket. The INET6 protocol family is an updated version of the INET family. While INET implements Internet Protocol version 4, INET6 implements Internet Protocol version 6. Addressing IPv6 addresses are 16-byte quantities, stored in network standard (big-endian) byte order. The header file <netinet/in.h> defines this address as a discriminated union. Sockets bound to the INET6 family use the structure shown above. You can create sockets with the local address :: (which is equal to IPv6 address 0:0:0:0:0:0:0:0) to cause wildcard matching on incoming messages. You can specify the address in a call to connect() or sendto() as :: to mean the local host. You can get the :: value by setting the sin6_addr field to 0, or by using the address contained in the in6addr_any global variable, which is declared in <netinet6/in6.h>. The IPv6 specification defines scoped addresses, such as link-local or site-local addresses. A scoped address is ambiguous to the kernel if it's specified without a scope identifier. To manipulate scoped addresses properly in your application, use the advanced API defined in RFC 2292. A compact description on the advanced API is available in IP6 . If you specify scoped addresses without an explicit scope, the socket manager may return an error. The KAME implementation supports extended numeric IPv6 address notation for link-local addresses. For example, you can use fe80::1%de0 to specify fe80::1 on the de0 interface. The getaddrinfo() and getnameinfo() functions support this notation. With special programs like ping6 , you can disambiguate scoped addresses by specifying the outgoing interface with extra command-line options. The socket manager handles scoped addresses in a special manner. In the socket manager's routing tables or interface structures, a scoped address's interface index is embedded in the address. Therefore, the address contained in some of the socket manager structures isn't the same as on the wire. The embedded index becomes visible when using the PF_ROUTE socket or the sysctl() function. You shouldn't use the embedded form. Interaction between IPv4/v6 sockets The behavior of the AF_INET6 TCP/UDP socket is documented in the RFC 2553 specification, which states: - A specific bind on an AF_INET6 socket (bind() with an address specified) should accept IPv6 traffic to that address only. - If you perform a wildcard bind on an AF_INET6 socket (bind() to the IPv6 address ::), and there isn't a wildcard-bound AF_INET socket on that TCP/UDP port, then the IPv6 traffic as well as the IPv4 traffic should be routed to that AF_INET6 socket. IPv4 traffic should be seen by the application as if it came from an IPv6 address such as ::ffff:10.1.1.1. This is called an IPv4 mapped address. - If there are both wildcard-bound AF_INET sockets and wildcard-bound AF_INET6 sockets on one TCP/UDP port, they should operate independently: IPv4 traffic should be routed to the AF_INET socket, and IPv6 should be routed to the AF_INET6 socket. However, the RFC 2553 specification doesn't define the constraint between the binding order, nor how the IPv4 TCP/UDP port numbers and the IPv6 TCP/UDP port numbers relate each other (whether they must be integrated or separated). The behavior is very different from implementation to implementation. It is unwise to rely too much on the behavior of the AF_INET6 wildcard-bound socket. Instead, connect to two sockets, one for AF_INET and another for AF_INET6, when you want to accept both IPv4 and IPv6 traffic. Because of the security hole, by default, NetBSD doesn't route IPv4 traffic to AF_INET6 sockets. If you want to accept both IPv4 and IPv6 traffic, use two sockets. IPv4 traffic may be routed with multiple per-socket/per-node configurations, but, it isn't recommended. See IP6 for details. Based on: RFC 2553, RFC 2292
https://developer.blackberry.com/playbook/native/reference/com.qnx.doc.neutrino.lib_ref/topic/i/inet6_proto.html
CC-MAIN-2021-21
en
refinedweb
Now that we have Cocos2d-x installed and configured and our project created, we are going to take a look at basic graphics operations. This tutorial assumes you ran through the prior part and created a project already. I am going to assume you have a working AppDelegate, so I will only focus on creating a new scene object. The only changes you should have to make are to change your delegate to #include a different file and change the type of scene you call createScene() on. Ok, let’s jump right in with with a simple example. First we are going to need an image to draw. Personally I am going to use this somewhat… familiar image: It’s 400×360, with a transparent background named decepticon.png. Of course you can use whatever image you want. Just be certain to add the image to the resources directory of your project. Ok, now the code to display it. GraphicsScene.h #pragma once #include "cocos2d.h" class GraphicsScene : public cocos2d::Layer { public: static cocos2d::Scene* createScene(); virtual bool init(); CREATE_FUNC(GraphicsScene); }; GraphicsScene.cpp #include "GraphicsScene.h" USING_NS_CC; Scene* GraphicsScene::createScene() { auto scene = Scene::create(); auto layer = GraphicsScene::create(); scene->addChild(layer); return scene; } bool GraphicsScene::init() { if ( !Layer::init() ) { return false; } auto sprite = Sprite::create("decepticon.png"); sprite->setPosition(0, 0); this->addChild(sprite, 0); return true; } Now when you run this code: Hmmm, probably not exactly what you expected to happen, but hey, congratulations, you just rendered your first sprite! So, what exactly is happening here? Well after we created our sprite we called: sprite->setPosition(0, 0); This is telling the sprite to position itself at the pixel location (0,0). There are two things we can take away from the results. 1- The position (0,0) is at the bottom left corner of the screen. 2- By default, the position of a sprite is relative to it’s own center point. Which way is up? One of the most confusing things when working in 2D graphics is dealing with all the various coordinate systems. There are two major approaches to dealing with locations in 2D, having the location (0,0) at the top left of the screen and having the location (0,0) at the bottom left of the screen. This point is referred to as the Origin. It is common for UI systems, the most famous of which being Windows, to set the origin at the top left of the screen. It is also most common for graphics files to store their image data starting from the top left pixel, but by no means is this universal. On the other hand OpenGL and most mathematicians treat the bottom left corner of the screen as the origin. If you stop and think about it, this approach makes a great deal of sense. Think back to your high school math lessons ( unless of course you are in high school, in which case pay attention to your math lessons! ) and you will no doubt have encountered this graphic. This is a graphic of the Cartesian plane and it is pretty much the foundation of algebra. As you can clearly see, the positive quadrant ( the quarter of that graph with both positive x and y values ) is in the top right corner. Quite clearly then, to a mathematician the value (0,0) is at the bottom left corner of the top right quadrant. There are merits to both approaches of course, otherwise there would be only one way of doing things! This will of course lead to some annoying situations, where one API for example delivers touch coordinates in UI space, relative to the top left corner, or when you load a texture that is inverted to what you actually wanted. Fortunately, Cocos2d-x provides functionality to make these annoyances a little bit less annoying. Just be aware going forward, that coordinate systems can and do change! Also be aware, unlike some frameworks, Cocos2d-x does *NOT* allow you to change the coordinate system. The origin in Cocos2d-x is always at the bottom left corner. Sometimes positioning relative to the middle can be ideal, especially when dealing with rotations. However, sometimes you want to position relative to another point, generally using the top left or bottom left corner. This is especially true if for example you want to, say… align the feet of a sprite to the top of a platform. Changing the way a sprite ( or any Node ) is positioned is extremely simple in Cocos2d-x. This is done using something called an Anchor Point. Simply change the code like so: auto sprite = Sprite::create("decepticon.png"); sprite->setAnchorPoint(Vec2(0, 0)); sprite->setPosition(0, 0); And presto! Now our sprite is positioned relative to it’s bottom left corner. However, setAnchorPoint() might not take the parameters you expect it to. Yes, you are passing it in x and y coordinates that represent the location on the sprite to perform transforms relative to. However, we are dealing with yet another coordinate system here, sometimes referred to as Normalized Device Coordinates (NDC). These values are represented by two numbers, one for x and one for y, from 0 to 1, and they are a position within the sprite. Sprite? If you are new to game programming, the expression “sprite” might be new to you. The expression was termed way back in 1981 by a Texas Instruments engineer describing the functionality of the TMS9918 chip. Essentially a sprite was a bitmap image with hardware support to be movable. Early game hardware could handle a few sprites, often used to represent the player and enemies in the world. In real world examples, in Super Mario Brothers, Mario, the mushrooms, coins and such would be sprites. These days, “Sprite” is basically a bitmap image ( or portion of a bitmap, we’ll see this later ) along with positional information. These days the concept of hardware sprites doesn’t really exist anymore. I am making this sound entirely more complicated than it actually is. Just be aware the value (0,0) is the bottom left corner of the sprite, (1,1) is the top right of the sprite and (0.5,0.5) would be the mid point of the sprite. These coordinate system is extremely common in computer graphics and is used heavily in shaders. You may have heard of UV coordinates, for positioning textures on 3D objects. UV coordinates are expressed this way. Therefore, if you want to position the sprite using it’s mid point, you would instead do: sprite->setAnchorPoint(Vec2(0.5, 0.5)); Another important concept to be aware of is a sprite’s positioning is relative to it’s parent. Up until now our sprite’s parent was our layer, let’s look at an example with a different Node as a parent. This time, we are going to introduce another sprite, this one using this image: It’s a 200×180 transparent image named autobot.png. Once again, add it to the resources folder of your project. Now let’s change our code slightly: bool GraphicsScene::init() { if ( !Layer::init() ) { return false; } auto sprite = Sprite::create("decepticon.png"); auto sprite2 = Sprite::create("autobot.png"); sprite->setAnchorPoint(Vec2(0.0,0.0)); sprite2->setAnchorPoint(Vec2(0.0, 0.0)); sprite->addChild(sprite2); sprite->setPosition(100, 100); sprite2->setPosition(0, 0); this->addChild(sprite, 0); return true; } And when we run this code: There’s a couple very important things being shown here. Until this point, we’ve simply added our Sprite to our Layer, but you can actually parent any Node to any other Node object. As you can see, both Sprite and Layer inherit from Node, and Node’s form the backbone of a very important concept called a scene graph. One very important part of this relationship is the child’s position is relative to it’s parent. Therefore sprite2’s (0,0) position is relative to the origin of sprite1 ( not the anchor, origin and anchor are not the same thing and only anchors can be changed ), so moving sprite2 also moves sprite1. This is a great way to create hierarchies of nodes, for example you could make a tank out of a sprite for it’s base and another representing it’s turret. You could then move the base of the tank and the turret would move with it, but the turret itself could rotate independently.Scenegraph A scenegraph is a pretty simple concept. It’s basically the data structure used to hold the contents of your game. In Cocos2d-x, the scene graph is simply a tree of Node dervived objects. There exists Scene node that is pretty much an empty node with the intention of adding other nodes to it. You then add various nodes to it, nodes to those nodes, etc. An overview of how you can use this system in Cocos2d-x is available here. So what do you do when you want to get a node’s position in the world, not relative to it’s parent? Fortunately Node has that functionality built in: Vec2 worldPosition = sprite2->convertToWorldSpace(sprite2->getPosition()); worldPosition’s value would be (100,100). There is also an equivalent function for getting a world space coordinate in node space. So, in summary: - The world is composed of Node objects, including Scene, Sprite and Layer - The screen origin is at the bottom left corner of the screen, always - Nodes are positioned, scaled and rotated relative to their anchor point - The default anchor point of a sprite is (0.5,0.5), which is it’s mid point - Anchor points are defined with a value from (0,0) to (1,1), with (0,0) being bottom left corner and (1,1) being the top right - Nodes can have other nodes as children. When the parent moves, the child moves with it - Child node’s origin is the bottom left corner of their parent - Anchor point and origin are not the same thing - Sprites can only have other sprites as children ( EDIT – No longer true! There can however be some performance ramifications. Will discuss later ) So that covers the basics of dealing with graphics. Now that we know how to position and parent nodes, next time we will look at something a bit more advanced.
https://gamefromscratch.com/cocos2d-x-tutorial-series-basic-sprites-positioning-parenting-and-coordinate-systems/
CC-MAIN-2021-21
en
refinedweb
Generates FilterBankEvents containing raw camera images with interleaved pixels (YUVYUVYUV... instead of YYY...UUU...VVV...). More... #include <InterleavedYUVGenerator.h> Generates FilterBankEvents containing raw camera images with interleaved pixels (YUVYUVYUV... instead of YYY...UUU...VVV...).. List of all members. constructor Definition at line 9 of file InterleavedYUVGenerator.cc. constructor, you can pass which channels to interleave Definition at line 19 of file InterleavedYUVGenerator.cc. [virtual] destructor Definition at line 31 of file InterleavedYUVGenerator.h. [private] don't call [protected, virtual] 161 of file InterleavedYUV 148 of file InterleavedYUVGenerator.cc. Referenced by loadBuffer(). deletes the arrays Reimplemented from FilterBankGenerator. Definition at line 107 of file InterleavedYUVGenerator.cc. Referenced by ~InterleavedYUVGenerator(). should receive FilterBankEvents from any standard format FilterBankGenerator (like RawCameraGenerator) Definition at line 30 of file InterleavedYUV 130 of file InterleavedYUVGenerator.cc. The loadBuffer() functions of the included subclasses aren't tested, so don't assume they'll work without a little debugging... Definition at line 42 of file InterleavedYUVGenerator.cc. . marks all of the cached images as invalid (but doesn't free their memory) You probably want to call this right before you send the FilterBankEvent Definition at line 138 of file InterleavedYUVGenerator.cc. NULL Definition at line 50 of file InterleavedYUVGenerator.cc. Definition at line 75 of file InterleavedYUVGenerator.cc. resets stride parameter (to correspond to width*3 from FilterBankGenerator::setDimensions()) Definition at line 100 of file InterleavedYUVGenerator.cc. 116 of file InterleavedYUVGenerator.cc. Referenced by InterleavedYUVGenerator(). so you can refer to the YUV channel symbolically. (as opposed to others that might be added?) Definition at line 36 of file InterleavedYUVGenerator.h. Referenced by CameraBehavior::doEvent(). [protected](). the channel of the source's U channel Definition at line 60 of file InterleavedYUVGenerator.h. Referenced by calcImage(). the channel of the source's V channel Definition at line 61 of file InterleavedYUVGenerator.h. the channel of the source's Y channel Definition at line 59 of file InterleavedYUVGenerator.h. Referenced by calcImage(), and createImageCache().
http://tekkotsu.org/dox/classInterleavedYUVGenerator.html
CC-MAIN-2018-34
en
refinedweb
unable to evaluate symlinks in Dockerfile When I input docker build -t tutum/apache-php . in docker, it will output the error unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx C:\User\gao\Dockerfile: The system cannot find the file specified. What does this mean? Any advice is helpful. Thank you. One Solution collect form web for “unable to evaluate symlinks in Dockerfile” It means your Dockerfile is missing or incorrectly named. If you want to build a differently named Dockerfile, you can run docker build -t tutum/apache-php -f ./Dockerfile.dev . You also appear to be trying to build in a namespace that is in use (tutum) which is strongly recommended against. If you want their image, just run a docker pull tutum/apache-php.
http://dockerdaily.com/unable-to-evaluate-symlinks-in-dockerfile/
CC-MAIN-2018-34
en
refinedweb
Plotting only specific points using matplotlib's imshow import numpy as np import matplotlib.pyplot as plt N = 101 x = np.linspace(-1,1,N); ones = np.ones_like(x) coords = np.outer(ones,x) #x coords coords = np.concatenate([[coords], [coords.T]]) ourShape = np.zeros([N,N]) ourShape[np.square(coords[0,:,:]) + np.square(coords[1,:,:]) <= 1.] = 1. fig, ax = plt.subplots(); ax.imshow(ourShape) plt.show() This plots a circle inscribed in a square. But how do I get python to plot only the blue region, which is part of the square and not the circle? To be clear, I do not want to just turn the circle white; I want it to not plot at all. I tried ax.imshow(ourShape[ourShape < 1.]) and that produces a TypeError. - Matplotlib linked graphical analysis with scatter and bar plot I am doing financial data analysis and I have the following json data data = { 'result 1': { 'Function values': [-0.006227277397795026, 0.06383399272822152], 'Optimized weights': [('bonds', 1.4711817429946462e-15), ('forex', 5.550786381057787e-17), ('bitcoin', 0.9999999999999982), ('gold', 1.3183117655012245e-16), ('nyse', 9.697481555102928e-21), ('restate', 1.9775692500329443e-16)]}, 'result 2': { 'Function values': [-0.005261601871866209, 0.0458160221997947] 'Optimized weights': [('bonds', 0.3615398862486454), ('forex', 4.466610459077055e-25), ('bitcoin', 0.612702265453708), ('gold', 2.427629820084969e-25), ('nyse', 6.605705692605664e-25), ('restate', 0.02575784829764666)]}, 'result 3': { 'Function values': [-0.006227277397795026, 0.06383399272822152] 'Optimized weights': [('bonds', 1.4712010644711342e-15), ('forex', 5.55073975746577e-17), ('bitcoin', 0.9999999999999982), ('gold', 1.3183006923981202e-16), ('nyse', 1.1072819449579044e-20), ('restate', 1.977567049973079e-16)]}, 'result 4': { 'Function values': [-0.0026994057255751948, 0.022810143209823008] 'Optimized weights': [('bonds', 0.1799574677817418), ('forex', 4.974066668895019e-25), ('bitcoin', 0.3047792953486622), ('gold', 0.0), ('nyse', 0.0), ('restate', 0.5152632368695961)]} } The objective is to make the following kind of graph in which Function valuesare plot on the scatter plot with the point marked with specific color and the same color will be used in the below bar chart to represent its Optimized weightsvalues. I know how to plot simple scatter plots and bar plots using matplotlib import matplotlib.pyplot as plt import numpy as np # Separate Scatter plot plt.scatter(data['result 1']['Function values'], color='red') plt.scatter(data['result 2']['Function values'], color='blue') plt.scatter(data['result 3']['Function values'], color='orange') plt.scatter(data['result 4']['Function values'], color='green') plt.show() # Separate Bar plot for 1 results and similarly barplots for all asset_1 = data['result 1']['Optimized weights'] asset_1 = np.array(asset_1) n_assets = np.arange(6) plt.bar(asset_1[1], color='red') plt.xticks(n_assets, asset_1[0]) plt.show() But here they are separated. Is there any to combine them like the figure I made above? Thanks - Seaborn Lineplot Module Object Has No Attribute 'Lineplot' Using seaborn's documentation code to generate a lineplot returns an AttributeError: 'module' object has no attribute 'lineplot'. I have updated seaborn and reimported the module and tried again, no luck. Did lineplot get retired, or is there something else going on? import seaborn as sns; sns.set() import matplotlib.pyplot as plt fmri = sns.load_dataset("fmri") ax = sns.lineplot(x="timepoint", y="signal", data=fmri) - Matplotlib tick label precision When defining tick labels I get an abnormally high level of precision. For example: import pylab as pl fig = pl.figure(figsize=(3.25, 2.5)) ax0 = fig.add_subplot(111) ax0.set_ylim([0, 0.5]) ax0.set_yticks(np.arange(0, 0.51, 0.1), minor=False) ax0.set_yticklabels(np.arange(0, 0.51, 0.1), fontsize=8) ax0.set_xlim([0, 0.5]) ax0.set_xticks(np.arange(0, 0.51, 0.1), minor=False) ax0.set_xticklabels(np.arange(0, 0.51, 0.1), fontsize=8) fig.show() The output figure is below with the bad tick labels on the 0.3 marker (both x and y axes). I have tried using np.linspace, which yields the same problem. I understand the issues with floating point precision, but I would expect the label to be rounded off a lot sooner. How do I correct this to only show the first decimal? - ggplot using position dodge push bars to the left when some count is zero When zero count cases are present, geom_bar()with position_dodge(preserve = 'single')and a 'fill' aesthetic leaves an empty space. If the missing bar is not the last, all remaining bars get pushed to the left. The fenomenon is visible in the following picture with a two-cases variable for the fill aesthetic. Sometimes red bars seem one next to the other because some blue bars are missing. I would like to keep the order even with missing cases, that is blue bars on the left and red ones on the right. - Visualizing changes in number of followers according to user ID (values of column) I have been working with R only for a short time. I have a dataframe called "users" where column 2 "userid" consists of 27 user IDs (character) which are repeated several times as new information is added several times a day. Column 5 "total_followers" shows the number of followers of the users (numeric/integer) My question is: How can I visualize the development/trend of the number of followers of each user according to user ID? I would like to create a line for each user showing the development. (either one plot for all or one for each user. Thank you! - Analyse CAN signals in CANoe tests When running tests via the CANoe test environment, I can check the instantaneous value of a signal using e.g. checkSignalInRange(). For some signals it would make more sense to evaluate typical physical attributes like amplitude, frequency, period and mean value. Is there a way to do it in CANoe? As an acceptable workaround, is it possible to set up some signals to be recorded during a test, and include the signal plot into the test report?
http://quabr.com/48758000/plotting-only-specific-points-using-matplotlibs-imshow
CC-MAIN-2018-34
en
refinedweb
Quick settings is undoubtedly one of the most popular feature in Android devices. It provides a convenient way to quickly change the device settings or key actions directly from the notification panel. Like required or frequently used, and should not be used as shortcuts to launching an app. Android Quick Settings Tiles can only have icons of a single colour. It can be tinted to either white or grey. You can handle click, double click action on the tiles but the long press is restricted only to few system apps. Android Quick Settings API Example In this tutorial we will see how to use the Quick Settings Tile API in Android N to register a custom tile action. The sample application will add a custom action to quick settings and when clicked it will launch an activity. You need the following perquisites to run this code sample. - Android Studio version 2.0+ - A test device or emulator configuration with Android version 6.0+ Adding a tile to quick settings involves two steps. First you need to declareQuick Settings Tile in AndroidManifest.xml file. Add the following code snippets inside <application> element. <service android: <intent-filter> <action android: </intent-filter> </service> Let us now extend the TileService class to respond the Tile events and handle click action to launch an activity when user clicking on the Quick Settings Tile. You can optionally override the following methods to perform different actions when the Tile state changes. MyAppTileService.java public class MyAppTileService extends TileService { @Override public void onDestroy() { super.onDestroy(); } @Override public void onTileAdded() { super.onTileAdded(); } @Override public void onTileRemoved() { super.onTileRemoved(); } @Override public void onStartListening() { super.onStartListening(); } @Override public void onStopListening() { super.onStopListening(); } @Override public void onClick() { super.onClick(); //Start main activity startActivity(new Intent(this, MainActivity.class)); } } Insightful example for bignners. However it is missing the other important aspects of the tile API such as listining to tile state, update tile dynamically. Adding that to this tut will make it precious Thanks Pankaj
https://www.stacktips.com/tutorials/android/quick-settings-tile-api-example-in-android-n
CC-MAIN-2018-34
en
refinedweb
This Recommendations when using Query Bands with the .Net Data Provider for Teradata Query Band Overview A brief overview of the purpose of Query Bands. Connection Level Discussion of Connection Level Query Bands. Transaction Level Discussion of Transaction Level Query Bands. Trusted Sessions Discussion of Trusted Session and how it is set up using Query Bands. Connection Pooling and Query Bands How Query Bands affect the provider's management of connection pools. Query Band support has been added to the .Net Data Provider For Teradata beginning with TDNETDP 13.01.00.00. There are several reasons to use of Query Bands. A few of these reason are: There are several articles that have been posted that discuss the benefits and use of Query Bands. If an application needed to use Query Bands prior to the 13.01 release, the SET QUERY_BAND statement had to be executed. It was also the application's responsibility to manage the Query Bands. Now, the provider is able to manage Query Bands on behalf of an application. There is a new class, TdQueryBand, that is used to manage Query Bands. Applications also have the capability of defining Query Bands on the connection string using the QueryBand connection string attribute. Query Bands can be defined at either the connection or transaction levels. This is how Query Bands are defined in a connection string: User Id=tuser;Password=tpass;Data Source=td1;QueryBand='Action=update;ProxyUser=puser;ProxyRole=prole;'; There is a set of reserved Query Band keys that are used by debugging, logging, workload management, and other tools to monitor the use of the Teradata Database. These reserved keys are implemented as properties in the TdQueryBand class. The name of a few of these keys/properties are: Action, ApplicationName, ProxyUser, ProxyRole. To view the full list of Query Band keys refer to the Teradata Manual: SQL Data Definition Language. The value for any of the properties/keys can be set several different ways: TdQueryBand qb = new TdQueryBand(); qb.Action = "update"; qb["ProxyUser"] = "terauser"; qb.Add("Deadline", DateTimeOffset.Now); Application specific Query Bands can be defined by using either the indexer or the Add method of the TdQueryBand class. qb.Add("CustomQB1", "custom1"); qb["CustomQB2"] = "custom2"; TdQueryBand also supports the removal of a Query Band. qb.Action = String.Empty; qb["ProxyUser"] = String.Empty; qb.Remove("Deadline"); Query Bands are defined at the Connection level by either defining them using the Query Band connection string attribute or by using the TdConnection.ChangeQueryBand() method. To retrieve the Query Bands that have been defined at the connection level, the property TdConnection.QueryBand is called. This method will retrieve all the Query Bands associated with the connection, and return the definitions in a TdQueryBand instance. After changes have been made to the Query Bands, the method TdConnection.ChangeQueryBand() must be called so that the changes can be applied to the Teradata Database. When this method is called, the provider will perform the following: IMPORTANT: Because all defined Query Bands are first removed it is important to retrieve them using the property TdConnection.QueryBand when Query Bands are to be added, deleted, or modified. Any changes that are to be made to Query Bands should be made to the TdQueryBand instance returned from this property. Query Bands that have been defined at the Connection level exist until the connection has been closed (TdConnection.Close), or have been removed (TdQueryBand.Clear) from the connection. This is an example of adding and removing Query Bands: static void QueryBandExample1() { TdConnectionStringBuilder sb = new TdConnectionStringBuilder(); sb.UserId = "terauser"; sb.Password = "terapass"; sb.DataSource = "tera1"; sb.QueryBand = new TdQueryBand("Action=Update;ProxyUser=proxy1;ProxyRole=role1;"); TdConnection conn = new TdConnection(sb.ConnectionString); conn.Open(); //Retrieving Query Bands that have been defined. TdQueryBand qb = conn.QueryBand; //Modifying the current Query Bands qb.Action = "delete"; //Modifying a Query Band qb["customQb1"] = "custom1"; //Query Band will be added qb.ProxyUser = String.Empty; //ProxyUser will be removed qb.Remove("ProxyRole"); // ProxyRole will be removed //Applying changes to Teradata Database conn.ChangeQueryBand(qb); conn.Close(); } Transaction level Query Band are defined when either the TdConnection.BeginTransaction() method is called and a TdQueryBand instance is passed in as a parameter, or when the TdTransaction.ChangeQueryBand() method is called. Modifying Query Bands at the Transaction level follow the same pattern as in the Connection Level. For example, to retrieve the Query Bands that have been defined in the transaction the property TdTransaction.QueryBand is called. All the modifications to the existing Query Bands should be performed on the TdQueryBand instance returned from this property. Once all the changes have been made, TdTransaction.ChangeQueryBand() is called to apply the changes to the transaction. TdTransaction.ChangeQueryBand() performs same tasks as TdConnection.ChangeQueryBand(). When TdTransaction.ChangeQueryBand() is called all Query Bands at the Transaction level are removed, and the Query Bands defined in the TdQueryBand instance passed in as a parameter are applied. IMPORTANT: If Query Bands exist in the transaction, it is important that TdTransaction.QueryBand is first called, and that any changes are performed on the TdQueryBand instance returned by this property. Query Bands defined at the Connection level are inherited by the Transaction. If a Query Band has been defined at both the Transaction and Connection levels, the one at the Transaction level has precedence. Query Bands that are defined at the Transaction level only exist while the transaction is open. Query Bands can be defined when opening a transaction (TdConnection.BeginTransaction()) or during an opened transaction (TdTransaction.ChangeQueryBand()). This is an example of retrieving Query Bands, then modifying and applying the changes to the Transaction: static void QueryBandExample2() { TdConnection conn = new TdConnection( "User Id=tuser;Password=tpass;Data Source=tera1;QueryBand=Action=Update;ProxyUser=proxy1;ProxyRole=role1;"); conn.Open(); TdQueryBand tranQb = new TdQueryBand("AppCustom1=custom1;Action=delete;"); TdTransaction trans = conn.BeginTransaction(tranQb); TdQueryBand definedQb = trans.QueryBand; //The same Query Bands are defined in definedQb as in tranQb //Modifying Query Bands definedQb["AppCustom2"] = "custom2"; //Adding app. Specific Query Band definedQb.Group= "gp1"; //Defining value for a reserved Query Band key //Applying changes made to Query Bands TdTransaction.ChangeQueryBand(definedQb); trans.Commit(); conn.Close(); } A Trusted session is only supported by Teradata Database 13.0 or greater. What is a Trusted Session? A Trusted Session is implemented using Query Bands. A Trusted Session enables a user of an application to access a Teradata Database by proxy through an established connection. An application will still need to log into the Teradata Database using a trusted user. However, each user of an application can be assigned an identifier used as a proxy. This proxy user is granted CONNECT THROUGH privileges to the trusted user. The proxy user is also assigned to roles which define a set of privileges. This is a brief explanation. For more information refer to the Teradata Manual SQL Data Definition Language: Detailed Topics. Many application developers will probably find the Trusted Session capability the most important feature that is provided by Query Bands. To specify a proxy user the ProxyUser reserved Query Band key is used. The roles assigned to a proxy user is specified using the ProxyRole key. TdQueryBand has properties for both these keys called ProxyUser and ProxyRole. The following demonstrates how to set up a trusted session: static TdConnection TrustedSessionExample(String proxyUser, String proxyRole) { TdQueryBand qb = new TdQueryBand(); qb.ProxyUser = proxyUser; qb.ProxyRole = proxyRole; TdConnectionStringBuilder builder = new TdConnectionStringBuilder(); builder.QueryBand = qb; builder.DataSource = "tdat1"; builder.UserId = "tdatuser"; builder.Password = "tdatpass"; TdConnection conn = new TdConnection(builder.ConnectionString); conn.Open(); return (conn); } The Teradata Provider enables Connection Pooling by default. The provider can manage several Connection Pools, and each pool is identified by the Connection String. For example a different connection pool will be accessed by the provider when TdConnection.Open is called for each of the four different connection strings : Data Source=tdat1; User Id=tuser; Password=tpass; Connection Pooling=true; Data Source=tdat1; User Id=tuser; Password=tpass; Connection Pooling=true; User Id=tuser; Data Source=tdat1; Password=tpass; Connection Pooling=true Password=tpass; User Id=tuser; Connection Pooling=true;Data Source=tdat1; The provider will create a new pool in the case where the Connection String has not been associated with a connection pool. When an application is using Query Bands, the Query Band values specified in the Connection String may need to be changed each time TdConnection.Open() is called. This is especially true when Trusted Sessions are being used. It would be a waste of resources if the provider were to create a new connection pool each time the Query Band values were changed by an application. To prevent a new connection pool from being created, the Query Band connection string attribute is ignored when the provider associates a Connection String to a pool. For example, the following connection strings are associated to the same pool: Data Source=tdat1; User Id=tuser; Password=tpass; Query Band='ProxyUser=joe;ProxyRole=admin;'; Data Source=tdat1; User Id=tuser; Password=tpass; Query Band='ProxyUser=sam;ProxyRole=client;'; Data Source=tdat1; User Id=tuser; Password=tpass; Query Band='ProxyRole=client;ProxyUser=sue;Action=upd;'; Data Source=tdat1; User Id=tuser; Query Band='ProxyRole=john;ProxyUser=client;Action=update;' ; Password=tpass;
http://community.teradata.com/t5/Blog/Query-Bands-in-the-Net-Data-Provider-for-Teradata-13-01-00-00/ba-p/65988
CC-MAIN-2018-34
en
refinedweb
Red Hat Bugzilla – Bug 25731 strcpy breaks with -O2 -fno-inline Last modified: 2016-11-24 09:53:58 EST $ cat foo.c #include <string.h> int main(void) { char foo[4]; strcpy(foo, "foo"); return 0; } $ gcc -O2 -fno-inline foo.c /tmp/ccLwrlUH.o: In function `main': /tmp/ccLwrlUH.o(.text+0x5c): undefined reference to `__strcpy_small' collect2: ld returned 1 exit status $ rpm -q glibc gcc glibc-2.2.1-3 gcc-2.96-71 Pass -O2 -fno-inline -D__NO_STRING_INLINES then. Really, there is nothing glibc can do about this (apart from exporting all those inlines as static functions but that makes no sense) and gcc does not pass any macros which would tell whether -finline or -fno-inline was passed, so it has to use __OPTIMIZE__ (and has done that for ages).
https://bugzilla.redhat.com/show_bug.cgi?id=25731
CC-MAIN-2018-34
en
refinedweb
Updates Archives Monthly updates for September 2019 Azure Sphere Preview—Update 19.09 is now available for evaluation The Azure Sphere Preview 19.09 feature release is now available via the retail evaluation feed. The retail evaluation is meant for backwards compatibility testing. Use the retail evaluation feed to verify production-signed applications against the new release before we deploy it broadly on the retail feed... Azure HPC Cache is now in preview Azure HPC Cache, a high-performance file cache with an aggregated namespace that reduces latency between storage and Azure compute for heavy read workloads, is now in preview. Azure Private Link is now available in preview Target availability: Q3 2019 Connect to services in your Azure virtual networks more securely and privately with Azure Private Link, now available in preview. Azure Backup support for large disks up to 30 TB is now in public preview Announcing the public preview support for larger and more powerful Azure Managed Disks of up to 30 TB size. Blueprints—NIST. Updates by date Tell us what you think of Azure and what you want to see in the future.Provide feedback Azure is available in more regions than any other cloud provider.Check product availability in your region
https://azure.microsoft.com/en-us/updates/2019/09/?status=inpreview
CC-MAIN-2020-34
en
refinedweb
A library for situated automated negotiations Project description A python library for managing autonomous negotiation agents in simulation environments. The name negmas stands for either NEGotiation MultiAgent System or NEGotiations Managed by Agent Simulations (your pick). Introduction This package was designed to help advance the state-of-art in negotiation research by providing an easy-to-use yet powerful platform for autonomous negotiation. It grew out of the NEC-AIST collaborative laboratory project. The main purpose of this package is to provide the public interface to be used in the implementation of the negotiation platform. Because of that, no attempts were made to optimize the internal implementation of sample negotiators. Moreover, the package is trying to follow best-practice in Python library design but that does not constraint implementations if carried out in different languages from utilizing these languages’ best practices as well even by modifying the provided interface. Main Features This platform was designed with both flexability and scalability in mind. The key features of the negmas package are: - The public API is decoupled from internal details allowing for scalable implementations of the same interaction protocols. Supports both bilateral and multilateral negotiations. Supports negotiators engaging in multiple concurrent negotiations. Provides support for inter-negotiation synchronization. - The package provides multiple levels of abstraction in the specifications of the computaitonal blocks required for negotiation allowing for gradual exposition to the subject. - There is always a single base class for every type of entity in the negotiation (e.g. Negotiator. Protocol, etc). Different options are implemented via Mixins increasing the flexibility of the system. The package provides sample negotiators that can be used as templates for more complex negotiators. The package allows for both mediated and unmediated negotiations. Novel negotiation protocols can be added to the package as easily as adding novel negotiators. Allows for non-traditional negotiation scenarios including dynamic entry/exit from the negotiation. Has built-in support for experimenting with elicitation protocols for both single and multi-issue auctions. What else is provided? - Name Resolution The package supports name resolution for finding partners using the YellowPages class. - Taking Initiative Any Negotiator (including Negotiator s) can create Protocol s and invite other Negotiator s to it. The Moderator negotiator need not be around. - Elicitation Utility elicitation is supported through the elicitors module and sample elicitors are available in the sample.elicitors module. Basic Use cases negotiators and negotiation protocols. This section gives some examples of both kinds of usages. Please refer to the full documentation for more concrete examples. Running existing negotiators/negotiation protocols Using the package for negotiation can be as simple as the following code snippet: from negmas import SAOMechanism, AspirationNegotiator, MappingUtilityFunction neg = SAOMechanism(outcomes=10) agents = [AspirationNegotiator() for _ in range(5)] for agent in agents: neg.add(agent, ufun = MappingUtilityFunction(lambda x: rand() * x[0])) neg.run() Developing a negotiator Developing a novel negotiator slightly more difficult by is still doable in few lines of code: from negmas.negotiators import Negotiator class MyAwsomeNegotiator(Negotiator, MultiNegotiationsMixin): def __init__(self): # initialize the parents Negotiator.__init__(self) MultiNegotiationsMixin.__init__(self) def respond(self, offer, negotiation = None): # decide what to do when receiving an offer @ that negotiation pass def propose(self, n=1, negotiation=None): # proposed the required number of proposals (or less) @ that negotiation pass By just implementing respond() and propose(). This negotiator is now capable of engaging in multiple concurrent negotiations. It can access all the negotiations it is involved in using self.negotiations and can enter and leave negotiations (if allowed by the protocol) using enter() and leave(). See the documentation of Negotiator for a full description of available functionality out of the box. Developing a negotiation protocol Developing a novel negotiation protocol is actually even simpler: from negmas.mechanisms import Mechanism class MyNovelProtocol(Mechanism): def __init__(self, n_steps, n_outcomes): super().__init__(n_steps=n_steps, n_outcomes=n_outcomes) def step(self): # one step of the protocol pass By implementing the single step() function, a new protocol is created. New negotiators can be added to the negotiation using add() and removed using remove(). See the documentation for a full description of Protocol available functionality out of the box. Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/negmas/0.1.2/
CC-MAIN-2020-34
en
refinedweb
Riena Getting Started with Wiring {{#eclipseproject:rt.riena}} Please read Riena Getting Started with injecting services and extensions first before you continue reading this page. A basic understanding of Riena's injection mechanism is necessary for understanding Riena's wiring mechanism. Use case: Why Wiring? In Eclipse-RCP-based applications, components often start their life cycle because they were contributed as an executable extension org.eclipse.core.runtime.IConfigurationElement.createExecutableExtension(String). Who or what is responsible for injecting the required services and/or extensions into these objects? And how to know what to inject? Moreover it is often desirable not to invoke an Inject.… sentence within the classes that need injecting. The answer to these questions is Wiring. With the following sentence it is possible to initiate the wiring, i.e. perform all the necessary injections of services and extensions. Wire.instance(object).andStart(context); Well, that looks really easy, but you may wonder how it works? This is the topic of the next section. Specifying a wiring There are two ways of specifying what needs to be done: Introducing a dedicated class responsible for the wiring, and annotating a method that requires injection. Wiring through a dedicated class This option is the most flexible but least convenient way. The class that needs to have services or extensions injected (i.e. the target class) specifies, using an annotation, another class that be responsible for the wiring: @WireWith(SSLConfigurationWiring.class) public class SSLConfiguration { public void configure(ISSLProperties properties) { ... } } The actual wiring is then performed by the class defined in the annotation, implementing the methods wire(...) and unwire(...):); } } Here we use Riena's well-known Inject.… to perform the necessary injections. Note how we explicitly specify that the update method shall be named "configure". This approach is the most flexible because within the wire(...) and unwire(...) methods you can do anything you like. When you do not need this flexibility, you can use a simpler approach, described in the following section. Wiring through annotations The same wiring can be done with: public class SSLConfiguration { @InjectExtension(id = "org.eclipse.riena.communication.core.ssl", min = 0, max = 1) public void configure(ISSLProperties properties) { ... } } You might ask: That's all? Yes, it is. Under the hood it will do exactly the same as the previous less-convenient approach. For example, there is no longer any need to specify how the update method needs to be called, because we denote this by annotating the method to be used, in this case configure(...). If the extension point ID is defined as a constant named "ID" in the extension interface: @ExtensionInterface public interface ISSLProperties { String ID = "org.eclipse.riena.communication.core.ssl"; ... } … wiring can be even more concise: public class SSLConfiguration { @InjectExtension(min = 0, max = 1) public void configure(ISSLProperties properties) { ... } } Of course, you can use corresponding annotations for injecting services through wiring as well. The shortest form is: public class CustomerSearchSubModuleController extends SubModuleController { @InjectService() public void bind(ICustomerSearch service) { ... } public void unbind(ICustomerSearch service) { ... } } This will inject the ICustomerSearch service into the annotated bind(...) method. The unbind(...) method's name is deduced from the name of the annotated bind method by prefixing it with "un". You can also specify explicitly the service class or name, the unbind method name and other properties with parameters of the annotation. Back to our use case If you define executable extensions that need to be wired, you don't need to care. Just provide your class with the approach that suits your needs best. And Riena's extension injector will automatically do the wiring. Of course you can initiate wiring everywhere you want by explicitly calling Wire.… Wrap-up Riena's wiring simplifies writing components that need services or extensions injected. Especially when those components start their life cycle through executable extensions.
https://wiki.eclipse.org/Riena_Getting_Started_with_Wiring
CC-MAIN-2020-34
en
refinedweb
WebKit+SVG does not support filterRes attribute Created attachment 43422 [details] Implementation of filterRes This is the implementation of filterRes. It scales the intermediate images used by the filter and it's effects to set the quality of a filter. It scales the values of any filter effect if needed too. According to the Spec () we can use filterRes to limit the quality to the needs of the device. I limit the size, so that the maximum size of any intermediate image is 5000x5000 pixels. A didn't tested the maximum value that is possible, but 10,000x10,000 crashed on cairo. It is also a question of slowness not to have a to big limitation. This fixes bug 26380. Other platforms can use a different limitations. A maximum size of 200x200 or 100x100 is maybe enough for mobile devices. Created attachment 43448 [details] Implementation of filterRes Sorry, _this_ patch checks for the biggest ImageBuffer that we will use and scales the filter down, so that all filters are in the maximum rect of 5000x5000. The scale factor for x and y are calculated independently. Comment on attachment 43448 [details] Implementation of filterRes Jeeezz, what a large patch, thank god I'm on a nightshift with nothing else to do ;-) Several comments: - You need a much more detailed ChangeLog, as this is a large patch, ideally per file, this time. > Index: WebCore/platform/graphics/filters/FEGaussianBlur.cpp ... > + sdx = std::max(sdx, static_cast<unsigned>(1)); > + sdy = std::max(sdy, static_cast<unsigned>(1)); Why not just std::max(sdx/y, 1); ? > Index: WebCore/platform/graphics/filters/Filter.h > =================================================================== > --- WebCore/platform/graphics/filters/Filter.h (revision 51070) > +++ WebCore/platform/graphics/filters/Filter.h (working copy) > @@ -22,6 +22,7 @@ > > #if ENABLE(FILTERS) > #include "FloatRect.h" > +#include "FloatSize.h" > #include "ImageBuffer.h" > #include "StringHash.h" > > @@ -40,15 +41,21 @@ namespace WebCore { > void setSourceImage(PassOwnPtr<ImageBuffer> sourceImage) { m_sourceImage = sourceImage; } > ImageBuffer* sourceImage() { return m_sourceImage.get(); } > > + FloatSize filterRes() const { return m_filterRes; } > + void setFilterRes(const FloatSize& filterRes) { m_filterRes = filterRes; } Hrm, I'd prefer to completly avoid abbrevations, aka. change it to "setFilterResolution" here. Filter* has no direct connection to SVG, and it's not in the "// SVG specific" section below, so why not rename it? We don't need to reuse SVG naming conventions here. >. > + if (this->hasAttribute(SVGNames::filterResAttr)) { s/this->// > + m_filter->setHasFilterRes(true); > + m_filter->setFilterResSize(FloatSize(filterResX(), filterResY())); Same thoughts as in Filter.h: s/setHasFilterRes/setHasFilterResolution/ s/setFilterResSize/setFilterResolution/ (Size prefix is superflous IMHO) > Index: WebCore/svg/graphics/SVGResourceFilter.cpp > =================================================================== > --- WebCore/svg/graphics/SVGResourceFilter.cpp (revision 51070) > +++ WebCore/svg/graphics/SVGResourceFilter.cpp (working copy) > @@ -35,6 +35,10 @@ > #include "SVGRenderTreeAsText.h" > #include "SVGFilterPrimitiveStandardAttributes.h" > > +#define MAX_FILTER_SIZE 5000.f Evil defines, please use a static constant here. I am not sure about our naming convention, it may have a g, or k prefix, please check for common usage of static constants in other files. > +bool SVGResourceFilter::matchesMaxImageSize(const FloatSize& size) { { neeeds to go on a new line > + bool matchesFilterSize = true; > + if (size.width() > MAX_FILTER_SIZE) { > + m_scaleX *= MAX_FILTER_SIZE / size.width(); > + matchesFilterSize = false; > + } > + if (size.height() > MAX_FILTER_SIZE) { > + m_scaleY *= MAX_FILTER_SIZE / size.height(); > + matchesFilterSize = false; > + } > + > + return matchesFilterSize; > +} matchesMaxImageSize is not a good name. How about "fitsInMaximumImageSize" or something similar. Matches sounds too much like "is equal". > void SVGResourceFilter::prepareFilter(GraphicsContext*& context, const RenderObject* object) ... > + // scale to big sourceImage size to MAX_FILTER_SIZE > + tempSourceRect.scale(m_scaleX, m_scaleY); > + matchesMaxImageSize(tempSourceRect.size()); Hrm, you're ignoring the return value of matchesMaxImageSize here?? > + > // prepare Filters > m_filter = SVGFilter::create(targetRect, m_filterBBox, m_effectBBoxMode); > + m_filter->setFilterRes(FloatSize(m_scaleX, m_scaleY)); > > FilterEffect* lastEffect = m_filterBuilder->lastEffect(); > - if (lastEffect) > + if (lastEffect) { > lastEffect->calculateEffectRect(m_filter.get()); > + // at least one FilterEffect has a to big image size, s/to/too/ > void SVGResourceFilter::applyFilter(GraphicsContext*& context, const RenderObject*) > { > + if (!m_scaleX || !m_scaleY || !m_filterBBox.width() || !m_filterBBox.height()) > + return; The same check is used as above, might make sense to refactor in a simple "static inline bool shouldProcessFilter()" helper function? > Index: WebCore/svg/graphics/SVGResourceFilter.h > =================================================================== > --- WebCore/svg/graphics/SVGResourceFilter.h (revision 51070) > +++ WebCore/svg/graphics/SVGResourceFilter.h (working copy) > @@ -53,6 +53,9 @@ public: > > virtual SVGResourceType resourceType() const { return FilterResourceType; } > > + void setFilterResSize(const FloatSize& filterResSize) { m_filterResSize = filterResSize; } > + void setHasFilterRes(bool filterRes) { m_filterRes = filterRes; } Same rename suggestions apply as above. > + bool matchesMaxImageSize(const FloatSize&); Ditto. > + FloatSize m_filterResSize; I'd suggest just "m_filterResolution" here. >? > Index: LayoutTests/ChangeLog > =================================================================== > --- LayoutTests/ChangeLog (revision 51126) > +++ LayoutTests/ChangeLog (working copy) > @@ -1,3 +1,25 @@ > +2009-11-18 Dirk Schulze <krit@webkit.org> > + > + Reviewed by NOBODY (OOPS!). > + > + The first two example have a filter with a size of 20000x20000. We limit > + the quality to be able to render this filter. > + On the third example the filter qulitiy is limited by different values > + to test the bahavior of effects with kernels or other values that need > + to be scaled too. It also tests the correctness of the subRegion calculation > + for filters with more than one effect. Better name the tests, instead of relying on the reviewers ability to count ;-) Just realized the patch is not that big, it's mostly the pngs, that create a frightning big patch size. Please fix these issues, and upload a new patch. I think the general concept looks sane. Wouldn't hurt if Simon Fraser / Eric Seidel / Oliver Hunt may have another look. I'll cc them soon. r- because of the mentioned issues above. (In reply to comment #3) > (From update of attachment 43448 [details]) > Jeeezz, what a large patch, thank god I'm on a nightshift with nothing else to > do ;-) I'll split out the LayoutTests into another patch, to shrink the patch to ~38k > > Index: WebCore/platform/graphics/filters/FEGaussianBlur.cpp > ... > > + sdx = std::max(sdx, static_cast<unsigned>(1)); > > + sdy = std::max(sdy, static_cast<unsigned>(1)); > > Why not just std::max(sdx/y, 1); ? Do not understand what you mean? the static_cast was neccessary to get a unsigned 1. What is y in your example? > >. I took a look at other SVG*Elements, we never handle parsing errors. We just ignore the attribute, if the arguments are not parseable. > >? Yes. Simon suggested this on ImageBufferFilter. I thougt it's the best to have a common style on all childs of Filter. > Wouldn't hurt if Simon Fraser / Eric Seidel / Oliver Hunt may have another > look. I'll cc them soon. I already added all persons, that responsed to bug 26380. I'll upload a fixed patch. Created attachment 43495 [details] Implementation of filterRes Fixed patch. LayoutTests following with the next patch. Created attachment 43509 [details] Tests for filterRes The LayoutTests for filterRes. Comment on attachment 43495 [details] Implementation of filterRes Looks nice, especially the ChangeLog, so much easier to understand the patch now :-) r=me, if you change the value to be 5000, as the comments say, it's 3000 in the code at the moment, please fix before landing. Comment on attachment 43509 [details] Tests for filterRes LGTM, r=me. Comment on attachment 43509 [details] Tests for filterRes Clearing flags on attachment: 43509 Committed r51301: <> landed in r51310.
https://bugs.webkit.org/show_bug.cgi?id=6021
CC-MAIN-2020-34
en
refinedweb
== == The answer to your question depends upon the law in your state. If an individual files for bankruptcy most assets of the individual may be sold or otherwise disposed of in a Chapter 7 bankruptcy in to partially satisfy the debts of the individual. While an interest in an LLC is an asset of the individual, many states have statutes within their LLC Act which provide that an LLC interest may not be taken outright by a creditor, but rather a charging order will be issued. Typically this means that the individual who is the holder of the LLC interest will continue to be a member of the LLC and will continue to vote the LLC interest; however, any distributions which are made by the LLC to the individual would be paid to the creditor or creditors rather than to the individual due to the charging order. If YOU file than yes...and your interest/ownership of the stock in the LLC is an asset that may be used to pay your personal debts/liabilities. If the LLC files, than your personal assets aren't involved...of course your investment in the LLc will likely become worthless....and there will be an e review to make sure that self serving transactions weren't done. Finally, normally, until a business (the LLC) is well established, any loans/leases, etc someone makes to it tey require you to sign for personally too....so you would be personally liable for them anyway. LLC is Limited Liability Company. It's allowed by state statute. But the IRS doesn't recognize LLC as a classification for federal tax purposes. Under IRS Default Rules, a Limited Liability Company with at least two members is considered as a partnership. Form 8832 is Entity Classification Election. An LLC with two or more members would only have to file Form 8832 if the LLC didn't want to file as a partnership. As a partnership, the LLC would file Form 1065 (U.S. Return of Partnership Income). For more information, go to for Publication 541 (Partnerships) and Publication 3402 (Tax Issues for Limited Liability Companies). It depends. Unless the owners of the LLC elect to have it treated as a corporation, then an LLC which has at least two members is treated as a partnership and files a partnership tax return, Form 1065. If there is only one member of the LLC, then the IRS disregards the LLC as a separate tax reporting entity entirely. If the single member is an individual, then the member reports the LLC's income and deductions on the individual's person 1040, usually on Schedule C (for a business) or Schedule E (for real estate). If the single member of the LLC is a corporation, partnership or trust, it likewise files the information on its entity tax return (1120, 1120 S, 1065, 1041, etc...) If the members of the LLC file an election, the LLC may be treated as a corporation or an S corp. In that case, the LLC would file an appropriate return (Form 1120 or 1120 S). LLC (Limited Liability Company) is a type of business that's allowed by state statute. But LLC isn't recognized as a classification for federal tax purposes. This means that an LLC must file a tax return as a corporation, partnership, or sole proprietorship. An LLC with at least two members can choose to be classified as a corporation or as a partnership. If you choose corporation status, you must file Form 8832 (Entity Classification Election). You don't need to file Form 8832 if you're an LLC filing as a partnership. Corporations file Form 1120 (U.S. Corporation Income Tax Return). Partnerships file Form 1065 (U.S. Return of Partnership Income). Each partner's share of income, expenses, etc., is then entered on Schedule C (Profit or Loss from Businss). For more information, go to the IRS Small Business screen at. Select from the left column A-Z Index for Business to view/print the article, Limited Liability Company (LL.
https://www.answers.com/Q/If_you_have_an_LLC_and_file_chapter_7_can_they_take_your_part_of_the_LLC
CC-MAIN-2020-34
en
refinedweb
Associates the given data with the specified beacon. Attachment data must contain two parts: - A namespaced type. - The actual attachment data itself. namespacesendpoint, while the type can be a string of any characters except for the forward slash ( /) up to 100 characters in length. Attachment data can be up to 1024 bytes long. Authenticate using an OAuth access token from a signed-in user with Is owner or Can edit permissions in the Google Developers Console project. HTTP request POST{beaconName=beacons/*}/attachments The URL uses Google API HTTP annotation syntax. Path parameters Query parameters Request body The request body contains an instance of BeaconAttachment. Response body If successful, the response body contains a newly created instance of BeaconAttachment. Authorization Requires the following OAuth scope: For more information, see the Auth Guide.
https://developers.google.cn/beacons/proximity/reference/rest/v1beta1/beacons.attachments/create
CC-MAIN-2020-34
en
refinedweb
Sessions are used to retain the state in your app. A session is represented by an instance of a Session class. Together with an instance of a Json object it can be used to enable client-server communication and synchronization using JSON patch. A new session is created by calling the constructor on Session class. To set the new session as active session, it's necessary to assign it to the static property Session.Current. When multiple apps are running, only one of them needs to create the Session object and set is as active, because the session identifies the browser tab, not only your app in that tab. Therefore, you always need to check before creating a new session if Session.Current is null. Each browser tab is a separate state of the UI. Therefore, each tab is tied to its own session. This makes it totally different from the session concept in frameworks like ASP.NET or Zend, where a session stores data from all the browser tabs. Starting with Starcounter 2.3.1.6839 there is a static method, Session.Ensure(), that can be used as simplification of the pattern described above that does this check and makes sure that a session with options enabled for patch-versioning and namespaces is set (if not already set) as current and returned. This method can be used everywhere where a session should be created if Session.Current is null. DateTime createdDate = Session.Ensure().Created; // Session.Ensure() will never be null. Once you have the session, you have the possibility to attach state to it. In Starcounter, the state is represented by a Jsoninstance (also called a view-model). The session contains a storage where any number of Json instances can be kept, using a string as key. This storage is separated per app, so each running app has it own section and can only access it's own state. From Starcounter 2.3.1.6839, Session.Data have been obsoleted and replaced with Session.Store. Also Json.Session is obsoleted. Session should be obtained by using Session.Current or Session.Ensure(). Json state1 = new Json();Json state2 = new Json();Session session = Session.Ensure();session.Store["state1"] = state1;session.Store["state2"] = state2;...state1 = session.Store["state1"] The storage on the session is server-side only. Nothing stored using Session.Store will be exposed to a client. This is a change in behavior of using the old obsoleted Session.Data. See the next section on how to attach a Json to be used for client-server communication One additional feature when using Session, besides keeping state on the server, is that it can enable client-server synchronization using JSON Patch. In short it allows the client and server to send deltas instead of the full viewmodel. When this is used, the client can send http requests using the PATCH verb (HTTP PATCH method) or use websocket to send and receive patches. To enable this, the session needs to know which Json instance should be considered the root viewmodel. If the PartialToStandalone middleware is used, the root viewmodel will be automatically assigned to the session based on the Jsoninstance returned from a handler. There is also a way to manually specify which Json instance to use as root, session.SetClientRoot(json). This functionality is included as an extension method instead of directly in the session class. The extension-method can be found in the Starcounter.XSON.Advanced namespace. From Starcounter 2.3.1.6839 the handling of determining root viewmodel on session have changed. Session.PublicViewmodel and Session.Data have been obsoleted and should no longer be used to set client root. Instead use the information in the section above. The whole root viewmodel can be obtained on the client using HTTP GET verb with a url that is sent in the Location header for the response of the request that created the session. The location contains a specific identifier for the session and viewmodel that is calculated for each session to be non-deterministic. The Session object exposes a few useful properties, including: Inactive sessions (that do not receive or send anything) are automatically timed out and destroyed. Default sessions timeout (with 1 minute resolution) is set in database config: DefaultSessionTimeoutMinutes. Default timeout is 20 minutes. Each session can be assigned an individual timeout, in minutes, by setting TimeoutMinutes property. User can specify an event that should be called whenever session is destroyed. Session destruction can occur, for example, when inactive session is timed out, or when session Destroy method is called explicitly. User specified destroy events can be added using Session.AddDestroyDelegate on a specific session. Session can be checked for being active by using IsAlive method. Session is created on current Starcounter scheduler and should be operated only on that scheduler. That's why one should never store session objects statically (same as one shouldn't store SQL enumerators statically) or use session objects in multithreaded/asynchronous programming. In order to save session and utilize it later please use Session.SessionIddescribed below. One can store sessions by obtaining session ID string ( Session.SessionId). Session strings can be grouped using desired principles, for example when one wants to broadcasts different messages on different session groups. When the session represented by the string should be used, one should call Session.RunTask(String sessionId, Session.SessionTask task). This procedure takes care of executing action that uses session on the scheduler where the session was originally created. This procedure underneath uses Scheduling.RunTask thereby it can be executed from arbitrary .NET thread. There is a variation of Session.RunTask that takes care of sessions grouped by some principle: Session.RunTask(IEnumerable<String> sessionIds, Session.SessionTask task). Use it if you want to operate on a group of sessions, like in the following chat app example: [Database]public class SavedSession{public string SessionId { get; set; }public string GroupName { get; set; }}Session.RunTask(Db.SQL<SavedSession>("SELECT s FROM GroupedSession s WHERE s.GroupName = ?", myGroupName).Select(x => x.SessionId).ToList(), (Session session, string sessionId) =>{var master = session.Data as MasterPage;if (master != null && master.CurrentPage is ChatGroupPage){ChatGroupPage page = (ChatGroupPage)master.CurrentPage;if (page.Data.Equals(this.Data)){if (page.ChatMessagePages.Count >= maxMsgs){page.ChatMessagePages.RemoveAt(0);}page.ChatMessagePages.Add(Self.GET<Json>("/chatter/partials/chatmessages/" + ChatMessageKey));session.CalculatePatchAndPushOnWebSocket();}}}); To schedule tasks on all active sessions, then Session.RunTaskForAll should be used (note that it runs on all active sessions and if you only need to update few - use Session.RunTask). Current session is determined and set automatically before user handler is called. Starcounter Gateway uses one of the following ways to determine the session that should be used for calling user handler. Location + X-Referer or Referer headers: Using HTTP protocol, when creating a new session, the response will contain the Location HTTP header with the value of a newly created session. Client code later can extract this session value from the received Location header and use the session in subsequent requests, using either of the specified ways. Often X-Referer or Referer request headers are used to specify the session value. Session as handler URI parameter: Session value can be specified as one of URI parameters when defining a handler, for example: Handle.GET("/usesession/{?}", (Session session, Request request) =>{// Implementation}); Session Cookie: Use of automatic session cookie and the property UseSessionCookie have been obsoleted. Instead enable adding a header on outgoing response by setting property UseSessionHeader to true and optionally specify name of header with SessionHeaderName (default X-Location). The priorities for session determination, for incoming requests, are the following (latter has higher priority than previous): session on socket, Referer header, X-Referer header, session URI parameter. The Session constructor has an overload that takes the enum SessionOptions. This enum has five options: JSON patches are calculated whenever there's an incoming request that asks for JSON patch. This means asynchronous changes to the view-model that are finished after the response is sent will not be included in the response patch. For example, if a user clicks a button to send an order, the user expects to see a confirmation message when the order has been sent. Since the operation is scheduled on a separate thread that executes asynchronously to avoid blocking, the task to send the order will finish after Starcounter has sent the response. This means that the user will not see the status message until they send another patch that triggers a response that includes the status message. void Handle(Input.SendOrderTrigger _){Session.RunTask(Session.Current.SessionId, (session, id) =>{SendOrder(Order);Order.StatusMessage = "Done";}); // The user will not see the status message until they send another patch} To fix this, use CalculatePatchAndPushOnWebSocket. That lets the user see the status message immediately after the order has been sent. void Handle(Input.SendOrderTrigger _){Session.RunTask(Session.Current.SessionId, (session, id) =>{SendOrder(Order);Order.StatusMessage = "Done";session.CalculatePatchAndPushOnWebSocket();});} When calling CalculatePatchAndPushOnWebSocket, Starcounter traverses the JSON tree and calculates the difference between the current and previous tree. It then sends patches to the client with the changes.
https://docs.starcounter.io/v/2.3.2/guides/blendable-web-apps/sessions
CC-MAIN-2020-34
en
refinedweb
Introduction Very often we face situations when an Expert Advisor successfully operates with one brokerage company and is not profitable or even lossmaking on the other one. The reasons may be different. Different brokerage companies have different settings: - Quotes. They slightly differ because of two factors - different data feeds and different filtration that smooths quotes. For some Expert Advisors this may be relevant. Situations may occur when an EA trades often with one brokerage company and rarely on another one. - Slippage. It may differ much in different brokerage companies. This also may lead to worse characteristics of an EA because of lower expected profit. - Requotes. In some brokerage companies they are oftener than in others. In this case an EA will miss successful entering points because of large number of requotes. Statistic Of course we can start several terminals from different brokerage companies, use them a month or two and then choose one, with which the profit is maximal. But such testing is low-informative. It would be better to get more information: mean slippage per a trade, number of requotes that take place at opening of each certain trade, opening time and so on. In order not to have to analyze logs, a project Statistic was developed. It is based on the following set of rules: - An EA analyzes the market, makes transactions, gets all necessary data about the trade and passes it into a common module. - This module contains all information about the current and closed deals. It also counts the statistic about all technical characteristics of the brokerage companies. - It should be maximally comfortable for operation with large amounts of data, so that we could see only necessary information, and not all that can be collected and counted. Analyzing the statistic (number of requotes, time of a trade execution, slippage) and viewing all trades we can conclude, with what brokerage company it is better to work. If statistic on all companies is negative, we should change some EA parameters, for example, time in the market, frequency of trades. And change them until the EA starts working with a profit. If on a certain stage an EA stops bringing profit with one brokerage company being profitable on others, we stop testing this company. Theory We can organize submission of data from an EA into an application ether through files, or through dll. The variant with files is easier in terms of technical realization, because it does not require serious system programming. However, it is not very convenient to work with files, because we do not know beforehand where MetaTrader 4 terminals for different brokerage companies will be, on what currencies they will be tested, what to do if the files are lost, and so on. If we need everything to be done dynamically, with maximum security, it is better to organize data passing through dll. For different terminals to operate with one dll, it should be located in the system directory windows\system32. It is important that EAs from one terminal download one and the same dll copy, because all they operate within one process, which is the terminal (terminal.exe), it means the have one and the same address space, i.e. they operate with the same variables. One terminal with EAs has its own dll copy for all EAs and the same variables, announced inside dll, another terminal has another copy with other variables. Thus a terminal does not get access to variables from another terminal. We want to create a single, where data from different terminals will be collected. There are different ways to organize a synchronous operation of different processes with one data field. This may be implemented through files, but again we will face the problem of path indicating, as well as the problem with the processing speed if we have many terminals and EAs. The best solution is a dividable core memory. Working with it requires higher attention and knowledge of the features of the used operating system (in our case it is Windows), however, the available possibilities are infinite. For the organization of a successive access to a certain block of the shared memory a special mechanism of program semaphores is used. Theory conclusion: through dll EAs write data into shared memory, and then in the application, let us call it Monitor, it reads data from the memory, displays it and conducts necessary statistic calculations. When MetaTrader 4 calls DLL for the first time, operating system generates a copy of this DLL for each terminal, because each terminal is a separate process. The operating scheme is in the picture below. Practice Expert Advisor Certainly, data about the current trade should be formed by an Expert Advisor. For data passing we need to form the interface of the function dll. For the implemented task we need three functions: bool NewExpert(string isBrokerName, string isInstrument, int Digit); Create a new Expert Advisor, identifying it by a broker's name and security. For the calculation of some statistical characteristics we pass the number of figures after a point in a security price. bool NewDeal(string isInstrument, int Action, int magik, double PriceOpen, int Slippage, int TimeForOpen, int Requotes);The registration of a new trade is performed the following way. While the terminal-process is already identified by a broker's name, for a new trade the name of a security upon which the trade is executed is enough. Other parameters are the trade characteristics. Table 1. Trade Opening bool CloseDeal(string isInstrument, int magik, double PriceClose, int Slippage, int TimeForClose, int Requotes); A trade closing is identified upon a security and the magic. Passed parameters: Table 2. Trade Closing Due to this interface, initialization and opening and closing functions will look like this: Initialization: int init() { int Digit; if(IsDllsAllowed() == false) { Print("Calling from libraries (DLL) is impossible." + " EA cannot be executed."); return(0); } if(!IsTradeAllowed()) { Print("Trade is not permitted!"); return(0); } Digit = MarketInfo(Symbol(), MODE_DIGITS); if((Digit > 0) && (Bid > 0)) { if(!NewExpert(AccountServer(), Symbol(), Digit)) { Print("Creation of a new broker failed"); return (0); } Print("A broker is successfully created "); return(0); } Print("No symbol in MarketInfo!"); return(0); } During the initialization after checking the terminal parameters (trade permission and confirmation of DLL calling) we receive the information about a security's digits and its current price. If both parameters are more than zero, the security is adequately presented in the terminal and we can work with it. Each broker differs in its name that can be received using the function AccountServer(), upon this name terminals differ from one another in the shared memory. EAs differ in the name of security they are trading with. That is why if different EAs are attached to one and the same currency pair, they will download one and the same DLL copy which may lead to collision. Function of opening a new order: int Deal(int act, double Lot) { int N = 0; int ticket; int err; double Price_open; double Real_price; datetime begin_deal; double Lots; int cmd; int magik; magik = GenericMagik() + 1; Lots = NormalizeDouble(Lot, 1); // checking margin for a position opening AccountFreeMarginCheck(Symbol(), cmd, Lots); err = GetLastError(); if(err > 0) { Print("No money for new position"); return(0); } begin_deal=TimeCurrent(); while(N < count) { if(act == 1) { Price_open = NormalizeDouble(Ask, Digits); cmd = OP_BUY; } if(act == 2) { Price_open = NormalizeDouble(Bid, Digits); cmd = OP_SELL; } ticket = OrderSend(Symbol(), cmd, Lots, Price_open, slippage, 0, 0, 0, magik); if(ticket > 0) { if(OrderSelect(ticket, SELECT_BY_TICKET) == true) { Real_price = OrderOpenPrice(); NewDeal(Symbol(), cmd,magik, Real_price , MathAbs(Real_price - Price_open), (TimeCurrent() - begin_deal), N); } return(ticket); } N++; Sleep(5000); RefreshRates(); } return(0); } An order is opened by the function Deal with two parameters: action (1 - buy, 2 - sell ) and lot. Each order differs from the previous one in magic - it is incremented. A position tries to open in count attempts. Thу information about the number of attempts together with opening duration, price and slippage is passed into a shared memory, from where it is read by the monitor. Order closing function: bool CloseOrder(int magik) { int ticket, i; double Price_close; int count = 0; datetime begin_time; double Real_close; begin_time = TimeCurrent(); for(i = OrdersTotal() - 1; i >= 0; i--) { if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) if(OrderSymbol() == Symbol()) if(OrderMagicNumber() == magik) { while(count < 10) { if(OrderType() == OP_BUY) Price_close = NormalizeDouble(Bid, Digits); if(OrderType() == OP_SELL) Price_close = NormalizeDouble(Ask, Digits); if(OrderClose(OrderTicket(), OrderLots(), Price_close, slippage)) { Real_close = OrderClosePrice(); CloseDeal(Symbol(), magik, Real_close, MathAbs(Real_close - Price_close), (TimeCurrent() - begin_time), count); return(true); } count++; Sleep(5000); RefreshRates(); } } } return(false); } Function of closing CloseOrder() has only one input parameter - the magic. An order tries to close several times and this number of attempts will be passed together with the time of transaction execution, closing price and slippage into the memory and then read by the monitor. The remaining code is the tested EA. So for using Statistic in your own EAs, you need to import the necessary dll functions; for initialization and opening/closing positions use functions Deal and CloseOrder. If you want, you may rewrite these functions, but data on transactions should be passed in accordance with the interface contained in dll. // Enable dll for operation with monitor #import "statistik.dll" bool NewExpert(string isBrokerName, string isInstrument, int Digit); // Create a broker bool NewDeal(string isInstrument, int Action, int magik, double PriceOpen, int Slippage, int TimeForOpen, int Requotes); bool CloseDeal(string isInstrument, int magik, double PriceClose, int Slippage, int TimeForClose, int Requotes); #import //---- extern int Num_Deals = 3; extern int TimeInMarket = 4; // maximally acceptable slippage int slippage = 10; // time for rest after a trade int TimeForSleep = 10; // period of request int time_for_action = 1; // number of attempts for opening a position int count = 5; // Function of a new bar bool isNewBar() { static datetime BarTime; bool res = false; if(BarTime != Time[0]) { BarTime = Time[0]; res = true; } return(res); } //+------------------------------------------------------------------+ //| Generation of magic | //+------------------------------------------------------------------+ int GenericMagic() { int deals; //---- for(int i = OrdersTotal() - 1; i >= 0; i--) { if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) if(OrderSymbol() == Symbol()) if(OrderMagicNumber() != 0) deals++; } return (deals); } //+------------------------------------------------------------------+ //| forming signals to open/close a position | //+------------------------------------------------------------------+ int GetAction(int &action, double &lot, int &magic) { int cnt, total; if(OrdersTotal() <= Num_Deals) { if(Close[1] > Close[2]) { action = 1; lot = 1; return(0); } if(Close[2] < Close[1]) { action = 2; lot = 1; return(0); } } total = OrdersTotal(); for(cnt = total - 1; cnt >= 0; cnt--) { if(OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES)) if(OrderSymbol() == Symbol()) if((TimeCurrent() - OrderOpenTime()) > TimeInMarket*60) { action = 3; magic = OrderMagicNumber(); return(0); } } } //+------------------------------------------------------------------+ //| expert start function | //+------------------------------------------------------------------+ int start() { int action = 0; double lot = 1; int magic = 0; while(!IsStopped()) { Sleep(time_for_action*1000); RefreshRates(); if(isNewBar()) { GetAction(action, lot, magic); if(((action == 1) || (action == 2))) { if(IsTradeAllowed()) Deal(action, lot); Sleep(TimeForSleep*1000); } if(action == 3) { if(IsTradeAllowed()) if(!CloseOrder(magik)) { Print("MANUAL CLOSING OF A POSITION IS NEEDED"); Sleep(TimeForSleep*1000); } } action = 0; lot = 0; magik = 0; } } Print("A serious error occurred, the EA stopped operating"); return(0); } //+------------------------------------------------------------------+The EA's executive block is an infinite cycle on the start function. At a preset frequency time_for_action the EA calls the analytical function GetAction() , which by reference returns an action that should be done by the EA, lot with which a position should be opened, and magic in case if you need to close a position. The analytical block is elementary here - buy, if the previous bar was more than the one before it, and sell if vice versa. Positions are closed by time. For testing your own EAs simply rewrite this block in accordance with their algorithm. You may make no changes in the executive part. DLL DLL may be implemented in different environments and in different languages. The dll necessary for our work was created in Visual C++. The trades will have the following structure: struct DealRec { int Index; int Magic; int Cur; int Broker; double PriceOpen; double PriceClose; int SlipOpen; int SlipClose; int Action; // 0 = BUY 1 = SELL int TimeForOpen; int TimeForClose; int ReqOpen; int ReqClose; int Profit; bool Checked; // indication that the position is closed }; They will be fulfilled in two stages - at opening and closing. I.e. one part of data (opening price, slippage at opening etc.) is passed at opening, another part (closing price, closing time etc.) is passed at closing. Prototypes of calling a function in dll __declspec(dllexport) bool __stdcall NewExpert (char *isBrokerName, char *isInstrument, int Digit); __declspec(dllexport) bool __stdcall NewDeal (char *isInstrument, int Action, int magic, double PriceOpen, int Slippage, int TimeForOpen, int Requotes); __declspec(dllexport) bool __stdcall CloseDeal (char *isInstrument, int magic, double PriceClose, int Slippage, int TimeForClose, int Requotes); differ from prototypes in MQL4 only in passing lines. You may look through source dll, which may help in creation of other projects. For the project recompiling open the file statistic.dsw using the program Visual C++. The full code dll is in the files statistic.cpp and statistic.h, the remaining ones are subsidiary. All the enumerated files are in Statistic.zip. Monitor An optimal tool for a quick writing of applications with tables and graphical interface - solution from Borland. That is Delphi and C++Builder. Monitor functions: create a shared memory, read data from it and display in tables, keep the statistics of slippage. There are some more options that make the work more convenient. So this is the functional of the monitor: - Keeping the journal of opened positions; - Keeping the journal of closed positions; - Statistics of slippage and requotes; - Adjustable tables; - Saving trades in html-file. The implementation is in the attached zip-file Statistic Monitor.zip. For the project recompiling use the program C++Builder. Extension of the project file is *.bpr. The main code is in в main.cpp. Testing For testing a special EA was created - it has the simplest conditions of entering and closing positions by time (the implementation was shown earlier). The EA with dll and monitor.exe is in the zip-file monitor+dll+expert.zip. When starting, click START, thus creating a shared memory. DLL should be in the folder system32. After that start several terminals and attach the EA to charts of currencies, on which it is going to trade. After a number of trades statistics is accumulated. The data is collected in the monitor/Journal. From time to time they should be transfered into a file, stored in the form of html-page. The real operation of the application will be the same. It allows traders to compare the operation of different brokerage companies in terms of their technical characteristics and choose the best ones for automated trading. Conclusion Enabling dll in MQL4 allows to develop different application programs, which help not only make decisions about trading, but also collect statistics. The latter one may be very useful in trafing and in choosing a brokerage company. The created application should help developers in this difficult search. For analyzing brokers, attach statistic.dll to an Expert Advisor as described in the example analyzed in this article. The files necessary for the work are in monitor+dll+expert.zip. For the operation copy statistic.dll into the folder system32, start Statistic. exe from any location and open terminal with Expert Advisors, which download dll, start trading and passing their data into the shared memory. Statistic.exe creates auxiliary files, that is why it is better to start the application from an empty folder. If the program is interesting to the developers of trading robots, it can be modified and amended. It should be noted that not all brokerage companies provide similar conditions for the automated trading: - A broker may prohibit automated trading. - A broker may prohibit to indicate at order placing SL or TP. - Nonsymmetrical levels for SL and TP. - May have no option of a mutual opening of orders. - Restriction on the number of simultaneously opened positions in an account. If the number of orders (open positions + pending orders) exceeds the restriction, the function OrderSend will return the error code ERR_TRADE_TOO_MANY_ORDERS. - Other restrictions. That is why it is strongly recommended to read carefully the regulations of the brokerage company you are going to work with. The project Statistic shows, what complexes can be created if you add the possibilities of other languages and programming environments to MQL4 options. The created program will be useful for Expert Advisors working with different brokerage companies, because it helps to analyze their technical characteristics in a convenient form. If a brokerage companies has slippages, trades are executed by time and requotes are quite often, then what for do we need such a brokerage company? There are so many alternatives! Translated from Russian by MetaQuotes Software Corp. Original article:
https://www.mql5.com/en/articles/1476
CC-MAIN-2020-34
en
refinedweb
Often your application will require some kind of recurring task that should happen at a specific time of the week, every minute, or every few months. These tasks can be things like: Reading XML from a directory and importing it into a remote database Checking if a customer is still a subscriber in Stripe and updating your local database Cleaning your database of unneeded data every minute or so Send an API call to a service in order to fire certain events Or anything in between. There are lots of use cases for simple tasks to be ran during certain parts of the day or even "offline" hours when your employees are gone. First we will need to install the scheduler feature. We can simply pip install it: terminal$ pip install masonite-scheduler and then add the Service Provider to our PROVIDERS list in config/providers.py: config/providers.py...from masonite.scheduler.providers import ScheduleProviderPROVIDERS = [AppProvider,......ScheduleProvider, # Here] This provider will add several new features to Masonite. The first is that it will add two new commands. The first command that will be added is the craft schedule:run command which will run all the scheduled tasks that need to run (which we will create in a bit). The second command is a craft task command which will create a new task under the app/tasks directory. Now that we added the Service Provider, we can start creating tasks. Let's create a super basic task that prints "Hi". First let's create the task itself: $ craft task SayHi This will create a file under app/tasks/SayHi.py from scheduler.Task import Taskclass SayHi(Task):def __init__(self):passdef handle(self):pass This will be the simple boilerplate for our tasks. All tasks should inherit the scheduler.task.Task class. This adds some needed methods to the task itself but also allows a way to fetch all the tasks from the container by collecting them. Make sure you read about collecting objects from the container by reading the Collecting section of the Service Container documentation. In order for tasks to be discovered they need to be inside the container. Once inside the container, we collect them, see if they need to run and then decide to execute them or not. There are two ways to get classes into the container. The first is to bind them into the container manually by creating a Service Provider. You can read the documentation on creating Service Providers if you don't know how to do that. The other way is to Autoload them. Starting with Masonite 2.0, You can autoload entire directories which will find classes in that directory and load them into the container. This can be done by adding the directory your tasks are located in to the AUTOLOAD config variable inside config/application.py: ...AUTOLOAD = ['app','app/tasks']... This will find all the tasks in the app/tasks directory and load them into the container for you with the key binding being the name of the class. You don't need to use the autoloader. You can also schedule jobs manually. To do this you'll need to use a Service Provider and bind. If you are loading jobs manually it is useful to inherit the CanSchedule class. This simply gives you a self.call() method you can use to more easily schedule your jobs and commands. You can do so in the register method of the Service Provider: from masonite.scheduler import CanSchedulefrom app.jobs.YourJob import YourJobclass YourServiceProvider(ServiceProvider, CanSchedule):def register(self):self.schedule(YourJob()).every('3 days') You can use these methods to schedule: every('5 minutes'), every_minute(), every_15_minutes(), every_30_minutes(), every_45_minutes(), daily(), hourly(), weekly(), monthly(). You can schedule commands in a similiar way. If you are loading jobs manually it is useful to inherit the CanSchedule class. This simply gives you a self.call() method you can use to more easily schedule your jobs and commands. from masonite.scheduler import CanSchedulefrom app.jobs.YourJob import YourJobclass YourServiceProvider(Serv):def register(self):self.call('your:command --flag').daily().at('9:00') Now that our task is able to be added to the container automatically, let's start building the class. Firstly, the constructor of all tasks are resolved by the container. You can fetch anything from the container that doesn't need the WSGI server to be running (which is pretty much everything). So we can fetch things like the Upload, Mail, Broadcast and Request objects. This will look something like: from scheduler.Task import Taskfrom masonite.request import Requestclass SayHi(Task):def __init__(self, request: Request):self.request = requestdef handle(self):pass The handle method is where the logic of the task should live. This is where you should put the logic of the task that should be running recurrently. We can do something like fire an API call here: from scheduler.Task import Taskimport requestsclass SayHi(Task):def __init__(self):passdef handle(self):requests.post('') The awesomeness of recurring tasks is telling the task when it should run. There are a few options we can go over here: A complete task could look something like: from scheduler.Task import Taskimport requestsclass SayHi(Task):run_every = '3 days'run_at = '17:00'def __init__(self):passdef handle(self):requests.post('') This task will fire that API call every 3 days at 5pm. All possible options are False by default. The options here are: If the time on the task is days or months then you can also specify a run_at attribute which will set the time of day it should should. By default, all tasks will run at midnight if days is set and midnight on the first of the month when months is set. We can specify which time of day using the run_at attribute along side the run_every attribute. This option will be ignored if run_every is minutes or hours. You can also set timezones on individual tasks by setting a timezone attribute on the task: from scheduler.Task import Taskimport requestsclass SayHi(Task):run_every = '3 days'run_at = '17:00'timezone = 'America/New_York'def __init__(self):passdef handle(self):requests.post('') This feature is designed to run without having to spin up a seperate server command and therefore has some caveats so be sure to read this section to get a full understanding on how this feature works. Since the scheduler doesn't actually know when the server starts, it doesn't know from what day to start the count down. In order to get around this, Masonite calculates the current day using a modulus operator to see if the modulus of the tasks time and the current time are 0. For example, if the task above is to be ran (every 3 days) in May then the task will be ran at midnight on May 3rd, May 6th, May 9th, May 12th etc etc. So it's important to note that if the task is created on May 11th and should be ran every 3 days, then it will run the next day on the 12th and then 3 days after that. After we add the directory to the AUTOLOAD list, we can run the schedule:run command which will find the command and execute it. $ craft schedule:run Masonite will fetch all tasks from the container by finding all subclasses of scheduler.tasks.Task, check if they should run and then either execute it or not execute it. Even though we ran the task, we should not see any output. Let's change the task a bit by printing "Hi" and setting it to run every minute: from scheduler.Task import Taskclass SayHi(Task):run_every = '1 minute'def __init__(self):passdef handle(self):print('Hi!') Now let's run the command again: $ craft schedule:run We should now see "Hi!" output to the terminal window. You may also run a specific task by running the schedule:run command with a --task flag. The flag value is the container binding (usually the task class name): craft schedule:run --task SayHi Or you can give your task a name explicitly: from scheduler.Task import Taskclass SayHi(Task):run_every = '1 minute'name = 'hey'def __init__(self):passdef handle(self):print('Hi!') and then run the command by name craft schedule:run --task hey Setting up Cron Jobs are for UNIX based machines like Mac and Linux only. Windows has a similar schedule called Task Scheduler which is similar but will require different instructions in setting it up. Although the command above is useful, it is not very practical in a production setup. In production, we should setup a cron job to run that command every minute so Masonite can decide on what jobs need to be ran. We'll show you an example cron job and then we will walk through how to build it. PATH=/Users/Masonite/Programming/project_name/venv/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Frameworks/Python.framework/Versions/3.6/bin* * * * * cd /Users/Masonite/Programming/project_name && source venv/bin/activate && craft schedule:run When a cron job runs, it will typically run commands with a /bin/sh command instead of the usual /bin/bash. Because of this, craft may not be found on the machine so we need to tell the cron job the PATH that should be loaded in. We can simply find the PATH by going to our project directory and running: $ env Which will show an output of something like: ...__CF_USER_TEXT_ENCODING=0x1F5:0x0:0x0PATH=/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Frameworks/Python.framework/Versions/3.6/binPWD=/Users/Masonite/Programming/masonite... If you are using a virtual environment for development purposes then you need to run the env command inside your virtual environment. We can then copy the PATH and put it in the cron job. To enter into cron, just run: $ env EDITOR=nano crontab -e and paste the PATH we just copied. Once we do that our cron should look like: PATH=/Users/Masonite/Programming/masonitetesting/venv/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Frameworks/Python.framework/Versions/3.6/bin Exit out of nano. Now we just need to setup the actual cron job: Now we just need to setup the cron task itself. This could be as easy as copying it and pasting it into the nano editor again. You may need to change a few things though. The first * * * * * part is a must and bascially means "run this every minute by default". The next part is the location of your application which is dependant on where you installed your Masonite application. The next part is dependant on your setup. If you have a virtual environment then you need to activate it by appending && source venv/bin/activate to the cron task. If you are not running in a virtual environment then you can leave that part out. Lastly we need to run the schedule command so we can append && craft schedule:run Great! Now we have a cron job that will run the craft command every minute. Masonite will decide which classes need to be executed.
https://docs.masoniteproject.com/useful-features/task-scheduling
CC-MAIN-2020-34
en
refinedweb
Code Map improvements in Visual Studio 2015 CTP6 February 23, 2015 Code Maps, previously known as Directed Graph Documents, are a great way to visualize the relationships and interdependencies between the components of your applications. They make it much easier to understand the architecture of your (or, even more useful, somebody else’s) application, and where you should start when you need to update the application. Code Maps are a core part of the features of Visual Studio that help you to visualize and get insights about code. Since Visual Studio 2015 Preview, and based primarily on your feedback, we have improved several features related to architectural and dependency analysis using Code Maps: · Simplified Architecture menu · Faster display and better responsiveness · Progressively visible solution structure and dependencies · Additional dependency link styles · Assembly styling depending on the project type · Less clutter with implicit .NET type dependencies hidden · Filters for code elements as well as dependency links Simplified Architecture menu In Visual Studio 2013 Update 3, the Architecture menu is simpler than in previous releases—we added a Generate Dependency Graph sub menu—but this is still complicated because it mixes UML designers, settings for UML code generation, and the Dependency Graph diagrams. In the more recent in Visual Studio 2015 Preview, we added an option to create a new Code Map—making things even more confusing. Now, in Visual Studio 2015 CTP6, you get a much cleaner Architecture menu: – We unified the terminology so that it refers everywhere to Code Maps, rather than sometimes to Code Maps and sometimes to Dependency Graphs or Dependency Diagrams. – We renamed the New Diagram command to New UML or Layer Diagram to make it clear what it does. – We made the code generation settings and XML import commands available from the UML Explorer, where they really make sense. – We added the tool windows that you can use as drag sources for Code Maps (Class View and Object Browser) to the Windows submenu. Faster display and better responsiveness In previous versions, it could take several minutes to generate Code Maps and Dependency Graphs. In Visual Studio2015 CTP6, we’ve improved the performance of Code Maps so that dependency generation and background processing have much less impact on the responsiveness of the UI and Code Map. For example, creating a Code Map of the Roslyn solution, with its 58 projects, takes only a few seconds. The map is responsive immediately, even though it is still being built—you can see that the dependencies between the assemblies are shown as simple gray lines until the map generation process is fully completed. Notice how Visual Studio is currently generating the map by searching for and inspecting assemblies in the background. In addition, if you were using Code Maps to understand local dependencies in a bottom-up approach by creating the map from an element in the code editor or Solution Explorer—which means it must add related elements—a build was attempted every time. This could make it very slow. In Visual Studio 2015 Preview, we introduced the Skip Build toggle button in the Code Map toolbar to avoid automatic rebuilds. However, the experience was still not completely right—until now. In Visual Studio 2015 CTP6, if you don’t want to see the details of the link dependencies and you are happy with the initial diagram, or you want to focus on a sub-diagram using the New Graph from Selection command, you can use the Cancel link located in the information bar of the Code Map. Progressively visible solution structure and dependencies In Visual Studio 2013, with very large solutions, the resulting Dependency Graphs can be virtually un-usable because there are too many assemblies, connected to each other without any notion of grouping or layers. For example, a Dependency Graph of the 58 projects in the Roslyn solution is very large, and is missing any kind of grouping that would really make it usable. We heard from Visual Studio 2013 customers how difficult it is to get useful maps from large solutions such as this. To be able to understand this graph, the first thing you had to do was to add groups manually and delete stuff you don’t want to see. This is possible, and we’ve worked with customers who found some value out in it, but it is extremely cumbersome. In Visual Studio 2015 CTP6, you quickly get a map representing the structure of the solution, and the map is much more useful. Assuming you have opened the Roslyn solution in Visual Studio 2015 CTP6 and built the solution, you can choose Generate Code Map for Solution Without Building from the Architecture menu to get the following diagram almost immediately. This is because Code Map crawls through the solution in the background extracting information about the projects and the solution folders. You can see that the projects are grouped into solution folders, which makes the diagram considerably more readable and accessible. For example, you can see the Compilers solution and, within this, the separate layers for CSharp, Visual Basic, some common Core stuff, and the Test project. Another great feature with the progressive creation of Code Maps is that, if your solution does not build in its entirety, you will immediately know which projects built and which didn’t. The structured layout makes it easy to see which project must be built first, and to specfiy the overall build order. This helps you when planning how to fix a broken build, without being overwhelmed by compiler errors. Additional dependency link styles After the initial creation of the Code Map, it does the same as it did in previous versions of Visual Studio—except, now, it does all this in the background. This includes fetching the assemblies, indexing them if required, and analysing the links. If you wait until the dependency links have been fully analysed (it takes a minute or so for this solution), you’ll notice that these links are colored, as was the case in Visual Studio 2013 Update 3 and later. The colors of the links relate to the type of dependency. One interesting point you might notice is the gray dotted link between Roslyn.Services.VisualBasic.UnitTests.dll and Microsoft.CodeAnalysis.VisualBasic.Workspaces.dll. We’ve hovered over this link in the following enlarged section of the map to show the pop-up information tooltip. This link tells us that the project generating Roslyn.Services.VisualBasic.UnitTests.dll references the project generating Microsoft.CodeAnalysis.VisualBasic.Workspaces.dll. But the link is not colored because the compiler does not really need this reference. So, unless you want to force a specific build order, it’s safe to remove this unrequired reference. In fact, removing it will probably ensure that msbuild better uses its parallel build capabilities, and therefore that your solution builds more quickly. Assembly styling depending on the project type If you look carefully at the earlier screenshots of the Code Maps, you’ll see that some of the assemblies have different colors and icons. This is because they are styled based on the project types. In the case of the Roslyn solution we’ve been using, most assemblies are libraries—the purple ones being Visual Studio extensions (VSIX). However, the new styling is more obvious when you look at a Code Map for the solution we used in the keynote demonstrations during the Connect event when we released Visual Studio 2015 Preview. In the following screenshot, which shows a close-up view, you can see that there is a Web Project, a Phone Project, and a Portable Library type. Note that the Test Projects are not yet styled in CTP6, but that’s something we are working on. Less clutter with implicit .NET type dependencies hidden In previous releases of Code Maps, every assembly in the display had a dependency link of type Inheritance with respect to mscorlib (and therefore to the Externals group). This is because all .NET types inherit from one of the mscorlib base types: System.Object, System.ValueType, System.Enum, or System.Delegate. You told us that this information is not useful because it’s not something that you had coded, but was simply an implementation detail that was adding confusion and clutter to the map—as well as adding processing time when generating the map. Since Visual Studio 2015 CTP5, Code Maps no longer represent these dependencies. Instead, you see links between assemblies and externals in colors other than green (which represents inheritance). Filters for code elements as well as dependency links In Visual Studio 2015 Preview, we introduced filters for links. In CTP6, we’ve added a new and powerful node filtering mechanism; plus additional filters for the project references, and for the external references (references from a project to an assembly that is not built from a project in the solution). The links between nodes that belong to different groups (such as classes that belong to different namespaces) are now also filtered. For example, assume that you want to build a Roslyn analyser similar to the one provided by FxCop. You can find one in Solution Explorer (for example, the class CA1813DiagnosticAnalyzer) and add it to a new Code Map. Get all of its base classes (open the shortcut menu, choose Advanced, and then choose Show All Base Types), and then get the containing namespaces and assemblies (Select All, and then Advanced | Show Containing Namespace and Assembly). The result is a diagram such as the following (we chose Bottom to Top Layout from the Layout menu so that the base class is at the top). Now we can uncheck the check boxes in the Filters window so that the map shows only the details we’re interested in. For example, by unchecking Namespace we get a grouping of classes by the assemblies where they are defined, but skipping the Namespace level. Conversely, we can check Namespace and un-check Assembly and Class to get the type of namespace dependency diagram that many customers have requested (with the caveat that if two namespaces have the same name but belong to different assemblies they will still be represented as different groups: that’s the current model of Code Maps). Filtering on test assemblies is not yet available, but we’ve heard from you that you sometimes want to be able to focus only on production code. Test assembly filtering is something we want to do in future release. Got feedback? Please try the improved Code Maps and send your feedback, ideas, and requests to vsarchfeedback@microsoft.com Thank you, The Code Insights team To be honest I can't find any usability for code map but wasting times, Why finding driven classes of a class (one the most importance features that VS still doesn't have it!) takes more than one second, One keystroke and one glance would be enough. Developers find relations, specially finding driven and concrete classes, dozen times per day. using Shift+F12 is still faster, even with a large result. This means productivity to me, doing in less time. What is the point of a visualizing classes in a large unreadable image in term of productivity. It takes more time to understand it, Scanning classes by eyes are still faster and easier. We all know that in every well designed project there are much more interfaces than classes. VS IntelliSence will fail to create an simple statement like IList<Something>list = new List<Something>() We have to write second part manually dozen times per day! I think VS team should have a better user experience for productivity! A better Shift+F12 will bring more productivity. "A picture is worth a thousand words" is not always true! . It depends on context. It doesn't work for TypeScript, does it? I like codemap, it helps in understanding new code and bring us to pace.Hope it does make my understanding better with the new code and link filtering. Code map and DGML graph documents in general are about seeing more than the immediate Shift+F12 experience, so it is intended to be complementary to that. Think of it this way if you find your head hurting after jumping through a million Shift+F12 dependencies, try stepping back, and look at the big picture with code map and see if that helps understand how the code works, and better, how to clean it up. @thorn – Code Map currently works for C#, VB and C++ Nima is not totally wrong. The user experience with current implementation is absolutly a waste of time. Especially in big projects it becomes more and more useless. I could become very useful, if there were better filter functions. For example a function that would hide all items/namespaces that are not in direct reference with my actual selection, where a selection could be multiple namespaces or a project folder. Will the filter option be available in VS2013 or are we stuck with the VS2015 upgrade, as large projects makes this tool useless if there is no filter of the clutter? @Denis: Filters won't be available in VS 2013. In any case I strongly advise you to upgrade to VS 2015 as Code Map is much better for large projects there (filters, but also the Code map for solution scales). See the MSDN magazine article about that: msdn.microsoft.com/…/mt238403.aspx
https://blogs.msdn.microsoft.com/devops/2015/02/23/code-map-improvements-in-visual-studio-2015-ctp6/
CC-MAIN-2017-26
en
refinedweb
So we thought we knew money - Regina Blake - 1 years ago - Views: Transcription 1 So we thought we knew money Ying Hu Sam Peng Here at Custom House Global Foreign Exchange, we have built and are continuing to evolve a system that processes online foreign exchange transactions. Currency, money, rate and markup are terms frequently used in conversations between business stakeholders. They are part of the Glossary and appear in almost every requirement document. Not surprisingly, they show up in code quite frequently too, like this: public class Contract decimal tradingrate; bool isratedirect; string tradecurrency; decimal tradeamount; string settlementcurrency; decimal settlementamount; decimal Markup; (Code example 1) In the example, rate, currency and markup are represented as decimal, string, decimal respectively. These important terms appear in the code, but only in variable names of primitive types and sometime in method names whose arguments and return types are all primitives. The Problem A primitive type does not capture a domain concept. Take rate, for example. A rate is the ratio at which a unit of one currency may be exchanged for a unit of another currency. A decimal 1.12 is meaningless unless we know it is the ratio between USD and CAD. And even that is not enough. We must also know the rate direction (is it a rate to convert USD to CAD, or to convert CAD to USD) before we know how to apply it (multiply or divide?). Consequently, business logic was duplicated in several classes that calculate amount from rate. The Contract class provides a typical case. It contained a method to sort out these variations on rate: 1 2 decimal CalculateSettlementAmount( bool isratedirect, decimal tradeamount, decimal tradingrate) if (isratedirect) return RoundAmount(tradeAmount * tradingrate); else return RoundAmount(tradeAmount / tradingrate); (Code example 2) The Contract class then calculated settlement amount by calling: decimal settlementamount = CalculateSettlementAmount( true, 200m, 1.12m); Markup had the same duplication, and also had no explicit definition within the design. In foreign exchange, a markup is an amount or a percentage added to the market rate to determine the rate being offered to customer. You can think of this as similar to the profit a grocery store makes selling apples: They buy apples for $2/lb wholesale and sell them to customers at $2.50, a 25% markup. Markups on currency exchange rates are not so large, but if it costs 1.2 US Dollar to buy one Euro on the market and then manage it, then it might typically be marked up 2%, resulting in a price to customers of USD. Applying a markup to a rate is not straightforward, it depends on 1. markup type: whether it s percentage markup, or a points markup, and 2. markup direction: whether you want to markup a rate that sells Euro to customer, or to markup a rate that buys Euro from customer. 3. markup algorithm: what formula should be used, whether there are exceptional cases or not. This application logic was expressed by the following code: decimal ApplyMarkup( decimal rate, decimal markup, bool ispercentagemarkup, bool isbuymarkup) if (isbuymarkup) if (ispercentagemarkup) return rate* (1-markup); else return rate-markup; else 2 3 if (ispercentagemarkup) return rate* (1+markup); else return rate+markup; (Code example 3) When a contract used a markup, it called: decimal newrate = ApplyMarkup(1.12, 0.02, true, false); (Code example 4) The above code doesn t show an explicit markup concept, only a messy function that manipulates numbers. As for currency, we did, in fact, have a currency object, but it was not used consistently throughout the code. In a lot of cases currency was simply a string. Finally, there was no object to represent the money concept, but we saw that currency and amount always appeared together. The Discovery In early 2005, our team worked with Eric Evans, of Domain Language, Inc., to improve our domain model and design over a period of months. Early on, Eric pointed out a problem he thought must be addressed right away: the excessive use of primitive types, which indicated that a significant part of the language of the domain was only implicit in the model, leaving a big hole in the ubiquitous language, leading to bulky, inflexible object code. The team spent several white board sessions discussing the business domain, important terms used by business and what they mean in our code. For some terms, we found discrepancies between the business language and the development language; for others, there was no explicit representation in the code at all. From this process, a few essential value objects emerged and were refined, of which we consider Currency, Money, Rate, and Markup to be the most important. Currency: a unit of exchange. At first glance, it seems acceptable to use a string because currency is simply a 3-letter string without much specific logic. However, consider the following code: 3 4 Before: decimal GetRate(string unitcurrency, string referencecurrency); After: Rate GetRate(Currency unitcurrency, Currency referencecurrency); The second method clearly tells its callers that it expects two "Currency" parameters. Even though currency can be represented by a string, a string is by no means a currency! There is also a finite set of valid currencies allowed in the system; a factory method easily ensures the validation: Currency gbp = CurrencyList.Get( GBP ) Money: An amount of a particular currency. The object s major responsibility is to handle common monetary arithmetic and comparison properly. In a financial system like ours, it is no coincidence that amount always appears side-by-side with currency. Having a Money object greatly simplifies code, like this: Before public decimal CalculateProfit( string tradecurrency, decimal tradeamount, string settlementcurrency, decimal settlementamount) After public Money CalculateProfit( Money trademoney, Money settlementmoney) Note that the first method actually makes the assumption that the returned amount has the same currency as the settlementcurrency logic that can only be discovered by the diligent developer who looks into the method implementation. So, not only is the new code shorter, it also helps to make hidden logic explicit. Rate: A conversion of money of one currency into money of another currency. A Rate object derives one Money object from another. Rate knows which two currencies it relates, and how to calculate the conversion between them. The primary responsibility of rate is expressed through the method: public Money Convert (Money money) With the new smart Rate object, Contract calculates its settlement simply by calling: Money settlementmoney = tradingrate.convert(trademoney) This works as well: Money trademoney = tradingrate.convert(settlementmoney) 4 5 Either way the calculation is stated, the Rate knows how to properly convert between the two currencies. By comparing to (Code example 2), you can see how completely calculation and rounding logic is encapsulated! Markup: An amount of points or percentage added to wholesale cost to arrive at a resale price of rate. A Markup object can apply itself, following a certain formula, to a rate to produce a different rate. This is represented by the method on Markup: public abstract Rate AppliedTo(Rate rate); We designed markup as an abstract object with three subclasses (including the null object): Once a markup object is obtained, it can take a rate and apply it s calculation logic on it. Now contract uses markup like this (compare with Code example 4) Markup percentagemarkup = new PercentageMarkup( ); Rate newrate = percentagemarkup.appliedto(oldrate); Replacing primitive types with value objects based on fundamental domain concepts gives us other benefits too: 1. We are able to create and use Null objects, for example: class NullPercentageMarkup: PercentageMarkup // public static readonly PercentageMarkup NULL = new NullPercentageMarkup(); 2. We have a list of methods that have the nice property "Closure of Operations" Rate.AppliedTo(Money) --> Money Markup.AppliedTo(Rate) --> Rate 3. Those value objects are designed to be immutable. They are simply constructed with a constructor and are never changed except by full replacement. Calculations produce new instances. Immutable objects have well-documented advantages in designs. They mean the program can copy or share the objects freely. They mean a programmer does not need to be concerned about side-effects involving these 5 6 objects and their calculations. We found these properties helped us clarify our code and reduce bugs. Next Step: Retrofitting In a complex system like ours, it was a significant job to replace types that thread throughout the system and form its very heart. Here is an example modification of one of our existing domain objects: Before public class Order //... private decimal settlementamount; private string settlementcurrency; public string SettlementCurrency get return settlementcurrency; public decimal SettlementAmount get return settlementamount; Payment payment = new Payment(); payment.totalamount = order.settlementamount; payment.totalcurrency = order.settlementcurrency; After public class Order //... private decimal settlementamount; private Currency settlementcurrency; public Money SettlementMoney get return new Money( settlementcurrency, settlementamount); Payment payment = new Payment(); payment.total = order.settlementmoney; 6 7 The new Order class exposes SettlementMoney property, which makes its client, the Payment class, clearer and more concise.. Before public interface IRateSource decimal GetSpotProfitRate ( string unitcurrency, string referencecurrency, TradeDirection direction, string specifiedcurrency, decimal specifiedamount ); After public interface IRateSource Rate GetSpotProfitRate ( Currency unitcurrency, Currency referencecurrency, TradeDirection direction, Money specifiedmoney ); Currency, Money, Rate and Markup - they seem straightforward enough perhaps obvious, in hindsight. Yet we walked a long way to make them explicit with well defined responsibilities. Having these domain fundamentals represented in our model allowed our design and code to start to speak the same language as people in the business do. As these concepts work their way into the system, the habit of thinking in domain terms also gradually works its way into the team. More value objects have been designed to express the model such as BidAsk, ProfitRateQuote and PaymentMethod; more primitive types have been replaced The Future And a Few Pitfalls This is only the start. These value objects are now widely used in the system. But because of their prominent expressive power, developers start to put stuff in just because of convenience. Consider the following method defined inside Rate class: public Money AddMoney(Money target, Money moneytoadd) return target + Convert(moneyToAdd); 7 8! public static implicit operator decimal(rate rate) return rate.value; This code allows a rate to be implicitly cast into decimal the exact opposite of our intention in creating the value objects!. 2007, Ying Hu and Sam Peng 8 System Software Product Line System Software Product Line 2 1 Introduction The concept of Software Product Lines has been developed for more than a decade. Being initially an academic topic, product lines are more and more incorporated Work Example Question 1 Work Example Question 1 1 Question: Assuming one quarter of the revenue generated in 2008 was profit, how much profit did Lucy and Laura make that year? Answers: $13,500 $3,375 $2,250 $1,125 1) Start by FX Domain Kick-start for Testers FX Domain Kick-start for Testers A brief introduction to key FX elements. Discussion Document by Mark Crowther, Principle Test Architect Tien Hua, Senior Test Analyst Table of Contents Introduction... 2. Basic Relational Data Model 2. Basic Relational Data Model 2.1 Introduction Basic concepts of information models, their realisation in databases comprising data objects and object relationships, and their management by DBMS s that INTRODUCTION. This program should serve as just one element of your due diligence. FOREX ONLINE LEARNING PROGRAM INTRODUCTION Welcome to our Forex Online Learning Program. We ve always believed that one of the best ways to protect investors is to provide them with the materials they The Rules 1. One level of indentation per method 2. Don t use the ELSE keyword 3. Wrap all primitives and Strings Object Calisthenics 9 steps to better software design today, by Jeff Bay We ve all seen Java: Learning to Program with Robots. Chapter 11: Building Quality Software Java: Learning to Program with Robots Chapter 11: Building Quality Software Chapter Objectives After studying this chapter, you should be able to: Identify characteristics of quality software, both from MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. Study Questions 5 (Money) MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) The functions of money are 1) A) medium of exchange, unit of account, 09336863931 : provid.ir provid.ir 09336863931 : NET Architecture Core CSharp o Variable o Variable Scope o Type Inference o Namespaces o Preprocessor Directives Statements and Flow of Execution o If Statement o Switch Statement The Phases of an Object-Oriented Application The Phases of an Object-Oriented Application Reprinted from the Feb 1992 issue of The Smalltalk Report Vol. 1, No. 5 By: Rebecca J. Wirfs-Brock There is never enough time to get it absolutely, perfectly Writing a Requirements Document For Multimedia and Software Projects Writing a Requirements Document For Multimedia and Software Projects Rachel S. Smith, Senior Interface Designer, CSU Center for Distributed Learning Introduction This guide explains what a requirements Computer Programming I Computer Programming I COP 2210 Syllabus Spring Semester 2012 Instructor: Greg Shaw Office: ECS 313 (Engineering and Computer Science Bldg) Office Hours: Tuesday: 2:50 4:50, 7:45 8:30 Thursday: 2:50 4:50, Why HTML5 Tests the Limits of Automated Testing Solutions Why HTML5 Tests the Limits of Automated Testing Solutions Why HTML5 Tests the Limits of Automated Testing Solutions Contents Chapter 1 Chapter 2 Chapter 3 Chapter 4 As Testing Complexity Increases, So Introduction to Foreign Currency Exchange Introduction to Foreign Currency Exchange Introduction to Foreign Currency Exchange In the most basic of terms, currency exchange (also known as foreign exchange, forex or FX) is where you swap one currency Foreign Exchange Market INTERNATIONAL FINANCE. Function and Structure of FX Market. Market Characteristics. Market Attributes. Trading in Markets Foreign Exchange Market INTERNATIONAL FINANCE Chapter 5 Encompasses: Conversion of purchasing power across currencies Bank deposits of foreign currency Credit denominated in foreign currency Foreign trade Balanced Assessment Test Algebra 2008 Balanced Assessment Test Algebra 2008 Core Idea Task Score Representations Expressions This task asks students find algebraic expressions for area and perimeter of parallelograms and trapezoids. Successful THE OPTIMIZER HANDBOOK: THE OPTIMIZER HANDBOOK: LEAD SCORING Section 1: What is Lead Scoring? Picture this: you re selling vehicles, and you have a list that features over two hundred different leads, but you re only allowed PHP5 Design Patterns in a Nutshell. By Janne Ohtonen, August 2006 By Janne Ohtonen, August 2006 Contents PHP5 Design Patterns in a Nutshell... 1 Introduction... 3 Acknowledgments... 3 The Active Record Pattern... 4 The Adapter Pattern... 4 The Data Mapper Pattern... Domain-Driven Design SWE577 2011S 1 Domain-Driven Design Ali Fındık Abstract Domain Driven Design (DDD) is an approach to developing software for complex needs by deeply connecting the implementation to an evolving model of Calculating performance indicators - liquidity Calculating performance indicators - liquidity Introduction When a business is deciding whether to grant credit to a potential customer, or whether to continue to grant credit terms to an existing Web Application Development for the SOA Age Thinking in XML Web Application Development for the SOA Age Thinking in XML Enterprise Web 2.0 >>> FAST White Paper August 2007 Abstract Whether you are building a complete SOA architecture or seeking to use SOA services Total Student Count: 3170. Grade 8 2005 pg. 2 Grade 8 2005 pg. 1 Total Student Count: 3170 Grade 8 2005 pg. 2 8 th grade Task 1 Pen Pal Student Task Core Idea 3 Algebra and Functions Core Idea 2 Mathematical Reasoning Convert cake baking temperatures How Leverage Really Works Against You Forex Trading: How Leverage Really Works Against You By: Hillel Fuld Reviewed and recommended by Rita Lasker 2012 Introduction: The Forex market is an ideal trading arena for making serious profits. CS 61A Scheme to CS 61B Java Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope) Synchronizing databases TECHNICAL PAPER Synchronizing databases with the SQL Comparison SDK By Doug Reilly In the wired world, our data can be almost anywhere. The problem is often getting it from here to there. A common problem, Introduction to Futures Contracts Introduction to Futures Contracts September 2010 PREPARED BY Eric Przybylinski Research Analyst Gregory J. Leonberger, FSA Director of Research Abstract Futures contracts are widely utilized throughout Android Application Development Course Program Android Application Development Course Program Part I Introduction to Programming 1. Introduction to programming. Compilers, interpreters, virtual machines. Primitive data types, variables, basic operators, Testing and Inspecting to Ensure High Quality Testing and Inspecting to Ensure High Quality Basic definitions A failure is an unacceptable behaviour exhibited by a system The frequency of failures measures the reliability An important design objective The Magic Lines Trading System The Magic Lines Trading System A trading system that works with all instruments, indexes and currencies. This copy is with compliments from Markets Mastered. For the full range of systems visit: 3. The Foreign Exchange Market 3. The Foreign Exchange Market The foreign exchange market provides the physical and institutional structure through which the money of one country is exchanged for that of another country, the rate of Time Value of Money Dallas Brozik, Marshall University Time Value of Money Dallas Brozik, Marshall University There are few times in any discipline when one topic is so important that it is absolutely fundamental in the understanding of the discipline. How to Plan a Successful Load Testing Programme for today s websites How to Plan a Successful Load Testing Programme for today s websites This guide introduces best practise for load testing to overcome the complexities of today s rich, dynamic websites. It includes 10 CS 111 Classes I 1. Software Organization View to this point: CS 111 Classes I 1 Software Organization View to this point: Data Objects and primitive types Primitive types operators (+, /,,*, %). int, float, double, char, boolean Memory location holds the data Objects PharmaSUG 2016 Paper IB10 ABSTRACT PharmaSUG 2016 Paper IB10 Moving from Data Collection to Data Visualization and Analytics: Leveraging CDISC SDTM Standards to Support Data Marts Steve Kirby, JD, MS, Chiltern, King of Prussia, Essential Question Essential Question Essential Question Essential Question Essential Question Essential Question Essential Question What is the difference between an arithmetic and a geometric sequence? Essential Question Essential Question Essential Question Essential Question Essential Question Essential Question Essential Question Automated Underwriting and Pre-Qualification. Qualifying and Closing Borrowers Using a Functional Script Automated Underwriting and Pre-Qualification Qualifying and Closing Borrowers Using a Functional Script Contents Introduction - Automated Underwriting and Pre-Qualification...2 Loan Officers Have Stopped Fractions and Decimals Fractions and Decimals Tom Davis tomrdavis@earthlink.net December 1, 2005 1 Introduction If you divide 1 by 81, you will find that 1/81 =.012345679012345679... The first Computing Concepts with Java Essentials 2008 AGI-Information Management Consultants May be used for personal purporses only or by libraries associated to dandelon.com network. Computing Concepts with Java Essentials 3rd Edition Cay Horstmann Q&A: Your Ebook Engine Your books. Your brand. Your customer. Q&A: Your Ebook Engine 1. What is Ebook Engine? Ebook Engine enables you to sell electronic books with your existing e-commerce infrastructure. 2. So how exactly Building the business case for ITAM Building the business case for ITAM Executive summary An ITAM Review reader asked: What data do I need to collect to show the value of my ITAM practice? This article attempts to answer that question, from Chapter 8 Software Testing Chapter 8 Software Testing Summary 1 Topics covered Development testing Test-driven development Release testing User testing 2 Program testing Testing is intended to show that a program does what it is Code Qualities and Coding Practices Code Qualities and Coding Practices Practices to Achieve Quality Scott L. Bain and the Net Objectives Agile Practice 13 December 2007 Contents Overview... 3 The Code Quality Practices... 5 Write Tests THE THREE ASPECTS OF SOFTWARE QUALITY: FUNCTIONAL, STRUCTURAL, AND PROCESS David Chappell THE THREE ASPECTS OF SOFTWARE QUALITY: FUNCTIONAL, STRUCTURAL, AND PROCESS Sponsored by Microsoft Corporation Our world runs on software. Every business depends on it, every mobile phone 7 Habits of Highly Successful Property Investors 7 Habits of Highly Successful Property Investors 7 Habits of Highly Successful Property Investors In property investment there are people who have been hugely successful, making enough money to buy them Introduction to Diophantine Equations Introduction to Diophantine Equations Tom Davis tomrdavis@earthlink.net September, 2006 Abstract In this article we will only touch on a few tiny parts of the field 2. Compressing data to reduce the amount of transmitted data (e.g., to save money). Presentation Layer The presentation layer is concerned with preserving the meaning of information sent across a network. The presentation layer may represent (encode) the data in various ways (e.g., 9 Steps to Selecting and Implementing an IP Business Phone System 9 Steps to Selecting and Implementing an IP Business Phone System 2011, GWI Introduction: GWI has written this whitepaper in an effort to provide our customers with an overview of the process of identifying, How to Improve your next Software Purchase How to Improve your next Software Purchase Sub-title here How to Improve your next Software Purchase One of the big areas of concern for growing businesses is How do we choose the right software and supplier Number Systems and Radix Conversion Number Systems and Radix Conversion Sanjay Rajopadhye, Colorado State University 1 Introduction These notes for CS 270 describe polynomial number systems. The material is not in the textbook, but Software Engineering Techniques Software Engineering Techniques Low level design issues for programming-in-the-large. Software Quality Design by contract Pre- and post conditions Class invariants Ten do Ten do nots Another type of summary (Refer Slide Time 00:56) Software Engineering Prof.N. L. Sarda Computer Science & Engineering Indian Institute of Technology, Bombay Lecture-12 Data Modelling- ER diagrams, Mapping to relational model (Part -II) We will continue experience INTERNATIONAL FINANCE AND EXCHANGE RATES INTERNATIONAL FINANCE AND EXCHANGE RATES CHAPTER 16 1 CHAPTER OUTLINE International Financial Transactions Foreign Exchange Markets Alternative Foreign Exchange Systems 2 YOU ARE HERE 3 CURRENCY In DIGITAL-TO-ANALOGUE AND ANALOGUE-TO-DIGITAL CONVERSION DIGITAL-TO-ANALOGUE AND ANALOGUE-TO-DIGITAL CONVERSION Introduction The outputs from sensors and communications receivers are analogue signals that have continuously varying amplitudes. In many systems, Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction Connecting Currency. Tel: +44 (0)1736 335250 Connecting Currency Consistently Excellent I have used TorFX for nearly 5 years now. From major transfers to smaller ones, the service works like a finely tuned machine. Daily market updates are excellent, Inflation. Chapter 8. 8.1 Money Supply and Demand Chapter 8 Inflation This chapter examines the causes and consequences of inflation. Sections 8.1 and 8.2 relate inflation to money supply and demand. Although the presentation differs somewhat from that Getting started with API testing Technical white paper Getting started with API testing Test all layers of your composite applications, not just the GUI Table of contents Executive summary... 3 Introduction... 3 Who should read this Chapter 4.1. Intermarket Relationships 1 Chapter 4.1 Intermarket Relationships 0 Contents INTERMARKET RELATIONSHIPS The forex market is the largest global financial market. While no other financial market can compare to the size of the forex USING METHODS PROGRAMMING EXAMPLES USING METHODS PROGRAMMING EXAMPLES Roulette French Roulette is a casino game that uses a wheel with 37 pockets numbered 0 to 36. To play a straight-up bet, you lay your money beside any single number. Chapter Four: How to Collaborate and Write With Others Chapter Four: How to Collaborate and Write With Others Why Collaborate on Writing? Considering (and Balancing) the Two Extremes of Collaboration Peer Review as Collaboration * A sample recipe for how peer 3Lesson 3: Web Project Management Fundamentals Objectives 3Lesson 3: Web Project Management Fundamentals Objectives By the end of this lesson, you will be able to: 1.1.11: Determine site project implementation factors (includes stakeholder input, time frame, Module 10. Coding and Testing. Version 2 CSE IIT, Kharagpur Module 10 Coding and Testing Lesson 23 Code Review Specific Instructional Objectives At the end of this lesson the student would be able to: Identify the necessity of coding standards. Differentiate between nouns verbs methods class noun COMP209 Object Oriented Programming Designing Classes Mark Hall Overview Choosing Classes Cohesion & Overview Designing classes can be a challenge How to start? Is the result of good quality? Good class (Refer Slide Time: 01:52) Software Engineering Prof. N. L. Sarda Computer Science & Engineering Indian Institute of Technology, Bombay Lecture - 2 Introduction to Software Engineering Challenges, Process Models etc (Part 2). Instructions for SA Completion Instructions for SA Completion 1- Take notes on these Pythagorean Theorem Course Materials then do and check the associated practice questions for an explanation on how to do the Pythagorean Theorem Substantive Java EE Web Development Course Program Java EE Web Development Course Program Part I Introduction to Programming 1. Introduction to programming. Compilers, interpreters, virtual machines. Primitive types, variables, basic operators, expressions, RSA VIA LIFECYCLE AND GOVERNENCE: ROLE MANAGEMENT BEST PRACTICES RSA VIA LIFECYCLE AND GOVERNENCE: ROLE MANAGEMENT BEST PRACTICES A practitioner s perspective on best practices for Role Management ABSTRACT This white paper provides an overview of the Role Management Carry Trade Explained What Is the Carry Trade? I The Forex Trading Formula Carry Trade Triad Trading Formula - The Introduction Carry Trade Carry Trade Explained What Is the Carry Trade? The carry trade is a trading strategy in which you simultaneously Mechanics of Foreign Exchange - money movement around the world and how different currencies will affect your profit Dear Business Leader, Welcome to the Business Insight Seminars an exclusive, informational series to help you gain a powerful edge in today s highly competitive business environment. Our first topic in TIMING: When and When not to invest in the Stock Market Popular Delusions TIMING: When and When not to invest in the Stock Market Popular Delusions Is there a right time to invest in the stock market? That s the magic question people have asked for as long as the stock market How To Consistently Make $900 - $9,000 in 48 Hours or Less Forex & Gold Trading Bootcamp Break-Out Session How To Consistently Make $900 - $9,000 in 48 Hours or Less CHEAT & ACTIVITY SHEET MARK SO (THE HANDSOMEST FOREX TRADER THAT EVER EXISTED ;-) MARK SO Quality Management. Managing the quality of the software process and products Quality Management Managing the quality of the software process and products Ian Sommerville 2000 Software Engineering, 6th edition. Chapter 24 Slide 1 Objectives To introduce the quality management process
http://docplayer.net/1767239-So-we-thought-we-knew-money.html
CC-MAIN-2017-26
en
refinedweb
I am just an idiot, but thats my opinion. For those with MSPGCC compilers, we have a more difficult time finding code examples, and many of the code examples given either don’ explain very well (cryptic Coding, un-commented code) or they are for the CCS or IAR, and they dont use the same syntax as the MSPGCC compiler. So here is how to create an interrupt handler for non-PUC/POR interrupts. I will not go into interrupt vector masking, that is beyond me at this moment, but im not saying that i wont cover it later on, once i understand why you would want to mask it….. So lets start at what headers and other setup items you need before, creating the interrupt handler. First the signal.h has to be included into your code. #include<signal.h> this will give you access to the special function of interrupt(VECTOR ) service_routine (void) {/*interrupt code*/ } this is the same as #pragma vector=WDT_VECTOR __interrupt void watchdog_timer(void){ } These are the Defined vectors for interrupts right from the header files.(mspgcc headers) #define PORT1_VECTOR 4 /* 0xFFE4 Port 1 */ #define PORT2_VECTOR 6 /* 0xFFE6 Port 2 */ #define USI_VECTOR 8 /* 0xFFE8 USI */ #define ADC10_VECTOR 10 /* 0xFFEA ADC10 */ #define TIMERA1_VECTOR 16 /* 0xFFF0 Timer A CC1-2, TA */ #define TIMERA0_VECTOR 18 /* 0xFFF2 Timer A CC0 */ #define WDT_VECTOR 20 /* 0xFFF4 Watchdog Timer */ #define NMI_VECTOR 28 /* 0xFFFC Non-maskable */ all the interrupts should be self expainatory, vector = the source of the interrupt. since now we have all the basics we can now right a small program that uses interrupt, we will just create a small WDT interval timer. /*WDT interval timer- code based on msp430 examples*/ //compiler=mspgcc #include<msp430x22x2.h> #include<signal.h> //interrupt service routine #include <io.h> //usually included on msp430 header, but for sfr register access. void main(void) { WDTCTL = WDT_MDLY_32; //~30mS intervals P1DIR |=BIT1; IE1 |= WDTIE; //enable interrupt _BIS_SR(LPM0_bits + GIE); //not low power mode and enable interrupts }//end of main //interrupt service routine interrupt(WDT_VECTOR) watchdog_timer(void) { P1OUT ^= BIT1; }//end of interrupt this should give you a good start on your Interrupts but there is still one thing that you may need. Changing the power modes when a interrupt is being serviced, the power mode will revert back to the power mode that it was in when the interrupt was called. There are 2 functions that we can use to clear or set power modes while in an interrupt. First one is to set the mode on exit of the routine, this is done by changing the copy of the status register that is saved to the stack. _BIS_SR_IRQ( ... ) you would use this the same way you would use the _BIS_SR(…) The second one will clear the bits you select _BIC_SR_IRQ(...) same usage as the other, except it will just clear the bits not modify them. ***the use of _BIx_SR_IRQ() should only be used in an interrupt service request, the compiler will give you a warning but will produce the correct code if you use it anywhere else.*** ****remember to enable Interrupts by using BIS_SR(GIE) or eint()**** Edit 6-23-2011 MSPGCC Uniarch branch of mspgcc has been released, It supports newer chips like the msp430G2453 (the newer 20pin DIPs) This is an initiative to unify the current branches of mspgcc. Interrupts for this version is slightly different. Once I test it or get confirmation from another user I will post the correct format for uniarch branch……but what would be better would be unify the branches so we don’t have so much confusion with these version discrepancies and nuances of the trees. As of right now uniarch is still being worked on and there and is not fully recommended unless you need support for the newer 20pin Dips (G2x53 G2x52). Please don’t let my opinion dissuade your choice of compiler, mspgcc works great for me but uniarch may work better for you. Thank you Tissit for your Comment “In current gcc, you can (should) include msp430.c instead of the specific header and use the -m switches (in a Makefile) to tell the compiler which chip you’re using. It will find the right headers automatically. “ If I forget something let me know and I will update
http://justinstech.org/index.php/category/programing/page/2/
CC-MAIN-2017-26
en
refinedweb
Red Hat Bugzilla – Full Text Bug Listing Description of problem: There should be nls support in help2man (1.40.12-1). Otherwise, help2man --locale en_US.UTF-8 throws "help2man: no locale support (Locale::gettext required)" Version-Release number of selected component (if applicable): help2man.noarch 1.40.12-1.fc17 @updates perl-gettext.x86_64 1.05-24.fc17 @fedora How reproducible: program.c is very small and printf é\n. Thus, it needs unicode support. Run "bash bugzilla.redhat.com-bug-help2man.sh" $ cat bugzilla.redhat.com-bug-help2man.sh # 1. Install dependencies sudo yum install -y gcc help2man perl-gettext coreutils bash &> /dev/null # 2. Create a source code cat > program.c << EOF #include <stdio.h> #include <stdlib.h> int main(int argc,char**argv){ printf("é\n"); return EXIT_SUCCESS; } EOF # 3. Compile the program gcc program.c -o program # 4. Run help2man, this calls ./program --help help2man -L en_US.UTF-8 ./program -o program.1 &> Errors # 5. Display the error head -n 1 Errors if test -f program.1 then echo "PASS: man page program.1 generated !" else echo "FAIL: man page program.1 not generated ;-(" fi Steps to Reproduce: 1. Run "bash bugzilla.redhat.com-bug-help2man.sh" 2. Read the line "help2man: no locale support (Locale::gettext required)" 3. Check in koji for nls support in help2man 1.40.12 => Actual results: $ bash bugzilla.redhat.com-bug-help2man.sh help2man: no locale support (Locale::gettext required) FAIL: man page program.1 not generated ;-( Expected results: $ bash bugzilla.redhat.com-bug-help2man.sh PASS: man page program.1 generated ! Additional info: (3 entries) 1. Information for build help2man-1.40.12-1.fc17 2. help2man in Fedora pkgdb 3. A package that needs help2man --locale Review Request: Ray - Parallel genome assemblies for parallel DNA sequencing Ping Ralf? Is there any reason this is not turned on by default? (In reply to comment #1) > Ping Ralf? Sorry for not having responded earlier. > Is there any reason this is not turned on by default? Yes. It's disabled for security reasons (Help2man uses LD_PRELOAD) ever since the package is in Fedora (many years). But it is not impossible to change the behavior...? Maybe Sébastien could have a look into it?. The specific code in help2man-1.40.12/help2man.PL that seems to do the splicing is !GROK!THIS! ... !WITH!GETTEXT! ... !NO!GETTEXT! ... The Fedora package only has the hunks for !NO!GETTEXT! and nothing at all for !WITH!GETTEXT!. If I compare the sizes (1.40.12-1.fc17 and 1.40.12 from upstream): $ wc -l /usr/bin/help2man 670 /usr/bin/help2man $ wc -l ~/help2man-1.40.12/help2man.PL 800 /home/seb/help2man-1.40.12/help2man.PL If I compare them: $ diff -u ~/help2man-1.40.12/help2man.PL /usr/bin/help2man |wc -l 168 $ diff -u ~/help2man-1.40.12/help2man.PL /usr/bin/help2man |grep ^\-|grep -v ^\-\-\-|wc -l 133 $ diff -u ~/help2man-1.40.12/help2man.PL /usr/bin/help2man |grep ^+|grep -v ^+++|wc -l 3 800 - 133 + 3 = 670 So during its evolution, help2man has lot all its --locale features for the Fedora ecological niche. (In reply to comment #4) >. I do not understand (May-be there is a language barrier in effect?) help2man in Fedora is the original help2man with no patches applied and is configured with --disable-nls. > So during its evolution, help2man has lot all its --locale features for the > Fedora ecological niche. ?!? nls in help2man is a configuration/build-time parameter. We chose to switch nls off, because the design/approach upstream chose to support nls appears error-prone and risky (c.f. info help2man "Localised man pages"). > I do not understand (May-be there is a language barrier in effect?) It just seems to me that the source code of help2man.PL is preprocessed during the packaged process, and that switching off nls eliminates lines during the preprocessing..
https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=873493
CC-MAIN-2017-26
en
refinedweb
How is it possible that files can contain null bytes in operating systems written in a language with null-terminating strings (namely, C)? For example, if I run this shell code: $ printf "Hello\00, World!" > test.txt $ xxd test.txt 0000000: 4865 6c6c 6f00 2c20 576f 726c 6421 Hello., World! test.txt Hello Hello\00, World! Null-terminated strings are a C construct used to determine the end of a sequence of characters intended to be used as a string. String manipulation functions such as strcmp, strcpy, strchr, and others use this construct to perform their duties. But you can still read and write binary data that contains null bytes within your program as well as to and from files. You just can't treat them as strings. Here's an example of how this works: #include <stdio.h> #include <stdlib.h> int main() { FILE *fp = fopen("out1","w"); if (fp == NULL) { perror("fopen failed"); exit(1); } int a1[] = { 0x12345678, 0x33220011, 0x0, 0x445566 }; char a2[] = { 0x22, 0x33, 0x0, 0x66 }; char a3[] = "Hello\x0World"; // this writes the whole array fwrite(a1, sizeof(a1[0]), 4, fp); // so does this fwrite(a2, sizeof(a2[0]), 4, fp); // this does not write the whole array -- only "Hello" is written fprintf(fp, "%s\n", a3); // but this does fwrite(a3, sizeof(a3[0]), 12, fp); fclose(fp); return 0; } Contents of out1: [dbush@db-centos tmp]$ xxd out1 0000000: 7856 3412 1100 2233 0000 0000 6655 4400 xV4..."3....fUD. 0000010: 2233 0066 4865 6c6c 6f0a 4865 6c6c 6f00 "3.fHello.Hello. 0000020: 576f 726c 6400 World. For the first array, because we use the fwrite function and tell it to write 4 elements the size of an int, all the values in the array appear in the file. You can see from the output that all values are written, the values are 32-bit, and each value is written in little-endian byte order. We can also see that the second and fourth elements of the array each contain one null byte, while the third value being 0 has 4 null bytes, and all appear in the file. We also use fwrite on the second array, which contains elements of type char, and we again see that all array elements appear in the file. In particular, the third value in the array is 0, which consists of a single null byte that also appears in the file. The third array is first written with the fprintf function using a %s format specifier which expects a string. It writes the first 5 bytes of this array to the file before encountering the null byte, after which it stops reading the array. It then prints a newline character ( 0x0a) as per the format. The third array it written to the file again, this time using fwrite. The string constant "Hello\x0World" contains 12 bytes: 5 for "Hello", one for the explicit null byte, 5 for "World", and one for the null byte that implicitly ends the string constant. Since fwrite is given the full size of the array (12), it writes all of those bytes. Indeed, looking at the file contents, we see each of those bytes. As a side note, in each of the fwrite calls, I've hardcoded the size of the array for the third parameter instead of using a more dynamic expression such as sizeof(a1)/sizeof(a1[0]) to make it more clear exactly how many bytes are being written in each case.
https://codedump.io/share/wCq99xuZwZP5/1/how-can-a-file-contain-null-bytes
CC-MAIN-2017-26
en
refinedweb
This notebook is a mental note about issues coming up when trying to estimate a panel with one and two-ways fixed effects. Any comments, suggestions or ideas are more than welcome. You can access the notebook in two flavours: Last, the notebook relies on two functions I provide in a separate Python file in order not to clutter and make this text more readable. You get the additional file when you pull the gist, but you can also check it online here. All the code examples are written in Python and rely on the following dependencies that you will need to reproduce the code in your machine: import panel_ols import pandas as pd print "Pandas: ", pd.__version__ import pysal as ps print "PySAL: ", ps.version import numpy as np print "Numpy: ", np.__version__ seed = np.random.seed(1234) Pandas: 0.12.0 PySAL: 1.7.0dev Numpy: 1.7.1 The idea is that we have a panel with two dimensions (you can think of individuals $i$ over time $t$, but there can be other dimensions too). In formal notation, we begin with the following baseline model:$$ y_{it} = \alpha + X_{it} \beta + \epsilon_{it} $$ Assuming the usual stuff about the good behaviour of $\epsilon_{it}$$, this can be estimated by OLS. If we want to control for time-invariant characteristics of individuals, we can include what is called a fixed-effect:$$ y_{it} = X_{it} \beta + \mu_i + \epsilon_{it} $$ where $\mu_i$ absorbs every individual effect that does not vary over time. If we want to estimate this model, we can simply include a dummy of each $i$ and run OLS. The problem is that if the number of individuals is very large, one quickly runs out of degrees of freedom and increases multicollinearity. An equivalent way to work around this is suggested by Baltagi on p. 34 (of Third edition at least). We can demean $y_{it} and $X_{it}$ as follows:$$ y_{it}* = y_{it} - \bar{y}_{i.} $$ where $\bar{y}_{i.}$ is the average of values for each individual. Running a straight OLS (without intercept) on the transformed variables results in the same $\beta$ estimates as we would by using dummy variables. If we also want to account for the unboserved individual-invariant heterogeneity, we can also include a time effect, converting the model in the so called two-way fixed-effects modes:$$ y_{it} = X_{it} \beta + \mu_i + \nu_t + \epsilon_{it} $$ In theory, you could also estimate this using dummy variables, but the problems that arise in the one-way model are even more acute. Fortunately, Baltagi proposes another transformation that gets around this:$$ y_{it}* = y_{it} - \bar{y}_{i.} - \bar{y}_{.t} + \bar{y}_{..} $$ If you apply this transformation to both $y$ and $X$, you can run a straight OLS (without intercept again) and obtain the $\beta$ estimates of interest. n = 1000 d1 = 100 d2 = 10 seed = np.random.seed(1234) x = np.random.random((n, 3)) fe1 = np.random.random_integers(0, d1, n) fe1_d = pd.get_dummies(fe1, 'fe1') fe2 = np.random.random_integers(0, d2, n) fe2_d = pd.get_dummies(fe2, 'fe2') e = np.random.normal(0, 1, (n, 1)) y = np.dot(x, np.array([[1., 1., 1.]]).T) \ + fe1_d.ix[:, :-1].values.sum(axis=1)[:, None] \ + fe2_d.values.sum(axis=1)[:, None] \ + e We can estimate the model including the dummies for the first effect: xone = np.hstack((x, fe1_d.values)) m1_dummy = ps.spreg.BaseOLS(y, xone) Or use the transformation, built into the method one_way_fe: m1_demean = panel_ols.one_way_fe(y, x, fe1) We can now compare the estimates of $\beta$: np.hstack((m1_dummy.betas[:3], m1_demean.betas)) array([[ 1.05322727, 1.05322727], [ 0.94063773, 0.94063773], [ 1.08095942, 1.08095942]]) If you check, the difference between the two is negligible: m1_dummy.betas[:3] - m1_demean.betas array([[ -4.15223411e-14], [ 1.57651669e-14], [ -1.82076576e-14]]) Also, you can see how the multicollinearity issue starts to creep up although, in this case, it is not unacceptable: ci = ps.spreg.diagnostics.condition_index print "Dummy: %.4f | Demean: %.4f"%(ci(m1_dummy), ci(m1_demean)) Dummy: 7.0236 | Demean: 1.0713 /home/dani/code/pysal_darribas/pysal/spreg/diagnostics.py:619: ComplexWarning: Casting complex values to real discards the imaginary part ci_result = sqrt(max_eigval/min_eigval) xtwo = np.hstack((xone, fe2_d.values[:, 1:])) m2_dummies = ps.spreg.BaseOLS(y, xtwo) We can estimate the fully transformed model: m2_demean = panel_ols.two_way_fe(y, x, fe1, fe2) Or you can have a middle way using dummies for the effect with less categories ( fe2 in this case) and the demeaner for the other one: m2_mix = panel_ols.one_way_fe(y, xone[:, :-1], fe2) We can now check the coefficients of the three methods: pd.DataFrame({'Dummies': m2_dummies.betas[:3].flatten(), \ 'Mix': m2_mix.betas[:3].flatten(), \ 'Demean': m2_demean.betas.flatten()}) And their multicollinearity: pd.Series({'Dummies': ci(m2_dummies), \ 'Mix': ci(m2_mix), \ 'Demean': ci(m2_demean)}) Demean 1.073158 Dummies 11.582533 Mix 11.704122 dtype: float64 As you can see, estimates for Dummies and Mix are exactly the same (at least at the sixth decimal), while those for the Demean are slightly different. This is probably related to precission issues, but if you have any suggestion as to why this happens, please drop me a line, I'll be happy to learn! Update It turns out that the two-way fixed effects differ in the previous cells because the way I have randomly set up the indices for both dimensions. Demeaning a-la Baltagi only works in a true panel setting in which you only have one occurrence of a pair of indices $it$. When you indeed have this case, the numbers match. n = 1000 d1 = 10 d2 = 100 seed = np.random.seed(1234) x = np.random.random((n, 3)) # Balanced panel d2 = int(n * 1. / d1) fe1 = np.arange(d1) fe2 = np.arange(d2) fe = np.array([(i, j) for i in fe1 for j in fe2]) fe1 = fe[:, 0] fe2 = fe[:, 1] # fe1_d = pd.get_dummies(fe1, 'fe1') fe2_d = pd.get_dummies(fe2, 'fe2') e = np.random.normal(0, 1, (n, 1)) y = np.dot(x, np.array([[1., 1., 1.]]).T) \ + fe1_d.ix[:, :-1].values.sum(axis=1)[:, None] \ + e #+ fe2_d.values.sum(axis=1)[:, None] \ # One-way m = panel_ols.one_way_fe(y, x, fe1) xone = np.hstack((x, fe1_d.values)) md = ps.spreg.BaseOLS(y, xone) print "De-meaned | Dummy" for i in range(3): print np.round(m.betas[i][0], 9), " | ", \ np.round(md.betas[i][0], 9) print 'Condition index' print ci(m), " | ", ci(md) # Two-way m = panel_ols.two_way_fe(y, x, fe1, fe2) malt = panel_ols.one_way_fe(y, xone[:, :-1], fe2) xtwo = np.hstack((xone, fe2_d.values[:, 1:])) md = ps.spreg.BaseOLS(y, xtwo) print "\nDe-meaned | 1 demeaned-1 dummy | Dummy" for i in range(3): print np.round(m.betas[i][0], 9), " | ", \ np.round(malt.betas[i][0], 9), " | ", \ np.round(md.betas[i][0], 9) print 'Condition index' print ci(m), " | ",ci(malt), " | ", ci(md) De-meaned | Dummy 1.001466538 | 1.001466538 0.823691091 | 0.823691091 0.988729449 | 0.988729449 Condition index 1.09144305033 | 6.66571288935 De-meaned | 1 demeaned-1 dummy | Dummy 0.971197304 | 0.971197304 | 0.971197304 0.867112279 | 0.867112279 | 0.867112279 0.88178915 | 0.88178915 | 0.88178915 Condition index 1.06881037371 | 3.32261011076 | 29.8077107922
http://nbviewer.jupyter.org/gist/darribas/7805381/panel_FE.ipynb
CC-MAIN-2017-26
en
refinedweb
Schema Validation¶ Some data types in Treeherder will have JSON Schema files in the form of YAML. You can use these files to validate your data prior to submission to be sure it is in the right format. You can find all our data schemas in the schemas folder. To validate your file against a yml file, you can use something like the following example code: import yaml import jsonschema schema = yaml.load(open("schemas/text-log-summary-artifact.yml")) jsonschema.validate(data, schema) This will give output telling you if your data element passes validation, and, if not, exactly where it is out of compliance.
http://treeherder.readthedocs.io/data_validation.html
CC-MAIN-2017-26
en
refinedweb
This action might not be possible to undo. Are you sure you want to continue? Python Programming PDF generated using the open source mwlib toolkit. See for more information. PDF generated at: Sun, 18 Jul 2010 13:13:10 UTC Contents Articles Learning Python Python Concepts Python Python Article Sources and Contributors Image Sources, Licenses and Contributors 161 163 Article Licenses License 164 dir(object) will return the names of the attributes of the specified object.1 Learning Python Python Programming/Overview Index Next: Getting Python Python is a high-level. just as automatically. However. 1 2 a. lists. For example.(a+b) print(b. The most unusual aspect of Python is that whitespace is significant. so that compilation need not happen again until and unless the source gets changed). they are quite helpful and are populated by the authors of many of the Python textbooks currently available on the market. Python also comes with a powerful standard library.. end=" ") 3 5 8 13 21 34 55 89 144 Another interesting aspect in Python is reflection and introspection. The locals() routine returns a dictionary in which the names in the local namespace are the keys and their values are the objects to which the names refer. It is an interpreted programming language that is automatically compiled into bytecode before execution (the bytecode is then normally saved to disk.b = 0. this provides a useful environment for exploration and prototyping. indentation is used to indicate where blocks begin and end.. While they discourage doing homework for you. a number of built-in functions.... to display the beginning values in the Fibonacci series: >>> >>> 1 >>> .g. . loop constructs that can iterate over items in a collection instead of being limited to a simple range of integer values. Python provides a powerful assortment of built-in types (e. dictionaries and strings). It is named after Monty Python's Flying Circus comedy program.b = b.1 print(b) while b < 100: a. Index Next: Getting Python . the following Python code can be interactively typed at an interpreter prompt.. structured. . and created by Guido Van Rossum. mostly statements. instead of block delimiters (braces → "{}" in the C family of languages). For example. Combined with the interactive interpreter.. It is also a dynamically typed language that includes (but does not require one to use) object oriented features and constructs. The dir() function returns the list of the names of objects in the current scope. The mailing lists and news groups [2] like the tutor list [3] actively support and help new python programmers. which includes hundreds of modules to provide routines for a wide variety of services including regular expressions and TCP/IP sessions. open-source programming language that can be used for a wide variety of programming tasks. Python is used and supported by a large Python Community [1] that exists on the Internet. and a few constructs. as well as complex and intricate applications. It is good for simple quick-and-dirty scripts. If you prefer having a temporary environment. In order to run Python from the command line. Download it. If it is not already installed or if the version you are using is obsolete.4 Tiger). change the "26" for the version of Python you have (26 is 2. PyScripter[5]. The advanced tab will contain the button labelled Environment Variables. eric[4].6. you could use an Integrated Development Environment (IDE) for Python like DrPython[3]. org/ community/ lists. the current version of Python 2. python. where you can append the newly created folder to the search path. you will need to have the python directory in your PATH. or Python's own IDLE (which ships with every version of Python since 2. html [2] http:/ / www. python. but if you want the more recent version head to Python Download Page [6] follow the instruction on the page and in the installers. read the instructions and get it installed. you can create a new command prompt short-cut that automatically executes the following statement: PATH %PATH%.1). python.3). However.x. it can be selected from the list of packages. html [3] http:/ / mail. you will need to obtain and install Python using the methods below: Installing Python in Windows Go to the Python Homepage [1] or the ActiveState website [2] and get the proper version for your platform. . the Cygwin installer for Windows does not include Python in the downloads. The PATH variable can be modified from the Window's System control panel. Alternatively. Installing Python on Mac Users on Apple Mac OS X will find that it already ships with Python 2.) Cygwin By default.3 (OS X 10. As a bonus you will also install the Python IDE. org/ mailman/ listinfo/ tutor Python Programming/Getting Python Previous: Overview Index Next: Setting it up In order to program in Python you need the Python interpreter.c:\python26 If you downloaded a different version (such as Python 3. org/ community/ index.Python Programming/Overview 2 References [1] http:/ / www. Other versions can be built from source from the Arch User Repository. As root (or using sudo if you've installed and configured it). and do not have pre-compiled binaries. only it sometimes is not the latest version. Gentoo GNU/Linux Gentoo is an example of a distribution that installs Python by default . just open a terminal and type at the prompt: $ sudo apt-get update # This will update the software repository $ sudo apt-get install python # This one will actually install python Arch GNU/Linux Arch does not install python by default. com http:/ / drpython. org/ download/ mac . In some cases. In these cases. org/ download/ http:/ / activestate. python. Once the download is complete.the package system Portage depends on Python. de/ eric/ index. Source code installations Some platforms do not have a version of Python installed. while other distributions require downloading the source code and using the compilation scripts. you will need to download the source code from the official site [1]. com/ Products. To build Python. If you would like to update it. the distribution CD will contain the python package for installation. sourceforge.Python Programming/Getting Python 3 Installing Python on Unix environments Python is available as a package for some Linux distributions. Ubuntu GNU/Linux Users of Ubuntu 6. Previous: Overview Index Next: Setting it up References [1] [2] [3] [4] [5] [6] http:/ / (Dapper Drake) and earlier will notice that Python comes installed by default. type: $ pacman -Sy python This will be update package databases and install python. simply run the configure script (requires the Bash shell) and compile using make. but is easily available for installation through the package manager to pacman. you will need to unpack the compressed archive into a folder. aspx?ProductID=4 http:/ / www. die-offenbachs. html http:/ / mmm-experts. python. net/ http:/ / www. Python Mode for Emacs There is also a python mode for Emacs which provides features such as running pieces of code. You can download the mode at. known as the "Cheese Shop. • If you get an error stating a requirement for the plugin "org. The install just requires you to unpack the downloaded Eclipse install file onto your system. Download and install it. found in the tool bar under "Help" -> "install new Software". The only requirement is Eclipse and the Eclipse PyDEV Plug-in. expand the PyDEV tree. and deselect the optional mylyn components.eclipse. Download it. Eclipse will now check for any updates to PyDEV when it searches for updates. • Or install PyDEV manually. telecommunity. and changing the tab level for blocks. There are also updates on the site but.sourceforge.mylyn". com/ DevCenter/ EasyInstall . You can install PyDEV Plug-in two ways: • Suggested: Use Eclipse's update manager. and select PyDEV and let Eclipse do the rest.net/python-mode Installing new modules Although many applications and modules have searchable webpages. python. and install it by unpacking it into the Eclipse base folder. just look for the basic program. add http:/ /pydev.net and get the latest PyDEV Plug-in version.org/updates/in "work with" clik add.Python Programming/Setting it up 4 Python Programming/Setting it up Previous: Getting Python Index Next: Interactive mode Installing Python PyDEV Plug-in for Eclipse IDE You can use the Eclipse IDE as your Python IDE. there is a central repository packages for installation. org/ downloads/ and get the proper Eclipse IDE version for your OS platform. by going to. org/ pypi [2] http:/ / peak. eclipse." [1] for searching See Also • EasyInstall [2] Previous: Getting Python Index Next: Interactive mode References [1] http:/ / www. Go to http:/ / www. you might be surprised by the result: >>> if 1: .. If you ever feel the need to play with new Python statements. make sure your path is set correctly.py files are run in the python interpreter. This is a good way to play around and try variations on syntax. simply type "python" without any arguments. Interactive mode is a command line shell which gives immediate feedback for each statement. See Getting Python.0b3 (r30b3:66303. (If Python doesn't run. A sample interactive session: >>> 5 5 >>> print (5*7) 35 >>> "hello" * 4 'hellohellohellohello' >>> "hello". 14:01:02) [MSC v. the following is a valid Python script: if 1: print("True") print("Done") If you try to enter this as written in the interactive environment. Python will respond with 2.. Python should print something like this: $ python Python 3.Python Programming/Interactive mode 5 Python Programming/Interactive mode Previous: Setting it up Index Next: Self Help Python has two basic modes: The normal "mode" is the mode where the scripted and finished . To get into interactive mode. line 3 print("Done") ^ SyntaxError: invalid syntax . In interactive mode what you type is immediately run. you need to be careful in the interactive environment to avoid any confusion..__class__ <type 'str'> However. "copyright".1500 32 bit (Intel)] on win32 Type "help". print("Done") File "<stdin>". For example. the fed program is evaluated both in part and in whole. print("True") .. while running previously fed statements in active memory. "credits" or "license" for more information. As new lines are fed into the interpreter.) The >>> is Python's way of telling you that you are in interactive mode. Sep >>> 8 2008. Try typing 1+1 in. go into interactive mode and try them out. Interactive mode allows you to test out and see what Python will do. "if") statement.. you can use the -i flag to start an interactive session. you should have entered the statements as though they were written: if 1: print("True") print("Done") Which would have resulted in the following: >>> if 1: .Python Programming/Interactive mode What the interpreter is saying is that the indentation of the second print was unexpected.e. python -i hello. print("True") . What you should have entered was a blank line to end the first (i... This can be very useful for debugging and prototyping.py Previous: Setting it up Index Next: Self Help . For example. True >>> print("Done") Done >>> 6 Interactive mode Instead of Python exiting when the program is finished... before you started writing the next print statement. Help parameter You can obtain information on a specific command without entering interactive help.org/tutorial/". "Welcome to Python 2. such as help("object"). type "modules".Python Programming/Self Help 7 Python Programming/Self Help Previous: Interactive mode Index Next: Creating Python programs This book is useful for learning python. keywords. you can obtain help on a given topic simply by adding a string in quotes. keywords. or topics. For example. or topics. You can access the different portions of help simply by typing in modules. Previous: Interactive mode Index Next: Creating Python programs . you should definitely check out the tutorial on the Internet at http:/ / docs. but indeed there might be topics that the book does not cover. Each module also comes with a one-line summary of what it does."keywords". Navigating help When you enter the help system through the help() call within the interactive session. You may also obtain help on a given object as well. That's where the interactive help() comes to play. or perhaps inspecting an unknown object's functions. To get a list of available modules. type "modules spam". You can exit the help system by typing "quit" or by entering a blank line to return to the interpreter. you are presented with a quick introduction to the help system.6! This is the online help utility. or perhaps you know there is a function that you have to call inside an object but you don't know its name. If this is your first time using Python. You might want to search for modules in the standard library. or "topics". by passing it as a parameter to the help function. Typing in the name of one of these will print the help page associated with the item in question. python. to list the modules whose summaries contain a given word such as "spam". make sure your PATH contains the python directory. and hit Enter. select "Run. print ends with a newline character.py">^ . you should run python3 hello.". and type in cmd. Save your hello.py program in that folder.py to run your program! <span class="citation wikicite" id="endnote_If you have both python version 2. and hit Enter..Python Programming/Creating Python programs 8 Python Programming/Creating Python programs Previous: Self Help Index Next: Variables and Strings Welcome to Python! This tutorial will show you how to start writing programs. World!" program.0 installed(Very possible if you are using Ubuntu. • In the Start menu. • Type cd \pythonpractice to change directory to your pythonpractice folder. See Getting Python. etc). however.6.py containing just this line (you can copy-paste if you want): print("Hello. • Type python hello. Mac • Create a folder on your computer to use for your Python programs. • Type python hello. Music. which simply moves the cursor to the next line. World!" and then quits.py program into this folder. go into the Utilities folder. Now that you've written your first program.1 and version 3. world!") This program uses the print function. such as C:\pythonpractice. Windows • Create a folder on your computer to use for your Python programs. Movies. World! The first program that every programmer writes is called the "Hello. Python programs are nothing more than text files. Hello.. and they may be edited with a standard text editor program. and save your hello. • Open the Applications folder. and ran sudo apt-get python3 to have python3 installed). Let's write "Hello. • Type cd pythonpractice to change directory to your pythonpractice folder. This program simply outputs the phrase "Hello. It is easier to use a text editor that includes Python syntax highlighting. A good suggestion would be to name it pythonpractice and place it in your Home folder (the one that contains folders for Documents. This will cause the Windows terminal to open. and open the Terminal program. which simply outputs its parameters to the terminal. World!" in Python! Open up your text editor and create a new file called hello.py to run your program! If it didn't work. let's run it in Python! This process differs slightly depending on your operating system.[1] What text editor you use will probably depend on your operating system: any text editor can create Python programs. Pictures. world! Congratulations! You're well on your way to becoming a Python programmer. • Type cd ~/pythonpractice to change directory to your pythonpractice folder. • Open up the terminal program. • Type python hello. it asks. open the Accessories folder. and hit Enter. open the Applications folder. and select Terminal." to open Konsole. The program should still only print out on one line. and save your hello. Solutions Notes [1] Sometimes. open the main menu and select "Run Command. Previous: Self Help Index Next: Variables and Strings .py program in that folder. 2.Python Programming/Creating Python programs 9 Linux • Create a folder on your computer to use for your Python programs. In KDE. Python programs are distributed in compiled form.py program to say hello to a historical political leader (or to Ada Lovelace). Re-write the original program to use two print statements: one for "Hello" and one for "world". open the main menu. We won't have to worry about that for quite a while. Modify the hello. 3.. "How did you get here?". Exercises 1. In GNOME.py to run your program! Result The program should print: Hello.. Change the program so that after the greeting. such as ~/pythonpractice. A concise program can make short work of this task. 5.0 >>> print(0.[1] [2] .2 pounds in a kilogram.x. mass_stone.0/2. For Python 3. "stone.2 and later modulo negation absolute value exponent square root Operation Name a%b -a abs(a) a**b math. For example: >>> print(0. let's write a program that might actually be useful! Let's say you want to find out how much you weigh in stone. 5/2=2) .2 / 14 print("You weigh". the following formula should do the trick: So. Since a stone is 14 pounds.5).6//0.0 For the Python 2.g. let's turn this formula into a program! mass_kg = int(raw_input("What is your mass in kilograms?" )) mass_stone = mass_kg * 2.Available in Python 2.") Run this program and get your weight in stone! Notice that applying the formula was as simple as putting in a few mathematical statements: mass_stone = mass_kg * 2.g. / does "true division" for all types.2 / 14 Mathematical Operators Here are some commonly used mathematical operators Syntax a+b a-b a*b a/b a//b Math addition subtraction multiplication division (see note below) floor division (e. and there are about 2.g.6/0.2) 2.sqrt(a) Beware that due to the limitations of floating point arithmetic. 5/2=2) but "true division" for floats and complex (e.2) 3.x series / does "floor division" for integers and longs (e.0=2. rounding errors can cause unexpected results.Python Programming/Basic Math 10 Python Programming/Basic Math Previous: Variables and Strings Index Next: Decision Control Now that we know how to work with numbers and strings. Python Programming/Basic Math 11 Order of.) Name Syntax Description PEMDAS Mnemonic Please Parentheses ( ... ) Before operating on anything else, Python must evaluate all parentheticals starting at the innermost level. (This includes functions.) As an exponent is simply short multiplication or division, it should be evaluated before them. Exponents ** Excuse Multiplication and Division Addition and Subtraction * / // % Again, multiplication is rapid addition and must, therefore, happen first. My Dear +- Aunt Sally Formatting output print statement prints numbers to 10 significant figures. But what if you only want one or two? We can use significant figures..") Python Programming/Basic Math 12 Exercises 1. Ask the user to specify the number of sides on a polygon and find the number of diagonals [3] within the polygon. 2. Take the lengths of two sides to a triangle from the user and apply the Pythagorean Theorem to find the third. Notes [1] What's New in Python 2.2 (http:/ / www. python. org/ doc/ 2. 2. 3/ whatsnew/ node7. html) [2] PEP 238 -- Changing the Division Operator (http:/ / www. python. org/ dev/ peps/ pep-0238/ ) [3] http:/ / www. mathopenref. com/ polygondiagonal. html Previous: Variables and Strings Index Next: Decision Control Python Programming/Decision Control Previous: Sequences Index Next: Conditional Statements Python, Here is a little example of boolean expressions (you don't have to type it in): a = 6 b = 7 c = 42 print (1, print (2, print (3, print (4, print (5, print (6, print (7, print (8, print (9, a == 6) a == 7) a == 6 and b == 7) a == 7 and b == 7) not a == 7 and b == 7) a == 7 or b == 7) a == 7 or b == 6) not (a == 7 and b == 6)) not a == 7 and b == 6) With the output being: 1 2 3 4 True False True False Python Programming/Decision Control 5 6 7 8 9 True True False True False 13: expression true and true true and false false and true false and false result true false false false: expression result not true not false false true: The first part is true so the second part could be either false or true. Here is an example of using a boolean expression: list = ["Life". This occurred since the parentheses forced the not to apply to the whole expression instead of just the a == 7 portion."Jill"] # Make a copy of the list. copy = list[:] # Sort the copy copy.prev) See the Lists chapter to explain what [:] means on the first line. not (a == 7 and b == 6)) and print (9. Here is the output: First Match: Jill This program works by continuing to check for match while count < len(copy) and copy[count]. print (8. This works since or is true if at least one half of the expression is true."Life". The next two lines:". If you look at the table for and notice that the third entry is "false and won't check". When either count is greater than the last index of copy or a match has been found the and is no longer true so the loop exits."Jill". not a == 7 and b == 6)."The Universe". If count >= len(copy) (in other words count < len(copy) is false) then . The other 'trick' of and is used in this example. but the whole expression is still true. Notice that the parentheses changed the expression from false to true. show that parentheses can be used to group expressions and force one part to be evaluated first.Python Programming/Decision Control 14 expression true or true true or false false or true result true true true false or false false Note that if the first expression is true Python doesn't check the second expression since it knows the whole expression is true."Jack". The if simply checks to make sure that the while exited because a match was found."Everything". # It then checks them to make sure that the user is allowed in. (If you don't believe me remove the matches `Jill' and `Life'. # real password code should never be implemented this way. Exercises. check that it still works and then reverse the order of count < len(copy) and copy[count] != prev to copy[count] != prev and count < len(copy). but they only get 3 chances to do so until the program quits. Solutions Previous: Sequences Index Next: Conditional Statements . 15 Examples password1.Python Programming/Decision Control copy[count] is never looked at. This is because Python knows that if the first is false then they both can't be true. This is known as a short circuit and is useful if the second half of the and will cause an error if something is wrong. Write a program that has a user guess your name. I used the first expression ( count < len(copy)) to check and see if count was a valid index for copy.) Boolean expressions can be used when you need to check two or more different things at once.py ## This programs asks a user for a name and a password. # Note that this is a simple and insecure example. This 2nd block of statements is run if the expression is false.a short program to compute the absolute value of a number: n = raw_input("Integer? ")#Pick an integer. we continue our drive. if raw_input is not supported by your OS.-n". Think of a traffic light.Python Programming/Conditional Statements 16 Python Programming/Conditional Statements Previous: Decision Control Index Next: Loops Decisions A Decision is when a program has more than one choice of actions depending on a variable's value. Next it reads the line "if n < 0:".n. you can define n yourself) if n < 0: print ("The absolute value of". Expressions can be tested several different ways. use input() n = int(n)#Defines n as the integer you chose."is". Here is a table of all of them: . More formally = raw_input("Integer? ")". Python has a decision statement to help us when our application needs to make such decision for the user.n. If statement Here is a warm-up exercise .n. Luckily. And remember. we proceed to reduce our speed. and when it is red. When we see the light turn yellow. Otherwise python runs the line "print "The absolute value of". we stop. If n is less than zero Python runs the line "print "The absolute value of"."is". When it is green. An if statement is followed by an indented block of statements that are run when the expression is true."is". Python looks at whether the expression n < 0 is true or false.n.-n) else: print ("The absolute value of". These are logical decisions that depend on the value of the traffic light.n". (Alternatively."is". After the if statement is an optional else statement and another indented block of statements. elif allows multiple tests to be done in a single if statement.py #Plays the guessing game higher or lower # (originally written by Josh Cogliati.5) 7: (a. but that will have to # wait till a later chapter. execute the block of code following the elif statement. modify it to be random . It stands for "else if.7) ("Neither test was true") If Examples High_low. improved by Quique) #This should actually be something that is semi random like the # last digits of the time or something else." which means that if the original if statement is false and the elif statement is true. Here's an example: a = 0 while a < 10: a = a + 1 if a > 5: print elif a <= print else: print and the output: 1 <= 7 2 <= 7 3 <= 7 4 <= 7 5 <= 7 6 > 5 7 > 5 8 > 5 9 > 5 10 > 5 Notice how the elif a <= 7 is only tested when the if statement fails to be true. (Extra Credit.Python Programming/Conditional Statements 17 operator < <= > >= function less than less than or equal to greater than greater than or equal to equal not equal == != Another feature of the if command is the elif statement."<=".">". (a. "is very strange.") elif number % 2 == 1: print (number. 18 .Python Programming/Conditional Statements # after the Modules chapter) #This is for demonstration purposes only.") Sample runs."is even."is odd. #Prints if it is even or odd number = raw_input("Tell me a number: ") number = float(number) if number % 2 == 0: print (number.") else: print (number. # It is not written to handle invalid input like a full program would.py #Asks for a number. number = 78 guess = 0 while guess != number : guess = raw_input("Guess an integer: ") guess = int(guess) if guess > number : print ("Too high") elif guess < number : print ("Too low") else: print ("Just right" ) Sample run: Guess an integer:100 Too high Guess an integer:50 Too low Guess an integer:75 Too low Guess an integer:87 Too high Guess an integer:81 Too high Guess an integer:78 Just right even. print ("Enter 0 to exit the loop") while number != 0: number = raw_input("Enter a number: ") number = float(number) if number != 0: count = count + 1 sum = sum + number print "The average was:".0 Enter 0 to exit the loop Enter a number:1 Enter a number:4 Enter a number:3 Enter a number:0 The average was: 2.Python Programming/Conditional Statements Tell me a number: 3 3 is odd.66666666667 average2. average1.0 # 19 # set this to something that will not exit the while loop immediately. Tell me a number: 2 2 is even. count = 0 sum = 0. #Prints the average value.0 number = 1.sum/count Sample runs Enter 0 to exit the loop Enter a number:3 Enter a number:5 Enter a number:0 The average was: 4.14159 is very strange.py #keeps asking for numbers until 0 is entered. #Prints the average value. .py #keeps asking for numbers until count have been entered. Tell me a number: 3.14159 3. How many numbers would you like to sum:3 Number 1 Enter a number:1 Number 2 Enter a number:4 Number 3 Enter a number:3 The average was: 2.Python Programming/Conditional Statements sum = 0.0 print ("This program will take several numbers. Write a program that asks the user their name. 3. otherwise tell them "You have a nice name.current_count) number = input("Enter a number: ") sum = sum + number print "The average was:". 2." If they enter "John Cleese" or "Michael Palin". and terminate the program.") count = raw_input("How many numbers would you like to sum:") count = int(count) current_count = 0 while current_count < count: current_count = current_count + 1 print ("Number". Write a password guessing program to keep track of how many times the user has entered the password wrong. print You have successfully logged in. tell them how you feel about them . If the password is correct. How many numbers would you like to sum:2 Number 1 Enter a number:3 Number 2 Enter a number:5 The average was: 4. and terminate the program. Write a program that asks for two numbers. then average them. print You have been denied access. then average them.sum/count Sample runs This program will take several numbers.66666666667 20 If Exercises 1. If it is more than 3 times. then average them. print That is a big number and terminate the program.)." . If they enter your name. If the sum of the numbers is greater than 100.0 This program will take several numbers. say "That is a nice name. however you could replicate it by constructing a tuple of results and calling the test as the index of the tuple. To resolve this issue. often used to simplify conditionally accessing a value. // read from program input // a normal conditional assignment int res. and as a better practice. which can lead to unexpected results and slower executions if you're not careful. wrap whatever you put in the tuple in anonymous function calls (lambda notation) to prevent them from being evaluated until the desired branch is called: in = int(raw_input("Enter a number to get its absolute value:")) res = (lambda:in. and with a totally different syntax): in = int(raw_input("Enter a number to get its absolute value:")) res = -in if in<0 else in Switch A switch is a control statement present in most computer programming languages to minimize a bunch of If .Python Programming/Conditional Statements 21 Conditional Statements Many languages (like Java and PHP) have the concept of a one-line conditional (called The Ternary Operator). if(in < 0) res = -in. unlike a built in conditional statement.5 however. For many years Python did not have the same construct natively. x = 1 def hello(): print ("Hello") def bye(): print ("Bye") def hola(): print ("Hola is Spanish for Hello") . // this can be simplified to int res2 = (in < 0) ? -in: in. Sadly Python doesn't officially support this statement.lambda:-in)[in<0]() Since Python 2.elif statements. but with the clever use of an array or dictionary. For instance (in Java): int in= . else res = in. like so: in = int(raw_input("Enter a number to get its absolute value:")) res = (-in. we can recreate this Switch statement that depends on a value. there has been an equivalent operator to The Ternary Operator (though not called such. both the true and false branches are evaluated before returning.in)[in<0] It is important to note that. adios] # To call our switch statement. # Calls the hello function being our first element in our menu[x]() # Calls the bye function as is the second element on the array x = 1 This works because Python stores a reference of the function in the array at its particular index. we simply make reference to the array with a pair of parentheses # at the end to call the function menu[3]() # calls the adios function since is number 3 in our array. 'c': lambda x: x .bye. result = { 'a': lambda x: x * 5. Here the last line is equivalent to: if x==0: hello() elif x==1: bye() elif x==2: hola() else: adios() Another way Source [1] Another way is to use lambdas.hola. only that we added the function's name inside # and there are no quotes menu = [hello. Code pasted here without permissions.2 }[value](x) Previous: Decision Control Index Next: Loops . 'b': lambda x: x + 7. menu[0]() array.Python Programming/Conditional Statements 22 def adios(): print ("Adios is Spanish for Bye") # Notice that our switch statement is a regular variable. and by adding a pair of parentheses we are actually calling the function. g. if statements) also influence whether or not a certain statement will run. net/ 2004/ May/ 7/ switch/ Python Programming/Loops Previous: Conditional Statements Index Next: Sequences While loops This is our first control structure. As a side note.') while a != 0: print ('Current Sum: '.s) . In other words while a is less than ten the computer will run the tabbed in statements..Python Programming/Conditional Statements 23 References [1] http:/ / simonwillison. Control structures change the order that statements are executed or decide if a certain statement will be run. s) a = raw_input('Number? ') a = float(a) s += a print ('Total Sum = '. Here is another example of the use of while: a = 1 s = 0 print ('Enter Numbers to add to the sum. decision statements (e.') print ('Enter 0 to quit. Then it sees while a < 10: and so the computer checks to see if a < 10. The first time the computer sees this statement a is zero so it is less than 10. Here's the source for a program that uses the while control structure: a = 0 while a < 10 : a += 1 print (a) And here is the output: 1 2 3 4 5 6 7 8 9 10 So what does the program do? First it sees the line a = 0 and makes a zero. Ordinarily the computer starts with the first line and then goes down from there. 9 Number? 10. until the heat death of the universe or you stop it.25 Current Sum: 184 .85 Current Sum: 32.9 Number? 0 Total Sum = 42. it is possible to have programs that run forever. at the end of a print statement keeps it # from switching to a new line print (old_a. The way to stop it is to hit the Control (or Ctrl) button and `c' (the letter) at the same time.Python Programming/Loops Enter Numbers to add to the sum. The while statement only affects the lines that are tabbed in (a.k. Enter 0 to quit.a.00 Current Sum: 42.) 24 Examples Fibonacci. Current Sum: 0 Number? 200 Current Sum: 200 Number? -15. (Note: sometimes you will have to hit enter after the Control C.) print() Output: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 . I'm stuck in a loop. Now that we have while loops.") This program will output Help. I'm stuck in a loop. The != means does not equal so while a != 0 : means until a is zero run the tabbed in statements that are afterwards.s is only run at the end. This will kill the program.9 Notice how print 'Total Sum ='.75 Number? -151. An easy way to do this is to write a program like this: while 1 == 1: print ("Help. indented). py # Waits until a password has been entered. but the program code looks different.11) for count in onetoten: print (count) The output: 1 2 3 4 5 6 7 8 9 10 The output looks very familiar. without # the password Use control-C to break out 25 # This is another way of using loops: onetoten = range(1.finish). finish is one larger than the last number. Note that this program could have been done in a shorter way: for count in range(1. The first line uses the range function. The range function uses two arguments like this range(start.11): print (count) . start is the first number that is produced.Python Programming/Loops Password. ) So.6.21) [5. 7. -26. 18. (Notice how if you don't want print to go to the next line add a comma at the end of the statement (i.42. 17. 2. The above code acts exactly the same as: for a in range(0.8] sum = 0 for num in list: sum = sum + num . 6. -22.'and'. As for goes through each element in a list it puts each into variable. 20] >>> range(21. 4. 6. with 0 implied as the starting point. 8. The next line for count in onetoten: uses the for control structure. what is for good for? The first use is to go through all the elements of a list and do something with each of them. -24. The output is 0 1 2 3 4 5 6 7 8 9 The code would cycle through the for loop 10 times as expected. A for control structure looks like for variable in list:. 3. 9. 'the universe'. but starting with 0 instead of 1. 16. 10.e. -27. Here a quick way to add up all the elements: list = [2. -23.5) [] Another way to use the range() function in a for loop is to supply only one argument: for a in range(10): print a. -20) [-32. 13. -21] >>> range(5. 8. -30. 19. Here is another example to demonstrate: demolist = ['life'. That allows variable to be used in each successive time the for loop is run through. 5.10) [1. if you want to print something else on that line). -28.4.7. 12. list is gone through starting with the first element of the list and going to the last.Python Programming/Loops Here are some examples to show what happens with the range command: >>> range(1. 10): print a. 14. 9] >>> range(-32. 6. 11. 7.'everything'] for item in demolist: print ("The Current item is: %s" % item) The output is: The The The The The The The Current Current Current Current Current Current Current item item item item item item item is: is: is: is: is: is: is: life 42 the universe 6 and 7 everything 26 Notice how the for loop goes through and sets item to each element in the list. -29. -25. -31. 15. 8."\tprev:". 7. 8. 5.sort() l: [0.7.prev."\tl:".0.prev.7. 10] prev = l[0] prev: 0 del l[0] l: [1. 7. 1. 8. 7.l) l. 7.0. 10] l.sort()". 1.sort() prev = list[0] del list[0] for item in list: if prev == item: print ("Duplicate of ". 1. 7. 1.prev. 5. 4.10]"."\tprev:".item) prev = item print ("prev = item"." Found") print ("if prev == item:". 9. 9.0. 5.l) prev = l[0] print ("prev = l[0]". 7."\titem:". 9. 4." Found") prev = item and for good measure: Duplicate of 7 Found How does it work? Here is a special debugging version: l = [4."\tl:".10] print ("l = [4. 9.7. 7. 0. 9. 1."\titem:".item) with the output being: l = [4."\tl:".prev) del l[0] print ("del l[0]". 7. 8.prev. 9. 8.10] l: [4. 5. 7.Python Programming/Loops print "The sum is: %d" % sum with the output simply being: The sum is: 20 27 Or you could write a program to find out if there are any duplicates in a list like this program does: list = [4. 5.l) for item in l: if prev == item: print ("Duplicate of ".sort() print ("l. 8.7. 9."\t\tprev:".10] list. 5. 5. 8.0. 7. 1. . Each item of the list is checked to see if it is the same as the previous. Next the first element of the list is deleted so that the first item is not incorrectly thought to be a duplicate. . If it is a duplicate was found. Sure enough. Next a for loop is gone into. The value of prev is then changed so that the next time the for loop is run through prev is the previous item to the current. a easy way to go through all the elements in a list or to do something a certain number of times. and help debug the program. Next the program sorts the list. First the program starts with a old list. This is so that any duplicates get put next to each other.Python Programming/Loops Duplicate of 7 Found if prev == item: prev = item if prev == item: prev = item if prev == item: prev = item if prev == item: prev = item 28 prev: prev: prev: prev: prev: prev: prev: prev: 7 7 7 8 8 9 9 10 item: item: item: item: item: item: item: item: 7 7 8 8 9 9 10 10 Note: The reason there are so many print statements is because print statements can show the value of each variable at different times. the 7 is found to be a duplicate. The program then initializes a prev(ious) variable. or subscript operator. In other languages. lists. then print each prime number up to that number. world!"[1] "Hello. There are five kinds of sequences in Python: strings. the elements in arrays and sometimes the characters in strings may be accessed with the square brackets. Negative indexes are counted from the end of the string: >>> "Hello. This works in Python too: >>> 'H' >>> 'e' >>> 'l' >>> 'l' >>> 'o' "Hello. but these are the most commonly used types). Solutions Previous: Conditional Statements Index Next: Sequences Python Programming/Sequences Previous: Basic Math Index Next: Source Documentation and Comments Sequences allow you to store multiple values in an organized and efficient fashion. world!"[4] Indexes are numbered from 0 to n-1 where n is the number of items (or characters). world!"[-2] 'd' >>> "Hello. 6 _ 7 w 8 o r l d ! 9 10 11 12 The item which comes immediately after an index is the one selected by that index. but that was before you knew what a sequence is. lower than. world!"[-9] 'o' . 2. world!"[0] "Hello. After each guess.Python Programming/Loops 29 Exercises 1. Ask the user to input a number. or equal to your guess. the user must tell whether their number is higher than. Instruct the user to pick an arbitrary number from 1 to 100 and proceed to guess it correctly within seven tries. and they are positioned between the items: H 0 1 e 2 l 3 l 4 o 5 . and sets (actually there are more. Create a program to count by prime numbers. world!"[2] "Hello. tuples. dictionaries. world!"[3] "Hello. Strings We already covered strings. followed by the item's number in the list inside brackets. world!"[3:9] 'lo." and the result of slicing a string is often called a "substring. world!"[-13] 'H' >>> "Hello. which count backwards from the end of the list: >>> spam[-1] 42 . world!' As demonstrated above. items in a list can be accessed by indexes starting at 0.Python Programming/Sequences >>> "Hello. For example: spam = ["bacon". the colon : allows the square brackets to take as many as two numbers. 'eggs'. To access a specific item in a list. world!' >>> string[:-8] 'Hello' >>> string[:] 'Hello. For example. 30 Lists A list is just what it sounds like: a list of values." >>> "Hello. For example: >>> spam ['bacon'. if either number is omitted it is assumed to be the beginning or end of the sequence. world!" >>> string[:5] 'Hello' >>> string[-6:-1] 'world' >>> string[-9:] 'o. an empty list would be initialized like this: spam = [] The values of the list are separated by commas. world!"[-1] '!' But in Python. It may hold both the strings "eggs" and "bacon" as well as the number 42. Like characters in a string. A list is created using square brackets. For any sequence which only uses numeric indexes. organized in order. 42] Lists may contain objects of varying types. this will return the portion which is between the specified indexes. you refer to it by the name of the list. wo' >>> string = "Hello. This is known as "slicing. "eggs". 42] >>> spam[0] 'bacon' >>> spam[1] 'eggs' >>> spam[2] 42 You can also use negative numbers. 'and'.1). 'eggs'. 'eggs'.append(10) >>> spam ['bacon'. you must use the append() function. The following code would fail: >>> spam[4] = 10 IndexError: list assignment index out of range Instead. The items in a list can also be changed. 10] Note that you cannot manually insert an element by specifying the index outside of its range. 42] >>> spam[:-1] [42] It is also possible to add items to a list.) As with strings. 42. If you want to insert an item inside a list at a certain index. returning the number of items in the array: >>> len(spam) 3 Note that the len() function counts the number of item inside a list. 42] >>> spam ['bacon'. 42. 'eggs'. are impossible to modify.insert(1. 42] >>> spam[1] 'eggs' >>> spam[1] = "ketchup" >>> spam ['bacon'. just like the contents of an ordinary variable: >>> spam = ["bacon".Python Programming/Sequences >>> spam[-2] 'eggs' >>> spam[-3] 'bacon' The len() function also works on lists. 42] (Strings. There are many ways to do it. 10] You can also delete items from a list using the del statement: >>> spam ['bacon'. you may use the insert() method of list. 'and'. 10] 31 . 'and') >>> spam ['bacon'. "eggs". 42. 'eggs'. being immutable. for example: >>> spam. 'ketchup'. lists may be sliced: >>> spam[1:] ['eggs'. the easiest way is to use the append() method of list: >>> spam. so the last item in spam (42) has the index (len(spam) . ('us'. see Data Structure/Lists 32 Tuples Tuples are similar to lists. 42. For further explanation on tuple. For further explanation on list. "the universe" It is often necessary to use parentheses to differentiate between different tuples.Python Programming/Sequences >>> del spam[1] >>> spam ['bacon'. 10] >>> spam[0] 'bacon' >>> spam[1] 'eggs' >>> spam[2] 42 >>> spam[3] 10 As you can see. 3 on right foo. "us". "you". "the universe" # An error: 2 elements on left. ("us". you use commas:>> var = ("me". so there are no gaps in the numbering. the last of which is itself a tuple. 'eggs'. 'them') but: >>> var = ("me". such as when doing multiple assignments on the same line: foo. "the universe") Unnecessary parenthesis can be used without harm. bar = "rocks". or remove elements of a tuple. "you". (0. "them") both produce: >>> print var ('me'. the list re-orders itself. change. "them")) >>> print(var) ('me'. 'you'. 0. but nested parentheses denote nested tuples: >>> var = "me". 'you'. "us". Once you have set a tuple. 'us'. tuples work identically to lists. see Data Structure/Tuples . 40. Every element in a dictionary has two parts: a key. You could consider a list to be a special kind of dictionary. and a value.you can add. >>> mind = set([42. the elements in a dictionary are not bound to numbers. "python": "a programming language". 0. 'a string']) >>> mind = set([42. 42. 'the answer': 42. and they are mutable -. 40. change. 42. in which the key of every element is a number. 'the answer': 42. deletion. then a colon. However. Calling a key of a dictionary returns the value linked to that key. "the answer": 42} >>> definitions {'python': 'a programming language'. and remove elements from a dictionary. 'a string']) >>> mind. 'a string'. 42. 0]) >>> mind set([40. 'a string'. 'a string'. 0. and then its value.Python Programming/Sequences 33 Dictionaries Dictionaries are also like lists. 'guava': 'a tropical fruit'. 'new key': 'new value'} For further explanation on dictionary. >>> definitions["new key"] = "new value" >>> definitions {'python': 'a programming language'.add('hello') >>> mind set([40. For example: >>> definitions = {"guava": "a tropical fruit". 41. and fast membership testing. The reason for using set over other data types is that set is much faster for huge number of items than a list or tuple and sets provide fast data insertion. adding an element to a dictionary is much simpler: simply declare it as you would a variable. 41]) >>> mind set([40. (23. in numerical order. and each element is declared first by its key. 'a string'. Sets also support mathematical set operations such as testing for subsets and finding the union or intersection of two sets. the way a list is. Elements of a set are neither bound to a number (like list and tuple) nor to a key (like dictionary). 4). 4)]) >>> mind set([(23. 'hello']) . except that it is unordered and it does not allow duplicate values. see Data Structure/Dictionaries Sets Sets are just like list. 42. 'guava': 'a tropical fruit'} >>> definitions["the answer"] 42 >>> definitions["guava"] 'a tropical fruit' >>> len(definitions) 3 Also. Dictionaries are declared using curly braces. 'a string']) >>> mind = set([42. when an element is not found.defaultdict A dictionary that. 'hello'. an array may only contain homogeneous values. 'a string'. 34 Frozenset The relationship between frozenset and set is like the relationship between tuple and list. For further explanation on set. collections.deque A double ended queue. which can contain anything. Note that a list can also be used as queue in a single-threaded code. items you add into sets will end up in an indeterminable position. strings. Frozenset is an immutable version of set. allows fast manipulation on both sides of the queue. A set can only contain hashable.'everything']) >>> frozen frozenset({'universe'. lists. 40. An example: >>> frozen=frozenset(['life'. immutable data types. Integers. returns a default value instead of error. dictionaries. although these are less frequently used and they need to be imported from the standard library before used. the types of data that can be included in sets is restricted. heapq A priority queue. see Data Structure/Sets .Python Programming/Sequences Note that sets are unordered. and it may also change from time to time. and tuples are hashable. We will only brush on them here. collections.add('duplicate value') >>> mind. Unlike lists. Queue A thread-safe multi-producer. see below) are not. >>> mind. 42.add('duplicate value') >>> mind set([0. 'duplicate value']) Sets cannot contain a single value more than once. and other sets (except frozensets. multi-consumer queue for use with multi-threaded programs. 'life'.'universe'. array A typed-list. 'everything'}) Other data types Python also has other types of arrays. Comments There will always be a time in which you have to return to your code. you leave comments. The two mechanisms for doing this in Python are comments and documentation strings.array useful for heavy number crunching sorteddict like the name says.py # Display the knights that come after Scene 24 print("The Knights Who Say Ni!") # print("I will never see the light of day!") As you can see. . What one needs is a means to leave reminders to yourself as to what you were doing. numpy. We'll mention some of the more well known 3rd party types. looking at your own code after six months is almost as bad as looking at someone else's code. A comment is denoted by the hash character (#) and extends to the end of the line. Regardless. like the second print statement. a sorted dictionary more this list isn't comprehensive Notes Previous: Basic Math Index Next: Source Documentation and Comments Python Programming/Source Documentation and Comments Previous: Sequences Index Next: Modules and how to use them Documentation is the process of leaving information about your code. Perhaps it is to fix a bug.Python Programming/Sequences 35 3rd party data structure Some useful data types in Python don't come in the standard library. Some of these are very specialized on their use. For example: #!/usr/bin/env python # commentexample. For this purpose. you can also use comments to temporarily remove segments of your code. or to add a new feature. Comments are little snippets of text embedded inside your code that are ignored by the Python interpreter. the period at the end can be omitted. You could always write a separate text file with how to call the functions. Python has such a capability. Documentation strings (or docstrings) are used to create easily-accessible documentation. Fortunately.. class. • You should use two spaces after a sentence-ending period. They should start with a # and a single space. written by Guido van Rossum.. unless it is an identifier that begins with a lower case letter (never alter the case of identifiers!).""" class Knight: """ An example class. • Inline Comments • An inline comment is a comment on the same line as a statement. For example: #!/usr/bin/env python # docstringexample. or method? You could add comments before the function. Strunk and White applies. Always make a priority of keeping the comments up-to-date when the code changes! • Comments should be complete sentences. • Python coders from non-English speaking countries: please write your comments in English. Call spam to get bacon. • When writing English. You can add a docstring to a function.""" . so that is less than ideal. """ def spam(eggs="bacon"): """Prints the argument given. but that would mean that you would have to remember to update that file. this is useful: x = x + 1 # Compensate for border Documentation Strings But what if you just want to know how to use a function. unless you are 120% sure that the code will never be read by people who don't speak your language. If only there was a mechanism for being able to embed the documentation and get at it easily. or module by adding a string as the first indented statement. Don't do this: x = x + 1 # Increment x But sometimes. its first word should be capitalized. • Inline comments are unnecessary and in fact distracting if they state the obvious. Inline comments should be separated by at least two spaces from the statement. but comments are inside the code.Python Programming/Source Documentation and Comments 36 Comment Guidelines The following guidelines are from PEP 8 [1]. But you can't pull up comments from a C extension. • If a comment is short.py """Example of using documentation strings. and each sentence should end in a period. Block comments generally consist of one or more paragraphs built out of complete sentences. class. • General • Comments that contradict the code are worse than no comments. so you would have to pull up a text editor and view them that way. If a comment is a phrase or sentence. create a new python file. one could enter pydoc docstringexample to get documentation on that module. If we were in the directory where docstringexample.... since it'd mess up python's module importing.localtime() current_time = time. because it makes it easier to add more documentation spanning multiple lines.call it Modules can be called in a various number of ways.Python Programming/Source Documentation and Comments print(eggs) The convention is to use triple-quoted strings.localtime() print(current_time) # print the tuple # if the year is 2009 (first value in the current_time tuple) if current_time[0] == 2009: print('The year is 2009') # print the year if __name__ == '__main__': # if the function is the main function . For example. You can call it using: import time Then.py. For example. you can use the help function inside a Python shell with the object you want help on.py lives. python. main() # . you'll see why later): import time def main(): #define the variable 'current_time' as a tuple of time. a popular module is the time module. org/ dev/ peps/ pep-0008/ Python Programming/Modules and how to use them Previous: Source Documentation and Comments Index Next: Files Modules are libraries that can be called from other scripts. you can name it anything (except time..localtime() print(current_time) if current_time[0] == 2009: print('The year is 2009') . we could import the time module as t: import time as t # import the time module and call it 't' def main(): current_time = t. Previous: Sequences Index Next: Modules and how to use them 37 References [1] http:/ / www. To access the documentation. or you can use the pydoc command from your system's shell. it is unnecessary (and wrong) to call the module again: from time import localtime #1 def main(): current_time = localtime() #2 print(current_time) if current_time[0] == 2009: print 'The year is 2009' if __name__ == '__main__': main() it is possible to alias a name imported through from-import from time import localtime as lt def main(): current_time = lt() print(current_time) if current_time[0] == 2009: print('The year is 2009') if __name__ == '__main__': main() Previous: Source Documentation and Comments Index Next: Files . To do this. Note that a from-import would import the name directly into the global namespace. so when invoking the imported function.Python Programming/Modules and how to use them 38 if __name__ == '__main__': main() It is not necessary to import the whole module. you can do a from-import. if you only need a certain function or class. txt".seek(10) >>> f. Read one line at a time: for line in open("testit.close() >>> f <closed file '/proc/cpuinfo'.read() print(inputFileText) In this case the "r" parameter means the file will be opened in read-only mode. if one would want more random access to the file. This is illustrated in the following example: >>> f=open("/proc/cpuinfo".read(123) print(inputFileText) When opening a file. tell() shows that the current offset is at position 20.read(10) ': 0\nvendor' >>> f. one starts reading at the beginning of the file.Python Programming/Files 39 Python Programming/Files Previous: Modules and how to use them Index Next: Text File I/O Read entire file: inputFileText = open("testit.txt". now seek() is used to go back to position 10 (the same position where the second read was started) and ten bytes are read and printed again. it is possible to use seek() to change the current position in a file and tell() to get to know the current position in the file. Read certain amount of bytes from a file: inputFileText = open("testit.tell() 10L >>> f.read(10) ': 0\nvendor' >>> f. And when no more operations on a file are needed the close() function is used to close the file we opened. "r"). This example will output an additional newline between the individual lines of the file.tell() 20L >>> f. mode 'r' at 0xb7d79770> Here a file is opened. "r"): print line In this case readlines() will return an array containing the individual lines of the file as array entries.txt". this is because one is read from the file and print . "r"). twice ten bytes are read.read(10) 'processor\t' >>> f.tell() 0L >>> f."r") >>> f. Reading a single line can be done using the readline() function which returns the current line as a string. 40 Testing Files Determine whether path exists: import os os.txt".path.txt".isdir("/proc/cpuinfo") False >>> os. To get around this.exists('<path string>') When working on systems such as Microsoft Windows(tm).code. There is even a function os.24-21-generic' . or r: import os os.islink("/vmlinuz") True >>> os. Write to a file requires the second parameter of open() to be "w".path.path.path. a directory.Python Programming/Files introduces another newline.path." open("testit.isdir("/") True >>> os.write(outputFileText) Append to a file requires the second parameter of open() to be "a" (from append): outputFileText = "Here's some text to add to the existing file.realpath("/vmlinuz") '/boot/vmlinuz-2.path.realpath() which reveals the true destination of a symlink: >>> import os >>> os.exists('C:\\windows\\example\\path') A better way however is to use "raw". this will overwrite the existing contents of the file if it already exists when opening the file: outputFileText = "Here's some text to save in a file" open("testit.path.isfile("/") False >>> os.path.path.islink("/") False >>> os. a mount point or a symlink. where path.path.path. there are functions which let you know if the path is a file.isfile("/proc/cpuinfo") True >>> os. do the following: import os os.path. "w"). the directory separators will conflict with the path string.path.6.exists(r'C:\windows\example\path') But there are some other convenient functions in os.exists() only confirms whether or not path exists.ismount("/") True >>> os.write(outputFileText) Note that this does not add a line break between the existing file content and the string to be added. "a"). copy("original. use the shutil library."newlocation. to perform a recursive remove it is possible to use rmtree() import shutil shutil. import shutil shutil.move("originallocation."dir2") shutil.txt") To perform a recursive copy it is possible to use copytree().Python Programming/Files 41 Common File Operations To copy or move a file.copytree("dir1".txt") Previous: Modules and how to use them Index Next: Text Python Programming/Text Previous: Files Index Next: Errors Get the length of a string: len("Hello Wikibooks!") -> 16 Get ASCII character code. or get a character version of it: ord('h') -> 104 chr(65) -> 'A' Previous: Files Index Next: Errors .txt".remove("file.txt") shutil."copy.rmtree("dir1") To remove an individual file there exists the remove() function in the os module: import os os.txt". the output should look like this: Enter your age: 5 You must be 5 years old.Request(url) response = urllib2. Dealing with exceptions Unlike syntax errors.Python Programming/Errors 42 Python Programming/Errors Previous: Text Index Next: Namespace In python there are two types of errors. try: age = int(raw_input("Enter your age: ")) print "You must be {0} years old. Syntax errors are always fatal.com' try: req = urllib2.urlopen(req) the_page = response. An example would be trying to access the internet with python without an internet connection.e. import urllib2 url = '." Another way to handle an error is to except a specific error. exceptions are not always fatal. i. Consider the following code to display the HTML of the website 'goat. . When the execution of the program reaches the try statement it will attempt to perform the indented code following.format(age) except ValueError: print "Your age must be numeric. They arise when the Python parser is unable to understand a line of code.goat.read() print the_page except: print "We have a problem. Exceptions Exceptions arise when the python parser knows what to do with a piece of code but is unable to perform the action. if for some reason there is an error (the computer is not connected to the internet or something) the python interpreter will jump to the indented code below the 'except:' command.com'.". Syntax errors Syntax errors are the most basic type of error. the python interpreter knows what to do with that command but is unable to perform it. syntax errors and exceptions. Exceptions can be handled with the use of a try statement." If the user enters a numeric value as his/her age. there is no way to successfully execute a piece of code containing syntax errors. if the user enters a non-numeric value as his/her age.Python Programming/Errors However. Enter your age: 15 You must be 15 years old. and the code under the except clause is executed: Enter your age: five Your age must be a number.".. You can also use a try block with a while loop to validate input: valid = False while valid == False: try: age = int(raw_input("Enter your age: ")) valid = True # This statement will only execute if the above statement executes without error. Previous: Text Index Next: Namespace 43 . a ValueError is thrown when trying to execute the int() method on a non-numeric string. accelerating. Lets say you're writing a program where you need to keep track of multiple cars. Each car has different characteristics like mileage. We define its methods as we would a normal function: only one indent with 'self' as its first argument (we get to this later). Instead of writing code separately for each car we could create a class called 'Car' that will be the blueprint for each particular car. So our example car class may look like this: class Car: def brake(self): print("Brakes") def accelerate(self): print("Accelerating") . actions or events) and properties (values. the name we want. In python you define a class method (an action. or function) using the following structure: class <<name>>: def <<method>> (self [. color.Python Programming/Namespace 44 Python Programming/Namespace Previous: Errors Index Next: Object-oriented programming Previous: Errors Index Next: Object-oriented programming Python Programming/Object-oriented programming Previous: Namespace Index Next: User Interaction Object Oriented Programming OOP is a programming approach where objects are defined with methods (functions. <<optional arguments>>]): <<Function codes>> Let's take a detailed look. and top speed. but lucky for us they all can perform some common actions like braking. and turning. characteristics). We define our object using the 'class' keyword. event. more reusable code. and a colon. resulting in more readable. Constructing a Class Class is the name given to a generic description of an object. . For example: class Car: ._owner Notice the single underscore before the property name. now each car object can take advantage of the class methods and attributes. def set_owner(self.color) It is good programming practice to write functions to get (or retrieve) and set (or assign) properties that are not 'read-only'.. the set_owner function is called transparently. Example: car1 = Car() # car 1 is my instance for the first car car2 = Car() # And use the object methods like car1... but let's give them some properties to differentiate them.. so you don't need to write a brake and accelerate function for each car independently._owner = Owners_Name def get_owner(self): # This will retrieve the owner property return self. set_owner) When code such as mycar. Properties Right now all the cars look the same. However.Owners_Name): # This will set the owner property self.. previous methods . In python we create a new variable to create an instance of a class.owner = "John Smith" is used. you may also define the above example in a way that looks like a normal variable: class Car: . previous methods .Python Programming/Object-oriented programming 45 But how do I use it? Once you have created the class.. You would need to create a variable for each car. owner = property(get_owner.2.color = "Red" And retrieve its value like: print(car1. A property is just a variable that is specific to a given object. To assign a property we write it like: car1. you actually need to create an object for each instance of that class. Beginning from Python 2. this is a way of hiding variable names from users.brake() Using the parentheses ("calling" the class) tells Python that you want to create an instance and not just copy the class definition... brand = brand self. For example. model. model. In python you create a constructor by writing a function inside the method name __init__. It can even accept arguments. for example: class New_car(Car): def start_car(self): self."Corolla". When you extend a class you inherit all the parent methods and properties and can add new ones. To extend a class we supply the name of the parent class in parentheses after the new class name. e. year): # Sets all the properties self.start_car() car2.on = true This new class extends the parent class.2001) car2 = New_car("Toyota"."F-150".year = year def start_car(self): """ Start the cars engine """ print ("vroem vroem") if __name__ == "__main__": # Creates two instances of new_car. For instance.g.model = model self. we could create a new car object and set its brand. each with unique properties car1 = New_car("Ford". Previous: Namespace Index Next: User Interaction . but we are reluctant to change its code for fear that this might mess up programs that depend on its current version. we can add a start_car method to our car class. Special Class Methods A Constructor is a method that gets called whenever you create a new instance of a class. to set attribute values upon creating a new instance of the class.2007) car1. and year attributes on a single line.Python Programming/Object-oriented programming 46 Extending a Class Let's say we want to add more functions to our class.brand.start_car() For more information on classes go to the Class Section in this book. rather than expending an additional line for each attribute: class New_car(Car): def __init__(self. The solution is to 'extend' our class. These two functions have different purposes and both accept a string argument which is displayed on the terminal before accepting the user input. the first is input() and the second one is raw_input(). so we use AInput for Advance Input ''' This class will create a object with a simpler coding interface to retrieve console input''' def __init__(self. Console Windows (Command Line Interface) Python has two built in functions to retrieve users input on a console. class ainput: # We can't use input as it is a existent function name. this second function fits more of our current needs. However. This means that the user response must be python coded . There are two ways to retrieve user input: the first is using the console window (Command Line Interface) and the second is using the Graphical User Interface (GUI). print name If the information entered by the user needs to be numeric to perform some calculation the return value most be converted using the float() or int() conversion function. # Retrieve user age age = int(raw_input("Please enter your age:")) print age As you may expect coding all the input for a big application and all the validation will increase the file size. req=0): ''' This will display the prompt and retrieve the user input. there are times where user input is really important.Python Programming/User Interaction 47 Python Programming/User Interaction Previous: Object-oriented programming Index Next: Databases Scripts don't normally take user input since they are usually designed to perform small useful tasks.ask(msg) def ask(self.strings must include quotes or double quotes. To make steps simpler we can create an object (using a Class) that handles retrieving the data and validating. While the raw_input() function expects any type of input and returns a python string.''' if req == 0: . and return the result to the application. the input entered by the user will be evaluated.data = "" # Initialize a empty data variable if not msg == "": self. Once this function is called.msg=""): ''' This will create a instance of ainput object''' self. unless you're planning to be the only user of the application. The input() function expects a python instruction as the user input.msg. This can make it a security risk in some cases. # Ask user for his name and stores name = raw_input("Please enter your name:") # Display the name entered by the user. req) def getString(self): ''' Returns the user input as String''' return self.data = raw_input(msg) # Save the user input to a local object variable else: self. Better Validation needed if req == 1 and self. userInteraction. retrieving and validating user input is a breeze.ask(msg.msg=""): ''' This will create a instance of ainput object''' self. For this example we are using a single line to display the call and retrieve the information.Python Programming/User Interaction self.getInteger() print name.data == "": self.data = raw_input(msg) # Save the user input to a local object variable else: self. # import is not imported name = ainput("Please enter your first name:"). The use of the code will run like this. so we use AInput for Advance Input ''' This class will create a object with a simpler coding interface to retrieve console input''' def __init__(self.data = "" # Initialize a empty data variable if not msg == "": self.data) With this tool at our disposal displaying.py) class ainput: # We can't use input as it is a existent function name.getString() age = ainput("Now enter your age:"). req=0): ''' This will display the prompt and retrieve the user input.data) def getNumber(self): ''' Returns the user input as a Float number''' return float(self.data = raw_input(msg + " (Require)") # Verify that the information was entered and its not empty.''' if req == 0: self.data def getInteger(self): ''' Returns the user input as a Integer''' return int(self.ask(msg) def ask(self. This will accept a space character.msg.g.data = raw_input(msg + " (Require)") 48 . age To test this code copy the following to a python script file (e. This will accept a space character.get() if __name__ == "__main__": # Create Window Object or Window Form app_win = Tkinter.data def getInteger(self): ''' Returns the user input as a Integer''' return int(self. of which the most standard is Tkinter which comes with Python.data) def main(): # import is not imported name = ainput("Please enter your first name:"). Lets proceed by creating a classic developer Hello World example with the following code.Python Programming/User Interaction 49 # Verify that the information was entered and its not empty. a more detailed reference can be found in GUI Programming Modules of this wikibook.data) def getNumber(self): ''' Returns the user input as a Float number''' return float(self.data == "": self.Label(app_win.ask(msg.getString() age = ainput("Now enter your age:").text="Hello World") app_label.pack() .getInteger() print name. This section will be limited to basic Tkinter programming fundamentals.Tk() # Create label object app_label = Tkinter. import Tkinter # Define input retrieve function for application input def retrieve_text(): print app_entry.req) def getString(self): ''' Returns the user input as String''' return self. Better Validation needed if req == 1 and self. age if __name__ == '__main__': main() Graphical User Interface(GUI) Python has many different GUI toolkits. The next lines bind the entry object with the window. The next line binds the Label object to the Window object by using the pack method. the next argument is the label text. The next line proceeds to bind the Button to the window. while the text function returns a string value for the user input. the Tkinter library provides the Entry Object (same as Textbox in other programming languages).Entry(app_win) app_entry. The Button Text value is fill much like the same as we did with the label and the buttons action is fill using the command argument.pack() # Initialize Graphical Loop app_win. Next we create a windows object where all the gui components (or widgets as the Tkinter toolkit calls them) are place. Think of it like a painting canvas where we draw our application interface. Next stop is the User Input Object.mainloop() allow the Tkinter application to run. For a moment think of an application that requires a couple of inputs with labels to identify them. Having define the windows we proceed to create a Label widget. For the moment the value will be print to the console. The OOP methodolgy has the advantage of letting us create a new object that presents the label and entry object at the same time. Like all the other Objects the Window object its the first argument. The code below does just that. Notice that again we need the Window object as first argument.Frame): # Object Initialize def __init__(self.command=retrieve_text) app_button.mainloop() On the first line we actually import the Tkinter library in use by using import Tkinter.pack() # Create Button Object app_button = Tkinter. On the last line a call to app_win.text="Print Value". # Import Tkinter Library import Tkinter # Define our Textbox Object class textbox(Tkinter. A more advanced text box can include validation and data retrieval. it wraps a label and a entry object inside a Tkinter Frame Object. especially with so much code to write for such a simple program. msg): . Next is the creation of the Button Object for the application.Button(app_win.parent. But when you bring OOP concepts into the mix it is different. Notice the first argument on Label object call is the variable holding the window object this is for binding purpose. Notice that the command argument doesn't have quote as its not a string text but a reference to the function. Advance OOP GUI So far it seems tedious to create a GUI using Python. The object require windows object as first argument and the label text as the second.Python Programming/User Interaction 50 # Create User Input Object app_entry = Tkinter. is reusable and can be called with one line of code. Next a function is created to retrieve the value from the input object use in the GUI. expand=True) # Proceed to pack the frame self. Previous: Object-oriented programming Index Next: Databases 51 . but works wonders for small script GUI.g_entry = Tkinter.g_label.pack(side=Tkinter.X.Frame. This is not practical on complex layout application since the object controls this function. expand=True) def text(self): # Textbox text value retrieval return self.get() Now on our multi-input application we can use this new object with one simple line for each instance: name = textbox(win."Name:") Notice that we don't need to call the pack method as the text box object packs itself on the last line of the __init__.text=msg) self.Label(self.g_entry. anchor=Tkinter.__init__(self. fill=Tkinter.g_label = Tkinter.parent) # Create the Textbox Label on the Left side self.LEFT.NW.Entry(self) self.Python Programming/User Interaction # Initialize the Frame properties by explicit calling its Init method Tkinter.gui['entry'].X.pack(side=Tkinter.pack(fill=Tkinter.LEFT.expand=False) # Create the Textbox Entry on the Right side self. connect(read_default_file="~/.fetchone() if row == None: break #do something with this row of data db. otherwise the data will not be stored. In the end. the file . Modules included with Python include modules for SQLite and Berkeley DB.g. In order to make the initialization of the connection easier.Python Programming/Databases 52 Python Programming/Databases Previous: User Interaction Index Next: Internet Python has some support for working with databases. . some kind of data processing has to be used on row.cnf in the home directory contains the necessary configuration information for MySQL.close() Obviously. the Module MySQLdb is imported. a configuration file can be used: import MySQLdb db = MySQLdb.fetchone() and process the rows individually: #first 5 lines are the same as above while True: row = cursor. The result of the fetchone() command is a Tuple.my.g.close() On the first line.my. "dbname") cursor = db. "password". The latter have to be downloaded and installed before use. On line 5 we execute the query and on line 6 we fetch all the data.cnf") . MySQL An Example with MySQL would look like this: 1 2 3 4 5 6 7 import MySQLdb db = MySQLdb. lines contains the number of lines fetched (e. Here. If the number of lines are large.connect("host machine". Modules for MySQL and PostgreSQL and others are available as third-party modules. After the execution of this piece of code. it is better to use row = cursor.. the content of sampletable. e. we save the actual SQL statement to be executed in the variable query. Then a connection to the database is set up and on line 4. the connection to the database would be closed again..cursor() query = """SELECT * FROM sampletable""" lines = cursor. "dbuser". The variable data contains all the actual data.execute(query) data = cursor. the number of rows in the table sampletable).fetchall() db. urlopen(". org/ library/ sqlite3.urlopen(". org/ http:/ / www. html http:/ / initd.html").spam.urlencode({"plato":1. pygresql.org/eggs. "socrates":10.read() print pageText # Using POST method pageText = urllib.urlopen(". params).older) [3] MySQL module [4] Previous: User Interaction Index Next: Internet References [1] [2] [3] [4] http:/ / docs. python. import urllib params = urllib. Getting page text as a string An example of reading the contents of a webpage import urllib pageText = urllib.com/greece". "arkhimedes":11}) # Using GET method pageText = urllib. This module provides a file-like interface for web urls. too. org/ http:/ / sourceforge.com/greece?%s" % params). "sophokles":4. net/ projects/ mysql-python/ Python Programming/Internet Previous: Databases Index Next: Networks The urllib module which is bundled with python can be used for web interaction.Python Programming/Databases 53 External links • • • • SQLite documentation [1] Psycopg2 (PostgreSQL module .read() print pageText .read() print pageText Get and post methods can be used.newer) [2] PyGreSQL (PostgreSQL module . Python Programming/Internet 54 Downloading files To save the content of a page on the internet directly to a file.org/wikibooks/en/9/91/Python_Programming. Other functions The urllib module includes other functions that may be helpful when writing programs that use the internet: >>>>> print urllib.pdf") This will download the file from here [1] and save it to a file "pythonbook. wikimedia. the quote and quote_plus functions encode normal strings. org/ wikibooks/ en/ 9/ 91/ Python_Programming. converting urlencoded text to plain text. described above converts a dictionary of key-value pairs into a query string to pass to a URL.wikimedia. or you can use the urlretrieve function: import urllib urllib. you can read() it and save it as a string to a file object.pdf" "pythonbook. for use in submitting data for form fields. pdf .urlretrieve(" This%20isn%27t%20suitable%20for%20putting%20in%20a%20URL >>> print urllib.pdf" on your hard drive.quote_plus(plain_text) This+isn%27t+suitable+for+putting+in+a+URL The urlencode function. Previous: Databases Index Next: Networks References [1] http:/ / upload. The quote_plus function uses plus signs for spaces. The unquote and unquote_plus functions do the reverse. and cProfile for the profile module. Other modules have C implementations as well. import cPickle # You may want to import it as P for convenience. compact loops.join() for concatenation: (but don't worry about this unless your resulting string is more then 500-1000 characters long) [1] print "Spam" + " eggs" + " and" + " spam" print " "."eggs". Additionally. • String concatenation is expensive. you . directory = os. "and". C written module for pickle.join(["Spam"."spam"]) faster/more idiom print "%s %s %s %s" % ("Spam". cPickle is used to serialize python program. cStringIO for the StringIO module.Python Programming/Networks 55 Python Programming/Networks Previous: Internet Index Next: Tips and Tricks Previous: Internet Index Next: Tips and Tricks Python Programming/Tips and Tricks Previous: Networks Index Next: Basic syntax There are many tips and tricks you can learn in Python: Strings • Triple quotes are an easy way to define a string with both single and double quotes. List comprehension and generators • List comprehension and generator expressions are very useful for working with small.listdir(os. "spam") pythonic way of very fast # DON'T DO THIS # Much # common Python # Also a # doing it - Module choice • cPickle is a faster.getcwd()) # Gets a list of files in the # directory the program runs from filesInDir = [item for item in directory] # Normal For Loop rules apply. Use percent formatting and str. "eggs". it is faster than a normal for-loop."and". Dictionaries themselves cannot be used as members of a set as they are mutable. 'd': 4}.2. the following will be more efficient. then convert back. Other • Decorators can be used for handling common concerns like logging.b for (a. say you have 2 lists: list1 = [{'a': 1. a = None) -> list Return a flat version of the iterator `seq` appended to `a` """ if a == None: a = [] try: # Can `seq` be iterated over? for item in seq: # If so then iterate over `seq` flatten(item.3). • While Python has no built-in function to flatten a list you can use a recursive function to do the job quickly. 'j': 10}] and you want to find the entries common to both lists. perform the operation. (1. 'h': 8}. but for larger lists.intersection(set2) = [dict(entry) for entry in common] Sets are optimized for speed in such functions. 0. {'i': 9. db access. {'g': 7. 'f': 6}. a = None): """flatten(seq. for example if each contains thousands of entries.items()) for entry in list2]) = set1.2. checking for common items in the other: common = [] for entry in list1: if entry in list2: common. this will work fine. {'c': 3. but tuples can. one can convert the items to tuples and the list to a set. etc. You could iterate over one list. 0] 56 Data type choice Choosing the correct data type can be critical to the performance of an application. 'b': 2}. and produces the same result: set1 = set2 = common common set([tuple(entry.b) in zip((1.items()) for entry in list1]) set([tuple(entry. {'e': 5. If one needs to do set operations on a list of dictionaries. a) # and make the same check on each .Python Programming/Tips and Tricks # can add "if condition" to make a # more narrow search. 'f': 6}] list2 = [{'e': 5. This is often much faster than trying to replicate set operations using string functions. • List comprehension and generator expression can be used to work with two (or more) lists with zip or itertools.izip [a . def flatten(seq. For example.append(entry) For such small lists.3))] # will return [0. append(seq) return a 57 # If seq isn't iterable # append it to the new list. please [2]. wikibooks. except TypeError: a. References [1] "'concat vs join . php?title=Python_Programming/ Tips_and_Tricks& action=edit Previous: Networks Index Next: Basic syntax .8. 2004. .followup' on 'Python Rocks! and other rants 27. org/ w/ index.Python Programming/Tips and Tricks item.2004 Weblog of Kent S Johnson'" (http:/ / www. add this code: print 'Hit Enter to exit' raw_input() • Python already has a GUI interface built in: Tkinter Not complete. net/ users/ 0000323/ weblog/ 2004/ 08/ 27. Retrieved 2008-08-29. pycs. August 27. html). • To stop a Python script from closing right after you launch one independently. [2] http:/ / en. Add more. Python treats 'number' and 'Number' as separate. use a matched pair of parentheses surrounding a comma separated list of whatever arguments the method accepts (upper doesn't accept any arguments). unrelated entities. So in this example. like all object oriented languages. the way is the literal string that constructs the object). Tips: If you invoked python from the command-line.upper Code attributes are called "methods". To execute the code in a method.e. followed by the name of the attribute. Objects In Python. While they may look the same in editor. which typically represent the pieces in a conceptual model of a system. one could use the following: 'bob'. it is necessary to have a way to refer to the object (in the following example. Objects in Python are created (i.58 Concepts Python Programming/Basic syntax Previous: Tips and Tricks Index Next: Data types There are five fundamental concepts in Python. Spaces and tabs don't mix Because whitespace is significant. instantiated) from templates called Classes (which are covered later.py this will issue an error if you mixed spaces and tabs. the interpreter will read them differently and it will result in either an error or unexpected behavior. To access attributes. one writes the name of the object followed by a period (henceforth called a dot).. Most decent text editors can be configured to let tab key emit spaces instead. which represent the various pieces of code and data which comprise the object. so use only one or the other when indenting your programs. upper is a method of 'bob' (as it is of all strings).upper() . which refers to the code that returns a copy of the string in which all the letters are uppercase. 'bob'. pythonprogrammer@wikibook:~$ python -tt myscript. as much of the language can be used without understanding classes). Python's Style Guideline described that the preferred way is using 4 spaces. there are aggregations of code and data called Objects. you can give -t or -tt argument to python to make python issue a warning or error on inconsistent tab usage. A common error is to mix them. So to find an uppercase version of the string 'bob'. An example is the 'upper' attribute of strings. To get to this. remember that spaces and tabs don't mix. Case Sensitivity All variables are case-sensitive. They have "attributes". Python 2. 'zip'] >>> Namespaces are a simple concept... When you first start the Python interpreter (i. With functions. first we can use the type() function to show what __builtins__ is: >>> type(__builtins__) <type 'module'> Since it is a module. 'name'] Note that I was able to add the "name" variable to the namespace using a simple assignment statement. .e. To begin with. it is important that one piece of code does not affect another in difficult to predict ways.. The import statement was used to add the "math" name to the current namespace. there is a built-in function dir() that can be used to help one understand the concept of namespaces. There are two ways of delimiting regions in Python: with functions or with modules..Python Programming/Basic syntax 59 Scope In a large system. The way to access names from other modules lead us to another concept. Because of this. in interactive mode). A scope is a "region" of code in which a name can be used and outside of which the name cannot be easily accessed. . For example: >>> dir() ['__builtins__'.. but the concept of namespaces is one that transcends any particular programming language. you can list the objects in the current (or default) namespace using this function. the concept of scope was invented. 'math'.1200 32 bit (Intel)] on win32 Type "help". One of the simplest ways to further this goal is to prevent one programmer's choice of names from preventing another from choosing that name. To demonstrate this. that way is to return the data. which we have already mentioned. we can simply: . Each name within a namespace is distinct from names outside of the namespace. '__name__'. >>> dir() ['__builtins__'. '__name__'] This function can also be used to show the names available within a module namespace. 'credits'. '__name__'] >>>>> import math >>> dir() ['__builtins__'.4 (#53.. '__doc__'. "copyright". '__doc__'. A namespace is a place in which a name resides. Oct 18 2004. we can list the names within the __builtins__ namespace.. To see what math is. Namespaces It would be possible to teach Python without the concept of namespaces because they are so similar to attributes. . . 20:35:07) [MSC v.3.. and so it is important to teach. They each have different ways of accessing the useful data that was produced within the scope from outside the scope. A name is placed within a namespace when that name is given a value. "credits" or "license" for more information. 'help'. 'copyright'. 'license'. again using the dir() function (note the complete list of names has been abbreviated): >>> dir(__builtins__) ['ArithmeticError'. This layering of namespaces is called scope. '__doc__'.. 'ldexp'. you will notice that both the default namespace. 'log10'. 'sqrt'.Python Programming/Basic syntax >>> math <module 'math' (built-in)> Since it is a module. To access objects inside a namespace. simply use the name of the module. It provides access to the mathematical functions defined by the C standard. 'floor'. it also has a namespace. 'log'. followed by the name of the object. 'tanh'] >>> If you look closely. To display the names within this namespace. 'sin'. 'cos'. '__name__'. 'degrees'. 'radians'. 'fmod'.__name__ math >>> print math. 'tan'. 'exp'. 'cosh'.1415926535897931 Previous: Tips and Tricks Index Next: Data types 60 .__doc__ This module is always available. 'modf'. 'frexp'. 'pow'. and that of the object with the same name within the math module. 'ceil'. we: >>> dir(math) ['__doc__'. 'atan'. 'fabs'. 'asin'. followed by a dot. >>> math. 'atan2'. 'e'.pi 3. 'hypot'. For example: >>> print __name__ __main__ >>> print math. The fact that each layer can contain an object with the same name is what scope is all about. 'acos'. and the math module namespace have a '__name__' object. 'sinh'. This allow us to differentiate between the __name__ object within the current namespace. 'pi'. The difference is in the starting and ending delimiters. 10+5j is a complex number. Strings can be either single or triple quoted strings. Note that j by itself does not constitute a number. for example) • hexadecimal numbers can be entered by prepending a 0x (0xff is hex FF. which is entered by appending a j (i. They are entered with three consecutive single or double quotes. So is 10j). So therefore 'foo' works. but 'bar" does not work. and in that single quoted strings cannot span more than one line. also called dicts. Their starting and ending delimiters must also match. Python does not do that. Single quoted strings are entered by entering either a single quote (') or a double quote (") followed by its match. equivalent to C longs Floating-Point numbers. Python's basic datatypes are: • • • • • • Integers. Long integers are entered either directly (1234567891011121314151617181920 is a long integer) or by appending an L (0L is a long integer). Other programming languages often determine whether an operation makes sense for an object by making sure the object can never be stored somewhere where the operation will be performed on the object (this type system is called static typing). hashmaps. or 255 in decimal) Floating point numbers can be entered directly. Instead it stores the type of an object with the object. Complex numbers are entered by adding a real number and an imaginary one. Strings Some others. and "moo" works as well. but can span more than one line.Python Programming/Data types 61 Python Programming/Data types Previous: Basic syntax Index Next: Numbers Data types determine whether an object can do something. "quux'' is right out. or associative arrays Literal integers can be entered as in C: • decimal numbers can be entered directly • octal numbers can be entered by prepending a 0 (0732 is octal 732. equivalent to C doubles Long integers of non-limited length Complex Numbers. Triple quoted strings are like single quoted strings. such as type and function Python's composite datatypes are: • lists • tuples • dictionaries. or whether it just would not make sense. and checks when the operation is performed whether that operation makes sense for that object (this is called dynamic typing). Computations involving short integers that overflow are automatically turned into long integers.e. and "baz' does not work either. If this is desired. use 1j. so . Python Programming/Data types '''foo''' works. to any depth: ((((((((('bob'.) Lists are similar.). but '"'bar'"' does not work. but with brackets: ['abc'. 'weight': 'African or European?' } Any of these composite types can contain any other. 1. Tuples are entered in parenthesis. '"'quux"'" is right out. 'lamb']).). 'whose fleece was as white as snow' Note that one-element tuples can be entered by surrounding the entry with parentheses and adding a comma like so: ('this is a stupid tuple'. 'a'. 'Mary had a little lamb') Also. and """moo""" works as well.['Mary'.).). 'little'. 'had'. { 'hello' : 'world' } ).).) Previous: Basic syntax Index Next: Numbers 62 .). with commas between the entries: (10. and """baz''' does not work either. the parenthesis can be left out when it's not ambiguous to do so: 10.2.value pairs separated from each other by a colon and from the other entries with commas: { 'hello': 'world'.3] Dicts are created by surrounding with curly braces a list of key. Python Programming/Numbers 63 Python Programming/Numbers Previous: Data types Index Next: Strings Python supports 4 types of Numbers. 5/2.g. some expressions may be confusing since in the current version of python. 2.5 >>> from __future__ import division >>> 5/2 2.5. You have to specify one of the operands as a float to get true division.5 >>> 5//2 2 . • Complex: This is a complex number consisting of two floats. it is equivalent to the hardware 'c long' for the platform you are using. >>> x = 5 >>> type(x) <type 'int'> >>> x = 187687654564658970978909869576453 >>> type(x) <type 'long'> >>> x = 1. the int. Complex literals are written as a + bj where a and b are floating-point numbers denoting the real and imaginary parts respectively. • Long: This is a integer number that's length is non-limited. In python 2. The farther to the right you go. >>> 5/2 2 >>>5/2.5 >>>5. You don’t have to specify what type of variable you want./2 (the dot specifies you want to work with float) to have 2. using floor division. Python does that automatically. the number types are automatically 'up cast' in this order: Int → Long → Float → Complex. e. the long. Ints are automatically turned into long ints when they overflow. In general. For example. Longs and Ints are automatically converted to floats when a float is used in an expression. • Float: This is a binary floating point number.2 and later. or 5. the higher the precedence. This behavior is deprecated and will disappear in a future python release as shown from the from __future__ import. the float and the complex. using the / operator on two integers will return another integer./2 2. and with the true-division // operator.34763 >>> type(x) <type 'float'> >>> x = 5 + 2j >>> type(x) <type 'complex'> However. 5/2 will give you 2. • Int: This is the basic integer type in python.>> print a == b True >>> print a == 'hello' True >>> print a == "hello" True >>> print a == 'hello ' False >>> print a == 'Hello' False Numerical There are two quasi-numerical operations which can be done on strings -.addition and multiplication. Example: >>>>> c + 'b' 'ab' >>> c * 5 'aaaaa' # Assign 'hello' to a and b. String multiplication is repetitive addition. that is. or concatenation. they only test whether two strings occupy the same space in memory. String addition is just another name for concatenation.Python Programming/Numbers 64 Previous: Data types Index Next: Strings Python Programming/Strings Previous: Numbers Index Next: Lists String manipulation String operations Equality Two strings are equal if and only if they have exactly the same contents. # True # # (choice of delimiter is unimportant) # (extra space) # (wrong case) . Many other languages test strings only for identity. in ? TypeError: object does not support item assignment >>> s[1:3] = "up" Traceback (most recent call last): File "<stdin>". The last character has index -1. it will default to the first or last index. Python also indexes the arrays backwards. s[a:b] will give us a string starting with s[a] and ending with s[b-1]. >>> print s >>> s[0] = 'J' Traceback (most recent call last): File "<stdin>". line 1. and so on. The first character in string s would be s[0] and the nth character would be at s[n-1]. in ? TypeError: object does not support slice assignment >>> print s Outputs (assuming the errors were suppressed): Xanadu Xanadu Another feature of slices is that if the beginning or end is left empty. Indexing and Slicing Much like arrays in other languages. the second to last character has index -2. using negative numbers. >>> s[1:4] 'ana' Neither of these is assignable. line 1. >>> s[-4] 'n' We can also use "slices" to access a substring of s. the individual characters in a string can be accessed by an integer representing its position in the string. >>>>> s[1] 'a' Unlike arrays in other languages. This also works on substrings >>> x >>> y >>> x False >>> y True = 'hello' = 'll' in y in x 65 Note that 'print x in y' would have also returned the same value. depending on context: .Python Programming/Strings Containment There is a simple operator 'in' that returns True if the first operand is contained in the second. Python Programming/Strings >>>: Index: 1 0 -4 1 -3 2 2 -2 3 3 -1 4 4 66. Either single or double quotes may be used to delimit string constants. String methods There are a number of methods of built-in string functions: • • • • • • • • • • • • • • • • • • capitalize center count decode encode endswith expandtabs find index isalnum isalpha isdigit islower isspace istitle isupper join ljust • lower • lstrip • replace Python Programming/Strings • • • • • • • • • • • • • rfind rindex rjust rstrip split splitlines startswith strip swapcase title translate upper zfill 67. • isalnum returns True if the string is entirely composed of alphabetic and/or numeric characters (i.e. no punctuation). • isalpha and isdigit work similarly for alphabetic characters or numeric characters only. • isspace returns True if the string is composed entirely of whitespace. • >>> '2Yk'. Python Programming/Strings' count Returns the number of the specified substrings in the string. i.e. >>>>> s.count('l') # print the number of 'l's in 'Hello, World' (3)') print s.strip(string.lowercase) outside print s.strip(string.printable) 68 # Removes all w's from outside # Removes all lowercase letters from # Removes all printable characters rjust.wikibooks. '4'.rfind('l') 10 >>> s[:s.join(seq) '1 2 3 4 5' >>> '+'. center left. index.ljust(7) 'foo ' >>> s.4.5] >>> ' '.wikibooks.join(map(str.Python Programming/Strings Outputs: www. rfind and rindex are the same as find and index except that they search through the string from right to left (i. world' >>> s. Note that string. '3'. world' >>> s.rjust(7) ' foo' >>> s. '2'.e.wikibooks. they find the last occurrence) >>>>> s 'foo' >>> s. rindex The find and index methods returns the index of the first found occurrence of the given subsequence. expandtabs(4) print v print len(v) .>> s[s. Two lines . '*') print len(s. 'Green lines'. The splitlines method breaks a multiline string into many single line strings.. ''.... splitlines The split method returns a list of the words in the string.replace(' '.split('\n') [''.splitlines() [''..expandtabs()..expandtabs()) Outputs: abc*****abc*****abc 19 split. splitlines ignores that final character (see example). ''] >>> s..Python Programming/Strings Outputs: abcdefg abc a 13 Please note each tab is not always counted as eight spaces. It can take a separator argument to use instead of whitespace. Red lines .'. 'One line'.expandtabs(). but empty strings are allowed. One line .expandtabs()) Output: **************** 16>> s. It is analogous to split('\n') (but accepts '\r' and '\r\n' as delimiters as well) except that if the string ends in a newline character. 'd'] Note that in neither case is the separator included in the split strings. Green lines . 'Blue lines'. >>> s = 'Hello. 'o. "list"."is"."This is a list". 'o'. If you wish. If you are using a modern version of Python (and you should be). 'l'. and list elements don't have to be of the same type.Python Programming/Strings 72 Previous: Numbers Index Next: Lists Python Programming/Lists Previous: Strings Index Next: Tuples About lists in Python A list in Python is an ordered group of items (or elements). For example: [ 1. 'lp'.Donkey("kong") ] A couple of things to look at.3. 'wo'. To do that. 'a'. you should be familiar with the current behaviour of lists. That means you actually describe the process. 'ft'. The first is through assignment ("statically")."a". 'lo'. There are different data types here. List notation There are two different ways to make a list in python. For instance. >>> item = [x+y for x in 'flower' for y in 'pot'] >>> print item ['fp'. 'oo'. write them between square brackets."of". Writing lists this way is very quick (and obvious). 'rt'] . and determine list behaviour which is different than the default standard."list". It will evaluate the items in all of the objects sequentially and will loop over the shorter objects if one object is longer than the rest. Objects can be created 'on the fly' and added to lists."of". However. and the second is what you do to get it. 'ro'. it does not take into account the current state of anything else. 'w'] List comprehension allows you to use more than one for statement.2. The first is a picture of what each element will look like. 'eo'. you could put numbers. 'rp'. the second is using list comprehensions("actively")."a"."words"] >>> items = [ word[0] for word in listOfWords ] >>> print items ['t'. The other way to make a list is to form it using list comprehension. 'i'. 2. 'op'. there is a class called 'list'. strings and donkeys all on the same list. 'fo'. To make a static list of items. 'wt'. The last item is a new kind of Donkey.'c'. But first. 'ep'. 'wp'. 'ot'. >>> listOfWords = ["this". you can make your own subclass of it. Lists in python may contain more than one data type. 1. 'et'. lets say we have a list of words: listOfWords = ["this". the list is broken into two pieces. For instance. It is a very general structure."words"] We will take the first letter of each word and make a list out of it. 'lt'. letters."is". 0. 0. [0. 'foo'. 0]. 0].Python Programming/Lists Python's list comprehension does not define a scope. 'foo'. 0]. 0. [0. 0]] Assuming the above effect is not what you intend. 0. 0. 1. 0. [0. 0. 0. 1. 0]] What's happening here is that Python is using the same reference to the inner list as the elements of the outer list. 0. [0. 0]] >>> innerlist[2]=1 >>> print listoflists [[0. 0. 'foo'. 1. 0. 0. [0. 0. 1. 0. 0. [0. [0. 0. 0. 1. [0. 0]. 0]. 1. [0. 0. 1. 'foo'. 0]. 0. 0. [0. 0. You'd guess that the easy way to generate a two dimensional array would be: listoflists=[ [0]*4 ] *5 and this works. 0. 0. 'foo'. [0. 0. 0]] >>> listoflists[0][2]=1 73 . 0. [0. 0. 0]. [0. 1. 0. 0. 0]. Any variables that are bound in an evaluation remain bound to whatever they were last bound to when the evaluation was completed: >>> print x. 0. 0]. Python copies each item by reference. 0. 0]. 0]. but probably doesn't do what you expect: >>> listoflists=[ [0]*4 ] *5 >>> print listoflists [[0. 0. 0]. one way around this issue is to use list comprehensions: >>> listoflists=[[0]*4 for i in range(5)] >>> print listoflists [[0. [0. 1. 0]] >>> listoflists[0][2]=1 >>> print listoflists [[0. [0. 0. 0. 1. 0]. 0. [0. 0. Another way of looking at this issue is to examine how Python sees the above definition: >>> innerlist=[0]*4 >>> listoflists=[innerlist]*5 >>> print listoflists [[0. 0]. 0]. When building a new list by multiplying. 0. This poses a problem for mutable items. 0]. 0. 0. 0]. 0]. [0. 0] This works for any data type: >>> foos=['foo']*8 >>> print foos ['foo'. 0. 0]. 'foo'] with a caveat. 0. 'foo'. [0. 0]. [0. for instance in a multidimensional array where each element is itself a list. 0. List creation shortcuts Python provides a shortcut to initialize a list to a particular size and with an initial value for each element: >>> zeros=[0]*5 >>> print zeros [0. 0. [0. 0. y r t This is exactly the same as if the comprehension had been expanded into an explicitly-nested group of one or more 'for' statements and 0 or more 'if' statements. [3."n"] >>> list[2] 'usurp' >>> list[3:] [9. 0. 3. 4]] # or print p 2. [0. [3. If you need to combine lists inside of a lambda. 9. [0. 'n'] . [3. 1. [0. >>> >>> [1. >>> list = [2. 4]] However.4] >>> len( a ) 4 Combining lists Lists can be combined in several ways. 4. >>> len([1.2. "usurp". The easiest is just to 'add' them. 2. 0. Getting pieces of lists (slices) Continuous slices Like strings. For instance: >>> [1. append always adds one element only to the end of a list. So if the intention was to concatenate two lists. 0]. 0.2] + [3. 4] Another way to combine lists is with extend. a = [1. 0]. 0. 3. 0]. 0.0. and not part of the list. [0. 0]] 74 Operations on lists List Attributes To find the length of a list use the built in len() method. >>> >>> >>> >>> [1. 0].4] is an element of the list.2.6] a.extend(b) print a 2. 0. 0. 0. always use extend. For example: >>> >>> >>> [1.Python Programming/Lists >>> print listoflists [[0.3]) 3 >>> a = [1.5.4]) p 2. p=[1.3] b = [4.0.2] p. extend is the way to go.4] [1.3. lists can be indexed and sliced. 4. 5. 0. 6] The other way to append a value to a list is to use append.append([3.2. ['something']] . the slice of a list is a list.[]) >>> list ['element'. []. so be careful with mutable types: >>> list_copy[2]. 'elk'. "elk"] >>> list [2. >>> list[1] = 17 >>> list [2. 'element'. []. 'list'. ('t'. 9.71] >>> list [3. 'contents'] >>> list ['new'. 'list'. original = [1.14. 'element'. 'n'] It's even possible to append things onto the end of lists by assigning to an empty slice: >>> list[:0] = [3.14. 'n'] You can also completely change contents of a list: >>> list[:] = ['new'. which don't even have to be the same length >>> list[1:4] = ["opportunistic".('t'.0.). 17. 'contents'] On the right site of assign statement can be any iterable type: >>> list[:2] = ('element'. 'contents'] With slicing you can create copy of list because slice returns a new list: >>> >>> >>> [1. 'elk'. []] 75 but this is shallow copy and contains references to elements from original list.).append('something') >>> original [1. >>> >>> [1.71.Python Programming/Lists Much like the slice of a string is a substring.2.'n'] We can even assign new values to slices of the lists. 2. 'usurp'. 'opportunistic'. 2. >>> [1. []] list_copy. 'new element'] original 'element'. lists differ from strings in that we can assign new values to the items in a list.append('new element') list_copy 'element'. []] list_copy = original[:] list_copy 'element'. However. 'opportunistic'. 2. list = [2. 5] 76 Comparing lists Lists can be compared for equality. 1.2] == [3. The syntax is a:b:n where a and b are the start and end of the slice to be operated upon.4 or higher there are some more sort parameters: sort(cmp. 'b'] Note that the list is sorted in place. 3.Python Programming/Lists Non-Continuous slices It is also possible to get non-continuous parts of an array. If you use Python 2. 'a'. >>> >>> >>> [1. one would use the :: operator. 'b'] list. 6.sort() list 2. list = [1. 'a'.append(4) list 2. List is sorted by return-value of the function reverse : sort ascending y/n List methods append(x) Add item x onto the end of the list.2] == [1.4] False Sorting lists Sorting lists is easy with a sort method. 3. >>> >>> >>> [1. 4. >>> >>> [0. >>> [1. and the sort() method returns None to emphasize this side effect.key. list = [i for i in range(10) ] list[::2] 2. 3] list. If one wanted to get every n-th occurrence of a list.2] True >>> [1. 4] See pop(i) . >>> [1. 8] list[1:7:2] 3.reverse) cmp : method to be used for sorting key : function to be executed with key element. 3. pop() >>>list [2. 3. Tuple notation Tuples may be created directly or converted from lists.Python Programming/Lists 77 pop(i) Remove the item in the list at the index i and return it. >>> l = [1. [6. 'a'.pop(0) >>> list [2. 'a'. If i is not given. 'a'. 4] >>> a 1 >>> b = list. 3. remove the the last item in the list and return it.14]] >>> t = (1. 3. 'a'. 2.14]) >>> t (1. 3.) >>> t ('A single item tuple'. 3.1400000000000001]) >>> tuple(l) (1. [6. tuples are enclosed in parenthesis. 3.1400000000000001]) >>> t == tuple(l) True >>> t == l False A one item tuple is created by a item in parens followed by a comma: >>> t = ('A single item tuple'. Generally. 4] >>> a = list. >>> list = [1. They are generally used for data which should not be edited. [6. 3] >>> b 4 Previous: Strings Index Next: Tuples Python Programming/Tuples Previous: Lists Index Next: Dictionaries About tuples in Python A tuple in Python is much like a list except that it is immutable (unchangeable) once created. [6.) . tuples will be created from items separated by commas." while assigning multiple values to a tuple in one variable is called "tuple packing. adjective. 4) >>> a (1. >>> a = (1. b = 1. Operations on tuples These are the same as for lists except that we may not assign to indices or slices. 2) >>> b = (3. 2) >>> a[0] = 0 Traceback (most recent call last): File "<stdin>". and there is no "append" operator. noun. 'no'. 2) >>> b (3. 'parens') 78 Packing and Unpacking You can also perform multiple assignment using tuples. in ? TypeError: object does not support item assignment >>> a (1. 'needs'. or performing multiple assignment.Python Programming/Tuples Also. 'needs'." When unpacking a tuple. 'parens' >>> t ('A'. direct_object = t >>> noun 'tuple' Note that either. 2 >>> b 2 Assigning a tuple to a several different variables is called "tuple unpacking. 'tuple'. verb. in ? AttributeError: 'tuple' object has no attribute 'append' >>> a (1. 2) For lists we would have had: >>> a = [1. 2] >>> b = [3. line 1. 3. >>> t = 'A'. 4) >>> print a. you must have the same number of variables being assigned to as values being assigned. line 1. >>> article. 2. or both sides of an assignment operator can consist of tuples. 'no'.append(3) Traceback (most recent call last): File "<stdin>". >>> a. 4) >>> a + b (1. 'tuple'. 4] . 6] >>> tuple(l) (4. ('b'. 'b': 2} >>> tuple(d. >>> [3. 1). 4] a 2] b 4] a. 6] Dictionaries can also be converted to tuples of tuples using the items method of dictionaries: >>> d = {'a': 1. >>> [1.append(3) a 2. >>> len( ( 1. >>> l = [4.b) This can be combined with the unpacking technique above in later code to retrieve both return values: . 6) >>> list(t) [4. 3) ) 3 >>> a = ( 1. >>> >>> [1. 2. 2)) Uses of Tuples Tuples can be used like lists and are appropriate when a list may be used but the size is known and small. 2. 3. To return multiple values in many other languages requires creating an object or container of some type. >>> >>> [0. a + b 2. 3] 79 Tuple Attributes Length: Finding the length of a tuple is the same as with lists. 4 ) >>> len( a ) 4 Conversions Convert list to tuples using the built in tuple() method. 5. One very useful situation is returning multiple values from a function. but in Python it is easy: def func(x. 6) Converting a tuple into a list using the built in list() method to cast as a list: >>> t = (4. 3] a[0] = 0 a 2.Python Programming/Tuples >>> [1. 5. 3.y): # code to compute a and b return (a. use the built in len() method. 5.items()) (('a'. 5. (102.2.keys() ['a'.3. 'b': 2. 1601): 'A matrix coordinate'} >>> d == dict(seq) True Also. 'b'.1650.Python Programming/Tuples (a.'b':2. 'c': 3.'A matrix coordinate')] >>> d {'city': 'Paris'. Dictionary notation Dictionaries may be created directly or converted from sequences.1650. (102. 'Fluffers'] >>> d['a'] 1 >>> d['cat'] = 'Mr. Dictionaries are enclosed in curly braces.'b'.seq2)) >>> d {'a': 1. 'age': 38. Whiskers' . 38). 'd': 4} Operations on Dictionaries The operations on dictionaries are somewhat unique. dictionaries can be easily created by zipping two sequences. >>> d = {'a':1. ((102.'d') >>> seq2 = [1. 2. since the items have no intrinsic order.1601):'A matrix coordinate'} >>> seq = [('city'. 'age': 38.'c'.1601). 1650. 'cat'] >>> d. Slicing is not supported.4] >>> d = dict(zip(seq1. 1650. (102. 'cat':'Fluffers'} >>> d.2) Previous: Lists Index Next: Dictionaries 80 Python Programming/Dictionaries Previous: Tuples Index Next: Sets About dictionaries in Python A dictionary in python is a collection of unordered values which are accessed by key. Whiskers' >>> d['cat'] 'Mr. 1601): 'A matrix coordinate'} >>> dict(seq) {'city': 'Paris'.values() [1. ('age'. >>> seq1 = ('a'.'Paris').b) = func(1. {} >>> d = {'city':'Paris'. 'age':38. Unlike sequence objects such as lists and tuples. 1. Any object that can be used as a dictionary key can be a set member. tuples. dictionaries. 'e'.Python Programming/Dictionaries >>> 'cat' in d True >>> 'dog' in d False 81 Combining two Dictionaries You can combine two dictionaries by using the update method of the primary dictionary. 3]) set([0. >>> d = {'apples': 1. in which each element is indexed. >>> s = set([12. 54]) >>> s. 'apples': 1. For more information on sets. 'lemons': 6. 2. Constructing Sets One way to construct sets is by passing any sequential object to the "set" constructor. 3]) >>> set("obtuse") set(['b'. 'o'. and other sets (except frozensets) are not. floating point numbers. 'oranges': 3. Sets also cannot have duplicate members a given object appears in a set 0 or 1 times. 2. 1. 'lemons': 6} >>> d. 'grapes': 5. Integers. 54]) . 12. Note that the update method will merge existing elements if they conflict. using the "add" function. 's'. lists. a set is an unordered collection of objects. Sets also require that all members of the set be hashable. 't']) We can also add elements to sets one by one. 26. >>> set([0. 'u'. and strings are hashable.add(32) >>> s set([32. 'pears': 2} >>> ud = {'pears': 4. see the Set Theory wikibook. 'oranges': 3} >>> Deleting from dictionary del dictionaryName[membername] Previous: Tuples Index Next: Sets Python Programming/Sets Previous: Dictionaries Index Next: Operators Python also has an implementation of the mathematical set. 'pears': 4.update(ud) >>> d {'grapes': 5. 26. 12. 12. 5. 7]) <= set([4. >>> 32 in s True >>> 6 in s False >>> 6 not in s True We can also test the membership of entire sets. but not the individual elements. 14]) >>> s set([32. which adds a group of elements to a set. we check if is a subset or a superset >>> s. >>> set([4. 26]) Note that you can give any type of sequential structure. 8. 9. 19])) True >>> s. . 54.update([26. 7. 15]) >= set([9. and string.Python Programming/Sets Note that since a set does not contain duplicate elements. if we add one of the members of s to s again. the add function will have no effect. 9. However. to the update function. 54. 12. 12]) True Like lists. 12.issuperset([32. 26. regardless of what structure was used to initialize the set. 9]) True Note that the <= and >= operators also express the issubset and issuperset functions respectively. and . or even another set. 12.copy() >>> s2 set([32. 5. >>> s2 = s. 9. 9]) True >>> set([9. >>> s. remember that the copy constructor will copy the set. The set function also provides a copy constructor. we can use the "len" function to find the number of items in a set. 14. This same behavior occurs in the "update" function. 54.issuperset(set([9. 12])) True Note that "issubset" and "issuperset" can also accept sequential data types as arguments >>> s.issubset(set([32. Given two sets of . 14. 26]) 82 Membership Testing We can check if an object is in the set using the same "in" operator as with sequential data types. 9. tuples. -4. 14. using members of set.. For example. >>> s. Note that there is no defined behavior as to which element it chooses to remove.. >>> s." It has the same functionality as remove.remove(9) Traceback (most recent call last): File "<stdin>". Finally. . and discard.clear() >>> s set([]) Iteration Over Sets We can also have a loop move over each of the items in a set. some functions have equivalent special operators. clear. However.6]) We also have the "remove" function to remove a specified element. it is undefined which order the iteration will follow.5. called pop.5.3. line 1. since sets are unordered.6]) However.4. >>> s = set([1.function(s2) will return another set which is created by "function" applied to and .3.2. One of these forms. >>> s. but will simply do nothing if the element isn't in the set We also have another operation for removing elements from a set. will change to be the set created by "function" of and . s1. The first. Note that each of these set operations has several forms.4. s1 & s2 is equivalent to s1. which simply removes all elements from the set.function_update(s2). The other form. s1. r b e l set("blerg") n in s: print n.6]) >>> s.Python Programming/Sets 83 Removing Items There are three functions which remove individual items from a set.. remove. removing a item which isn't in the set causes an error.4.pop() 1 >>> s set([2. pop.intersection(s2) .remove(3) >>> s set([2. g Set Operations Python allows us to perform all the standard mathematical set operations. use "discard. in ? KeyError: 9 If you wish to avoid this error.5.. simply removes an item from the set. >>> s = >>> for . 1. 4.difference_update(s2) >>> s1 set([9. 6. >>> s2 = set([1. 9]) >>> s2 = set([1. 84 Note that union's update function is simply "update" above. 8]) >>> s1. 8. 4. 9]) >>> s1 ^ s2 set([8. 4. 6.s2 set([9. 1. 6. 8.symmetric_difference_update(s2) >>> s1 set([8. 4]) and . 9]) >>> s1. 9]) 6. 8]) >>> s1.intersection_update(s2) >>> s1 set([6]) Symmetric Difference The symmetric difference of two sets is the set of elements which are in one of either set. >>> s1 | s2 set([1. >>> s1. 4]) >>> s1. 4. 6. 9]) >>> s2 = set([1. 6. 6. 6. 6. which is the elements that are in but not in . 1. .symmetric_difference(s2) set([8.intersection(s2) set([6]) >>> s1 & s2 set([6]) >>> s1. 8]) >>> s1. 4. >>> s1 = set([4. Any element in >>> s1 = set([4. 9]) Set Difference Python can also find the set difference of >>> s1 = set([4. 9]) >>> s2 = set([1.union(s2) set([1. 4]) >>> s1 . >>> s1 = set([4.Python Programming/Sets Union The union is the merger of two sets.difference(s2) set([9. 6. Intersection Any element which is in both and will appear in their intersection. but not in both. 8]) 9]) 9]) or will appear in their union. Since they are immutable. pop. 6. they are also hashable. except that it is immutable . etc. 5.once it is created. 4]). 4]) >>> s1 = set([fs. frozenset([2. 5]) >>> fs. frozensets have the same functions as normal sets. 5. 3. line 1.Python Programming/Sets 85 frozenset A frozenset is basically the same as a set. 2/ lib/ types-set. 4.intersection(s1) frozenset([4]) >>> fs. which means that frozensets can be used as members in other sets and as dictionary keys. 3. remove. org/ doc/ 2.add(6) Traceback (most recent call last): File "<stdin>". in <module> AttributeError: 'frozenset' object has no attribute 'add' Reference Python Library Reference on Set Types [1] Previous: Dictionaries Index Next: Operators References [1] http:/ / python. its members cannot be changed. html . 6]) >>> s1 set([4. >>> fs = frozenset([2.) are available. except none of the functions that change the contents (update. 5. 'float()' with the integer as a parameter >>> x = 5 >>> float(x) 5. dividing two integers or longs uses integer division.0 This can be generalized for other numeric types: int(). "/" does "true division" for floats and complex numbers. for example. floating point or complex numbers. So.2 and later). "/" does "true division" for all types.Python Programming/Operators 86 Python Programming/Operators Previous: Sets Index Next: Flow control Basics Python math works like you would expect. >>> 2**8 256 Division and Type Conversion For Python 2. >>> >>> >>> >>> 6 >>> 5 >>> 11 >>> 25 x y z x = = = * 2 3 5 y x + y x * y + z (x + y) * z Note that Python adheres to the PEMDAS order of operations.[1] [2] Dividing by or into a floating point number (there are no fractional types in Python) will cause Python to use true division.0/2. 5 / 2 is 2. This occupies its proper place in the order of operations. For Python 3.0 is 2. Powers There is a built in exponentiation operator **. if you want floor division.x. long(). Beware that due to the limitations of floating point arithmetic. To coerce an integer to become a float. For example: . also known as "floor division" (applying the floor function after division.x. rounding errors can cause unexpected results. complex(). Using "/" to do division this way is deprecated. for example. which can take either integers. use "//" (available in Python 2. 5. 2 3. The divmod function returns a tuple containing the quotient and remainder. or by the divmod builtin function.0 87 Modulo The modulus (remainder of the division of the two operands. variables can be negated directly: >>> x = 5 >>> -x -5 Augmented Assignment There is shorthand for assigning the output of an operation to one of the inputs: >>> >>> 2 >>> >>> 6 >>> >>> 10 >>> >>> 2 >>> >>> 4 >>> >>> 1 x = 2 x # 2 x *= 3 x # 2 * 3 x += 4 x # 2 * 3 + 4 x /= 5 x # (2 * 3 + 4) / 5 x **= 2 x # ((2 * 3 + 4) / 5) ** 2 x %= 3 x # ((2 * 3 + 4) / 5) ** 2 % 3 >>>>> x # repeat this repeat this >>> x *= 3 # fill with x repeated three times >>> x .0 >>> print 0. >>> 10%7 3 Negation Unlike some other languages.2 2.6//0.6/0.Python Programming/Operators >>> print 0. rather than the quotient) can be found using the % operator. Python Programming/Operators repeat this repeat this repeat this 88 Boolean or: if a or b: do_this else: do_this and: if a and b: do_this else: do_this not: if not a: do_this else: do_this Previous: Sets Index Next: Flow control References [1] [. python.html What's New in Python 2.python.3/whatsnew/node7.Changing the Division Operator (http:/ /. org/ dev/ peps/ pep-0238/ ) .2 [2] PEP 238 -. 400] for i in l: print i This will output 100 200 300 400 The for loop loops over each of the elements of a list or iterator. In the first example above.300. -1): print i This will output 10 9 8 7 .100) for i in l: print i The next example uses a negative step (the third argument for the built-in range function): for i in range(10. l = [100. 'for' loops and 'while' loops. The loop above is equivalent to: l = range(100. each of the elements in l is assigned to i. 0. there are two kinds of loops. 401. Generators and list comprehensions are advanced forms of program flow control.Python Programming/Flow control 89 Python Programming/Flow control Previous: Operators Index Next: Functions As with most imperative languages. assigning the current element to the variable name given. For loops A for loop iterates over elements of a sequence (tuple or list). A builtin function called range exists to make creating sequential lists such as the one above easier. For example. A variable is created to represent the object in the sequence.200. there are three main categories of program flow control: • loops • branches • function calls Function calls are covered in the next section. Loops In Python. but they are not covered here. xsquared in l: print x. which is a block of statements that is executed (once) when the while statement evaluates to false. The break statement inside the while loop will not direct the program flow to the else clause. For example: x = 5 while x > 0: print x x = x . if it loops over a sequence of tuples. (4. -2): print i This will output 10 8 6 4 2 for loops can have names for each element of a tuple. 25)] for x. 1). ':'.Python Programming/Flow control 6 5 4 3 2 1 or for i in range(10. For instance l = [(1. 16). For example: . 9). 0. 4).1 Will output: 5 4 3 2 1 Python's while loops can also have an 'else' clause. (3. (2. (5. xsquared will output 1 2 3 4 5 : : : : : 1 4 9 16 25 90 While loops A while loop repeats a sequence of statements until some condition becomes false. The else clause of loops will be executed if no break statements are met in the loop. l = [5. use the break statement x = 5 while x > 0: print x break x -= 1 print x this will output 5 The statement to begin the next iteration of the loop without waiting for the end of the current loop is 'continue'.6.1 x This will output: 5 4 3 2 1 5 Unlike some languages." is not 100" else: . Breaking. there is no post-condition loop. l = range(1.Python Programming/Flow control x = 5 y = x while y > print y = y else: print 91 0: y . continuing and the else clause of loops Python includes statements to exit a loop (either a for loop or a while loop) prematurely.7] for x in l: continue print x This will not produce any output. To exit a loop.100) for x in l: if x == 100: print x break else: print x. . "grapes". "melon". avoiding the break statement...Python Programming/Flow control print "100 not found in range" Another example of a while loop using the break statement and the else statement: expected_str = "melon" received_str = "apple" basket = ["banana". "orange"] x = 0 step = int(raw_input("Input iteration step: ")) while(received_str != expected_str): if(x >= len(basket)): print "No more fruits left on the basket.expected_str.. and skips over it if the predicate is false For instance. and run that branch if it’s true. You can also add "elif" (short for "else if") branches onto the if statement."!" print "Going back home now !" This will output: Input iteration step: 2 I am waiting for my melon . If none of the other branches are executed... using the else clause. >>> x = 10 >>> if x > 0: . print "Negative" . You can also end your if statements with an "else" branch. if(received_str==basket[2]): print "I hate". it tries the second one.. print "Positive" . Note. and skip the rest of the if statement. Positive >>> if x < 0: . however. The simplest form of the if statement simple executes a block of code only if a given predicate is true. "strawberry".expected_str. and so on. that it will stop checking branches as soon as it finds a true predicate." else: print "Finally got what I wanted! my precious ".".". the 'if' statement. then python will run this branch. break received_str = basket[x] x += step # Change this to 3 to make the while statement # evaluate to false. break if(received_str != expected_str): print "I am waiting for my ". If the first elif is false. it will test the predicate on the first elif."!".basket[2]. If the predicate on the first “if” is false.. I hate strawberry ! Going back home now ! 92 Branches There is basically only one kind of branch in Python.. 24) # Result: 48 If a function takes no arguments.. arg2. but there are others.. such as classes or certain class instances. .. elif x == 0: . print "Zero" . A function is the simplest callable object in Python. else: ... 'Negative' 93 Conclusion Any of these loops.. print "Positive" ..): statement1 statement2 .. branches. print "Negative" .arg2): . A loop can loop over a loop.. Defining functions A function is defined in Python by the following format: def functionname(arg1..Python Programming/Flow control >>> x = -6 >>> if x > 0: . and function calls can be nested in any way desired... but without anything in them: def functionname(): statement1 statement2 .. return arg1+arg2 .. >>> def functionname(arg1. .. or even call itself. and a function can call other functions...... a branch can branch again.. Previous: Operators Index Next: Functions Python Programming/Functions Previous: Flow control Index Next: Decorators Function calls A callable object is an object that can accept some arguments (also called parameters) and possibly return an object (often a tuple containing multiple objects). >>> t = functionname(24. it must still include the parentheses.. the names of the actual parameters may not even be accessible (they could be inside another function). which are called formal parameters. For example. since the third parameter is marked with an asterisk. print tail . >>> display_message("message") mess >>> display_message("message".. you can specify any number of arguments above a certain number. then that parameter will have the default value given when the function executes.*tail): . Declaring Arguments Default Argument Values If any of the formal parameters in the function definition are declared with the format "arg = value.Python Programming/Functions The arguments in the function definition bind the arguments passed at function invocation (i. when the function is called). any actual parameters after the first two will be packed into a tuple and bound to "remaining. which are called actual parameters. like so def square(x): return x*x A function can define variables within the function body. 5. you must provide value for each of the first two arguments.e. >>> print_tail(1. 2. If you do not specify a value.... Any names within the function are unbound when the function returns or reaches the end of the function body. This means that each time you call the function.. >>> def display_message(message.. then it will be bound to a dictionary containing any keyword arguments in the actual parameters which do not correspond to any formal parameters. However. to the names given when the function is defined. which are considered 'local' to the function. consider the function: 94 ." >>> def print_tail(first.. def function(first. "omega") (5." then you will have the option of not specifying a value for those arguments when calling the function. When calling the above function. 6) messag Variable-Length Argument Lists Python allows you to declare two special arguments which allow you to create arbitrary-length argument lists.second.. truncate_after = 4): . A function can 'return' a value. print message[:truncate_after] .*remaining): statement1 statement2 . The locals together with the arguments comprise all the variables within the scope of the function. 2. 'omega') If we declare a formal parameter prefixed with two asterisks. The interior of the function has no knowledge of the names given to the actual parameters... key2 = 7. also known as nested function definition. 95 Closure Closure. x) A function's return value can be used by assigning it to a variable. . key3 = 9) {'key3': 9. "my message") because the third argument ("my message") is an unnamed argument. key1 = 5. they will be placed in the dictionary "entries... start=0.x) As shown above. end=3) This above is valid and start will be the default value of 0.. start=1. it will be bound to the formal parameter max_length.Python Programming/Functions def make_dictionary(max_length = 10. as usual. **entries): return dict([(key.. entries[key]) for i.. when calling a function you can specify the parameters by name and you can do so in any order def display_message(message..keys()) if i < max_length]) If we call this function with any keyword arguments other than max_length. 'key2': 7} Calling functions A function can be called by appending the arguments in parentheses to the function name. >>> make_dictionary(max_length = 2." If we include the keyword argument of max_length. key in enumerate(entries. >>> >>> 8 >>> 9 def outer(outer_argument): def inner(inner_argument): return outer_argument + inner_argument return inner f = outer(5) f(3) f(4) . or an empty matched set of parentheses if the function takes no arguments. foo() square(3) bar(5. like so: x = foo() y = bar(5. . A restriction placed on this is after the first named argument then all arguments after it must also be named. is a function defined inside another function. end=4): print message[start:end] display_message("message"... The following is not valid display_message(end=5. Perhaps best described with an example: >>> . . such as illustrated in the following example: >>> def attribution(name): . [3. return a + b . [3. it is used primarily to write very short functions that is a hassle to define in the normal way. This is the essence of closure. A unique feature that makes closure useful is that the enclosed function may use the names defined in the parent function's scope.. 3) 7 Lambda is often used as an argument to other functions that expects a function object. [1. [7. 5]] The lambda form is often useful to be used as closure. 2]..' + name .. [3.John' note that the lambda function can use the values of variables from the scope in which it was created (like pre and post). [7. that means a function is merely an object of type function. key=lambda x: x[1]) [[1. b: a + b)(4. 3].Python Programming/Functions Closure is possible in python because function is a first-class object. lambda lambda is an anonymous (unnamed) function. Previous: Flow control Index Next: Decorators 96 . 3]].. >>> pp = attribution('John') >>> pp('Dinner is in the fridge') 'Dinner is in the fridge -. such as sorted()'s 'key' argument. b): . 4].. 2]. 4]. A function like this: >>> def add(a.. 3) 7 may also be defined using lambda >>> print (lambda a... >>> sorted([[3. return lambda x: x + ' -. Being an object means it is possible to pass function object (an uncalled function) around as argument or as return value or to assign another name to the function object. 5]. >>> add(4. Minimal Example of property decorator: >>> class Foo(object): . bar = property(bar) .. **kargs) .... def bar(self): ..bar() A function is called somewhere baz A good use for the decorators is to allow you to refactor your code so that common features can be moved into decorators.. def bar(self): . def bar(self): . **kargs): ...bar baz The above example is really just a syntax sugar for codes like this: >>> class Foo(object): .. Now you can implement this in a decorator as follows . that you would like to trace all calls to some functions and print out the values of all the parameters of the functions for each invocation. >>> F = Foo() >>> print F.. >>> F = Foo() >>> print F... Consider for example....... return 'baz' ..... @decorator . return 'baz' ... >>> class Foo(object): . @property . return called .... return f(*args.. def called(*args. print 'A function is called somewhere' .Python Programming/Decorators 97 Python Programming/Decorators Previous: Functions Index Next: Scoping Decorator in Python is a syntax sugar for high-level function.. >>> F = Foo() >>> print F. return 'baz' ...bar baz Minimal Example of generic decorator: >>> def decorator(f): .... def Trace(f): def my_f(*args.f =f def __call__(self.2) entering function sum arg 0: 3 arg 1: 2 inside sum Alternately instead of creating the decorator as a class you could have use a function as well.f(*args. *args. f): self.__name__ i=0 for arg in args: print "arg {0}: {1}". **kwds) Then you can use the decorator on any function that you defined by @Trace def sum(a.__doc__ return my_f #An example of the trace decorator @Trace def sum(a.2) 98 .format(i. **kwds): print "entering function " + self. **kwds) print "exiting " + f. b): print "inside sum" return a + b if you run this you should see >>> sum(3.__name__ return result my_f. arg) i =i+1 return self. **kwds): print "entering " + f.__doc__ = f.Python Programming/Decorators #define the Trace class that will be #invoked using decorators class Trace(object): def __init__(self.__name__ my_f. b): print "inside sum" return a + b On running this code you would see output like >>> sum(3.f.__name__ result= f(*args.__name = f. line 2. but the objects to which they refer are not (unless the number of references to the object drops to zero). Variables exist only in the current scope or global scope. and are never typed. bar's scope includes y Now when this code is tested. Scope is delineated by function and class blocks.append(x) # append is an attribute of lists Traceback (most recent call last): File "<pyshell#46>". the variables are destroyed. in -toplevelbar() NameError: name 'bar' is not defined The name 'bar' is not found because a higher scope does not have access to the names lower in the hierarchy. When they go out of scope. In its most common form: >>> for x in range(10): y. in -toplevel- . line 1. So therefore def foo(): def bar(): x = 5 # x is now in scope return x + y # y is defined in the enclosing scope later y = 10 return bar() # now that y is defined. Previous: Functions Index Next: Scoping 99 Python Programming/Scoping Previous: Decorators Index Next: Exceptions Variables Variables in Python are automatically declared by assignment. Variables are always references to objects. Both functions and their scopes can be nested. It is a common pitfall to fail to lookup an attribute (such as a method) of an object (such as a container) referenced by a variable before the variable is assigned the object. So that decorators can be chained. >>> foo() 15 >>> bar() Traceback (most recent call last): File "<pyshell#26>".Python Programming/Decorators entering sum inside sum exiting sum 10: 5 remember it is good practice to return the function or a sensible decorated replacement for the function. append(x) NameError: name 'y' is not defined Here. If you execute this code: try: print 1/0 except ZeroDivisionError: print "You can't divide by zero. to correct this problem. This is a built-in exception -. If there is one. you silly. or dividing by zero. Python looks for a matching except block to handle it. Exceptions can propagate up the call stack: . Raising exceptions Whenever your program attempts to do something erroneous or meaningless. The keywords try and except are used to catch exceptions. If you don't specify an exception type on the except line. it will cheerfully catch all exceptions.see below for a list of all the other ones.Python Programming/Scoping y. one must add y = [] before the for loop. There are a number of built-in exceptions. Previous: Decorators Index Next: Exceptions 100 Python Programming/Exceptions Previous: Scoping Index Next: Input and output Python handles all errors with exceptions. you can set up exception handling blocks in your code. since it means your program will blissfully ignore unexpected errors as well as ones which the except block is actually prepared to handle. line 1. When an error occurs within the try block. execution jumps there. You can also define your own exceptions. This is generally a bad idea in production code. in ? ZeroDivisionError: integer division or modulo by zero This traceback indicates that the ZeroDivisionError exception is being raised. Python raises exception to such conduct: >>> 1 / 0 Traceback (most recent call last): File "<stdin>"." Then Python will print this: You can't divide by zero. An exception is a signal that an error or other unusual condition has occurred. you silly. which indicate conditions like reading past the end of a file. Catching exceptions In order to handle errors. That function calls the function g. This code prints: That value was invalid. So the exception raised propagates out to the main code. which will raise an exception of type ValueError. Neither f nor g has a try/except block to handle ValueError. where there is an exception-handling block waiting for it. use % formatting whenever possible print ErrorMessage Which of course will print: Sorry.Python Programming/Exceptions def f(x): return g(x) + 1 def g(x): if x < 0: raise ValueError." else: return 5 try: print f(-6) except ValueError: print "That value was invalid. (ErrorNumber. This can be extremely useful when trying to debug complicated projects. or to print the python error text yourself." else: print "Congratulation! you have managed to trip a #%d error" % ErrorNumber # String concatenation is slow. ErrorMessage): if ErrorNumber == 2: # file not found print "Sorry. Sometimes it is useful to find out exactly what went wrong.parameter) And then using that exception: try: raise CustomException("My Useful Error Message") except CustomException." In this code. Here is how that code would look. "I can't cope with a negative number here. Custom Exceptions Code similar to that seen above can be used to create custom exceptions and pass information along with them.parameter = value def __str__(self): return repr(self. 'the_parrot' has apparently joined the choir invisible. 'the_parrot' has apparently joined the choir invisible. first creating the custom exception class: class CustomException(Exception): def __init__(self. (instance): 101 . For example: try: the_file = open("the_parrot") except IOError. value): self. the print statement calls the function f. If you have a complicated piece of code to choose which of several courses of action to take. 'items'): self. finally clause allows programmers to close such resources in case of an exception.4 try: result = None try: result = x/y except ZeroDivisionError: print "division by zero!" print "result is ". Continuations are a powerful functional-programming tool and it can be useful to learn them. the code block where the exception occurred might not be revisited. Between 2.items = list(new_items) . after raising an exception.Python Programming/Exceptions print "Caught: " + instance.5 try: result = x / y except ZeroDivisionError: print "division by zero!" else: print "result is".and indeed it is.5 version of python there is change of syntax for finally clause. result finally: print "executing finally clause" Built-in exception classes All built-in Python exceptions [1] Exotic uses of exceptions Exceptions are good for more than just error handling.extend(new_items) else: self. Using exceptions like this may seem like it's a sort of GOTO -. The Python-based mailing list software Mailman does this in deciding how a message should be handled. but a limited one called an escape continuation. result finally: print "executing finally clause" • Python 2.items.parameter 102 Recovering and continuing with finally Exceptions could lead to a situation where.4 and 2. say you want to add items to a list but you don't want to use "if" statements to initialize the list we could replace this: if hasattr(self. • Python 2. Just as a simple example of how exceptions make programming easier. it can be useful to use exceptions to jump out of the code as soon as the decision can be made. In some cases this might leave external resources used by the program in an unknown state. the new input() function reads a line from sys. html Python Programming/Input and output Previous: Exceptions Index Next: Modules Input Python has two functions designed for accepting data directly from the user: • input() • raw_input() There are also very simple ways of reading a file and. It can also take an argument. python." . To get the old behavior of input().. for stricter control over input. org/ library/ exceptions.x ". It raises EOFError if the input is terminated prematurely. and simply returns the string.items.g.items = list(new_items) Previous: Scoping Index Next: Input and output 103 References [1] http:/ / docs. we can emphasize the normal program flow—that usually we just extend the list—rather than emphasizing the unusual case: try: self..Python Programming/Exceptions Using exceptions. reading from stdin if necessary.stdin and returns it with the trailing newline stripped.extend(new_items) except AttributeError: self. which is displayed as a prompt before the user enters the data. print raw_input('What is your name? ') prints out What is your name? <user input data here> Note: in 3.raw_input() was renamed to input(). raw_input() raw_input() asks the user for a string of data (ended with a newline). That is. E. use eval(input()). 'r') This means f is open for reading. So. The most common way to read from a file is simply to iterate over the lines of the file: f = open('test. More complicated expressions are possible. Because files are automatically closed when the file object goes out of scope.2. if a script says: x = input('What are the first 10 perfect squares? ') it is possible for a user to input: map(lambda x: x*x. 'r'): print line[0] It is also possible to read limited numbers of characters at a time. 'r') for line in f: print line[0] f. input() should not be used for anything but the most trivial program.3] would return a list containing those numbers. So entering [1. there is no real need to close them explicitly.txt'. and then returns the value that results. Note that a newline is attached to the end of each line read this way. or 'rw'. For example. Files can be opened by using the file type's constructor: f = file('test. range(10)) which yields the correct answer in list form. Note that no inputted statement can span more than one line. as input() uses eval() to turn a literal into a python type. the loop in the previous code can also be written as: for line in open('test.Python Programming/Input and output 104 input() input() uses raw_input to read a string of data. which can be 'r'. like so: . This will allow a malicious person to run arbitrary code from inside your program trivially. 'w'. File Input File Objects Python includes a built-in file type. The first argument is the filename and the second parameter is the mode.txt'. just as if it were assigned directly in the Python script.txt'. and then attempts to evaluate it as if it were a Python program. Turning the strings returned from raw_input() into python types using an idiom such as: x = None while not x: try: x = int(raw_input()) except ValueError: print 'Invalid Number' is preferable.close() This will print the first character of each line. among some others. In order to print multiple things on the same line. sys. and error. 'World' This will print out the following: Hello. There are also immutable copies of these in __stdin__. In the above example. Also important is the sys. In order to implement the UNIX 'cat' program in Python. a space was added by the print statement because of the comma between the two objects.(10+5j). stderr I/O handles.999. For more complicated command-line argument processing. This is for IDLE and other tools in which the standard files have been changed. and __stderr__. and then print them if they're not whitespace.argv is an array that contains the command-line arguments passed to the program.py hello there programmer! This array can be indexed. like so: print 'Hello.strip()) > 0: print c. sys.and the arguments evaluated. world' This code ought to be obvious.-0. stdout. import sys For finer control over input.argv[2] would contain the string "there".stdin.sys . A file object implicitly contains a marker to represent the current position.0777.stdin: print line.seek(0) Standard File Objects Like many other languages. If the file marker should be moved back to the beginning.0xff. use sys. use commas between them.map.read().read(1) This will read the characters from f one at a time.py") is stored in argv[0]. You must import the sys module to use the special stdin.Python Programming/Input and output c = f. __stdout__.argv array. c = f. stdout. and stderr. World Note that although neither string contained a space. you could do something like this: import sys for line in sys. These are in the sys module and are called stdin. there are built-in file objects representing standard input. Arbitrary data types can be printed this way: print 1.read(1) while len(c) > 0: if len(c. print 'Hello.'. one can either close the file object and reopen it or just move the marker back to the beginning with: f. output. see also( getopt module) 105 Output The basic way to do output is the print statement.2. because the name of the program ("program. python program. stdout. will output: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 If the bare print statement were not present. will output: 0 1 2 3 4 5 6 7 8 9 In order to end this line.999)+str(map)+str(sys) will output: 12255511(10+5j)-0. print str(1)+str(2)+str(0xff)+str(0777)+str(10+5j)+str(-0.stdout.write write('20') write('05\n') will output: 2005 .20): print i. print for i in range(10. the above output would look like: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 106 printing without commas or newlines If it is not desirable to add spaces between objects. for i in range(10): print i.Python Programming/Input and output This will print out: 1 2 255 511 (10+5j) -0.write and use that for output. but you want to run them all together on one line. there are several techniques for doing that. import sys write = sys. it may be necessary to add a print statement without any objects.999<built-in function map><module 'sys' (built-in)> write you can make a shorthand for sys. then later print the whole thing at once. concatenation Concatenate the string representations of each object.999 <built-in function map> <module 'sys' (built-in)> Objects can be printed on the same line without needing to be on the same line if one puts a comma at the end of a print statement: for i in range(10): print i. Modules can be three different kinds of things: • • • • Python files Shared Objects (under Unix and Linux) with the . Mostly.so suffix DLL's (under Windows) with the .e. in the current directory (each of which constitute a module). It is also possible to use similar syntax when writing to a file.py. 'Hello. import math This imports the math standard module. The second statement means that all the elements in the math namespace is added to the current scope.Python Programming/Input and output You may need sys. Directories should include a file in them called __init__. which should probably include the other files in the directory. world' This will print to any object that implements write(). which is controlled by sys. which includes file objects. Importing a Module Modules in Python are used by importing them. All of the functions in that module are namespaced by the module name. instead of to standard output. or directories containing Python files. You can also instruct Python to search other directories for modules by placing their paths in the PYTHONPATH environment variable. import math print math.sqrt(10) This is often a nuisance.). like so: print >> f. there are modules in the standard library and there are other Python files.path. so other syntaxes are available to simplify this. The current directory is always on the path.flush() to get that text on the screen quickly.pyd suffix directories Modules are loaded in the order they're found. . For example. i.stdout. Previous: Exceptions Index Next: Modules 107 Python Programming/Modules Previous: Input and output Index Next: Classes Modules are a simple way to structure a program. If you have the following file mymod. 108 Creating a Module From a File The easiest way to create a module by having a file called mymod.name = 'object 1' you can already import this "module" and create instances of the object Object1.g. "Object3"] The first three commands tell python what to do when somebody loads the module. we want to use Object1 in Object2. import * class Object2: def __init__(self): self.py in it. The last statement defining __all__ tells python what to do when somebody executes from mymod import *.py and Object3.py file: from Object1 import * from Object2 import * from Object3 import * __all__ = ["Object1".Object1() from mymod import * myobject = Object1() From a Directory It is not feasible for larger projects to keep all classes in a single file. These files would then contain one object per file but this not required (although it adds clarity). Each directory needs to have a __init__. Suppose we have two more objects called Object2 and Object3 and we want to load all three objects with one command. .otherObject = Object1() We can now start python and import mymod as we have in the previous section. import * command as the following file Object2.Python Programming/Modules Creating a DLL that interfaces with Python is covered in another section. "Object2".py. Object2.py either in a directory recognized by the PYTHONPATH variable or (even easier) in the same directory where you are working. Usually we want to use parts of a module in other parts of a module. import mymod myobject = mymod.py file which contains python commands that are executed upon loading the directory. It is often easier to store all files in directories and load all files with one command. We can do this easily with an from . We would then write the following __init__. We then create a directory called mymod and we store three files called Object1. e.name = 'object 2' self.py class Object1: def __init__(self): self.py shows: from . The first argument (methods must always take at least one argument) is always the instance of the class on which the function is invoked.<member>.x = x .. Class Members In order to access the member of an instance of a class.. An object constructed by a class is called an instance of that class. Instance Construction The class is a callable object that constructs an instance of the class when called. and the locals to this scope become attributes of the class.. The capitalization in this class definition is the convention. but is not required by the language. html Python Programming/Classes Previous: Modules Index Next: MetaClasses Classes are a way of aggregating similar data and functions. It is also possible to access the members of the class definition with <class name>. "call" the class object: f = Foo() This constructs an instance of class Foo and creates a reference to it in f. self.. use the following format: class ClassName: .x .. Methods A method is a function within a class. x): . use the syntax <class instance>. python.. Defining a Class To define a class.. For example >>> class Foo: .. org/ tutorial/ modules.<member>.. print self. A class is basically a scope inside which various code (especially function definitions) is executed. To construct an instance of a class.. def setx(self.Python Programming/Modules 109 External links • Python Documentation [1] Previous: Input and output Index Next: Classes References [1] http:/ / docs... def bar(self): . and of any objects constructed by this class. . 5) >>> Foo.y = 10 >>> g = Foo() >>> g. in bar AttributeError: Foo instance has no attribute 'x' Another effect of this is that we can change the definition of the Foo class during program execution. it will now have this new member. 110 . unlike classes in languages like C or Java. so why isn't it in the member dictionary? If you remember. We just saw that g had the member y. line 1. nothing would happen.bar() Traceback (most recent call last): File "<stdin>".Python Programming/Classes If this code were executed. and then bar were called on that instance. by using it as an attribute of the defining class instead of an instance of that class. in ? File "<stdin>". >>> del f. >>> vars(Foo) {'y': 10.x after running the code above. at least until an instance of Foo were constructed. Dynamic Class Structure As shown by the method setx above. If we then create a new instance of Foo. >>> Foo. the members of a Python class can change during runtime. We can even delete f. we put y in the class definition. Invoking Methods Calling a method is much like calling a function.setx(f. >>> f. this output makes no sense. not g. but instead of passing the instance as the first parameter like the list of formal parameters suggests. 'bar': <function bar at 0x4d6a3c>. like so: >>> Foo.bar(f) This will have the same output. we create a member of the Foo class definition named y. In the code below. '__module__': '__main__'.setx(5) >>> f. not just their values. though. Foo.bar() This will output 5 It is possible to call the method on an arbitrary object.x >>> f. use the function as an attribute of the instance. line 5.y 10 Viewing Class Dictionaries At the heart of all this is a dictionary that can be accessed by "vars(ClassName)" >>> vars(g) {} At first. >>> g. '__module__': '__main__'.y will still be 10.member. though.Python Programming/Classes 'setx': <function setx at 0x4d6a04>. but not Foo's.y 9 >>> Foo. but g.setx(5) >>> vars(g) {'x': 5} Note that if we now assign a value to g. the first parameter passed to the method will always be the class instance itself.y >>> g.y.y will also be 10.__dict__ {'y': 9. it will be added to g's dictionary.__dict__['z'] = -4 >>> g.y. >>> g. if we check the values: >>> g. we can treat functions just like variables. 'x': 5} >>> vars(Foo) {'y': 10.z -4 111 . When Python checks for g. If we create a new member of g.y will now override Foo. or change key-value pairs from g. '__doc__': None} And there we have all the members of the Foo class definition. Some may have also noticed that the methods in Foo appear in the class dictionary along with the x and y. >>> g. it first checks g's vars dictionary for "member.y = 9 >>> vars(g) {'y': 9. Changing Class Dictionaries We can also access the members dictionary of a class using the __dict__ member of the class. we are not assigning that value to Foo.__dict__. remember that if we call a method of a class instance. 'bar': <function bar at 0x4d6a3c>. Foo. as Python won't find 'y' in vars(f). this has the same effect as if we had made those changes to the members of g. If you do this. so it will get the value of 'y' from vars(Foo). 'x': 5} If we add. '__doc__': None} Sure enough.y 10 Note that f." then Foo. If you remember from the section on lambda forms. 'setx': <function setx at 0x4d6a04>. This means that we can assign methods to a class during runtime in the same way we assigned variables. remove. .. def __init__(self): .. return self... This puts user defined classes on a level playing field with built-ins. def __init__(self): . Old/Classic classes are slated to disappear in Python 3000. pass Properties Properties are attributes with getter and setter methods.. def setEgg(self..egg 'MyEgg' >>> sp.. self. def getEgg(self): . New Style classes also add constructs like properties and static methods familiar to Java programmers... New style class instances will return the same thing as x..NoSpam() ...Python Programming/Classes 112 New Style Classes New style classes were introduced in python 2. Old class instances were all of type instance.>> sp. A new-style class is a class that has a built-in as its base.__egg = egg .. They can be defined using staticmethod() >>> class StaticSpam(object): . egg = property(getEgg.2. NoSpam = staticmethod(StaticNoSpam) >>> StaticSpam. a major difference between old and new classes is their type.. >>> class SpamWithProperties(object): . self.__egg ...__class__ for their type.egg): .. Old/Classic Class >>> class ClassicFoo: . print "You can't have have the spam.. With this in mind all development should use new style classes. def StaticNoSpam(): .. eggs and spam without any spam.. pass New Style Class >>> class NewStyleFoo(object): . Static methods have no "self" argument and don't require you to instantiate the class before using them..__egg = "MyEgg" . spam.egg 'Eggs With Spam' >>> Static Methods Static methods in Python are just like their counterparts in C++ or Java...setEgg) >>> sp = SpamWithProperties() >>> sp.. def __init__(self): .. most commonly object.... At a low level. that's disgusting" .. .superclass3..y g. In order to use the method defined in the superclass... spam..bar()" Foo.bar()" x = 10 class Bar(Foo): def bar(self): print "I'm doing Bar. >>> .. def StaticNoSpam(): .. 'bar': <function bar at 0x4d6a04>...superclass2.. >>> >>> I'm I'm >>> 9 >>> 10 class Foo: def bar(self): print "I'm doing Foo... that's disgusting" 113 Inheritance Like all object oriented languages. eggs and spam without any spam. .. The subclass will then have all the members of its superclasses.bar(g) doing Bar.... . that's disgusting' They can also be defined using the function decorator @staticmethod. Use the following format for this: class ClassName(superclass1. ..... '__doc__': None} >>> vars(Foo) .Python Programming/Classes 'You can't have have the spam..bar() g.... >>> class StaticSpam(object): .. we can see what's going on under the hood by looking at the class dictionaries. . .bar() doing Foo. Inheritance is a simple concept by which a class can extend the facilities of another class..setx(f... print "You can't have have the spam. as in Foo.): ... >>> vars(g) {} >>> vars(Bar) {'y': 9. eggs and spam without any spam. spam. . it is necessary to call the method as an attribute on the defining class.bar(self) y = 9 g = Bar() Bar. or in Python's case. .5) above: >>> . '__module__': '__main__'.x Once again. the member in the subclass will override the one in the superclass... @staticmethod . multiple other classes. If a method is defined in the subclass and in the superclass. Python provides for inheritance.. x): print x foo = Foo('Hi!') class Foo2: def setx(self. Also as above. class A: def __init__(self): print 'A. Python will check vars(Foo) if it doesn't find x in vars(Bar). and the special name for this is '__init__'. 'bar': <function bar at 0x4d6994>. it checks vars(Bar) next. among other things. '__doc__': None} When we call g.__init__()' a = A() outputs A. All of these names begin and end with two underscores. __init__() is called before an instance is returned (it is not necessary to return the instance manually). thanks to inheritance. printme): print printme foo = Foo('Hi!') outputs Hi! Here is an example showing the difference between using __init__() and not using __init__(): class Foo: def __init__ (self.x. 114 Special Methods There are a number of methods which have reserved names which are used for special purposes like mimicking numerical or container operations. it first looks in the vars(g) dictionary. since g is an instance of Bar. as usual. As an example. For example.__init__() __init__() can take arguments.'Hi!') outputs . However. Initialization and Deletion __init__ One of these purposes is constructing an instance. '__module__': '__main__'. class Foo: def __init__ (self.setx(f. in which case it is necessary to pass arguments to the class in order to create an instance.Python Programming/Classes {'x': 10. It is convention that methods beginning with a single underscore are 'private' to the scope they are introduced within. x): print x f = Foo2() Foo2. it can be executed to get back the original object. For example: __str__ __repr__ __unicode__ Operator str(A) repr(A) unicode(x) (2. Representation __str__ Function Converting an object to a string.g. If __str__ is not present but this one is. this function's output is used instead for printing. iamthis): self.iamthis bar = Bar('apple') bar outputs (note the difference: now is not necessary to put it inside a print) Bar('apple') .Python Programming/Classes Hi! Hi! __del__ Similarly.iamthis = iamthis def __str__ (self): return self. iamthis): self.iamthis bar = Bar('apple') print bar outputs apple __repr__ This function is much like __str__(). __repr__ is used to return a representation of the object in string form. as with the print statement or with the str() conversion function. For example: class Bar: def __init__ (self. when it is no longer referenced. can be overridden by overriding __str__.iamthis = iamthis def __repr__(self): return "Bar('%s')" % self.x only) 115 class Bar: def __init__ (self. This will NOT usually be something that can be executed. e. In general. __str__ returns a formatted version of the objects content. '__del__' is called when an instance is destroyed. Usually. .. It is provided with the name and value of the variables being assigned. name.. return "You don't get to see " + name . B) Direct Form A. except this function is called when we try to access a class member.. name): ... name): . B) setattr(A. C) delattr(A. "cannot be deleted" . >>> p = Permanent() >>> p. comes with a default __setattr__ which simply sets the value of the variable. value): .B __delattr__ __getattr___ Similar to __setattr__. B.Python Programming/Classes Attributes __setattr__ Function This is the function which is in charge of setting attributes of a class.. >>> class Permanent: . print "Nice try" .. of course. def __getattr__(self....x = 9 >>> del p..B = C del A.x 9 . >>> class HiddenMembers: . line 1. def __setattr__(self. def __delattr__(self.. Indirect form getattr(A.. print name...anything "You don't get to see anything" __delattr__ This function is called to delete an attribute..x x cannot be deleted >>> p. >>> u = Unchangable() >>> u.x Traceback (most recent call last): File "<stdin>". and the default simply returns the value.x = 9 Nice try >>> u. but we can override it. >>> h = HiddenMembers() >>> h..B 116 __getattr__ >>> class Unchangable: . in ? AttributeError: Unchangable instance has no attribute 'x' __setattr__ A. Each class. n + 6 >>> -d 13 Function Operator __pos__ __neg__ __inv__ __abs__ __len__ +A -A ~A abs(A) len(A) . .n c + FakeNumber() FakeNumber() = 7 d To override the augmented assignment operators. i. ..n . __ge__ __le__ __lshift__ __rshift__ __contains__ >>> c = FakeNumber() >>> c += d >>> c 12 Unary Operators Unary operators will be passed simply the instance of the class that they are called on. merely add 'i' in front of the normal binary operator..__neg__ = lambda A : A. .. for '+=' use '__iadd__' instead of '__add__'.n + B.e. This will work as expected. >>> FakeNumber. we can use the '+' operator to add instances of the class.Python Programming/Classes Operator Overloading Operator overloading allows us to use the built-in Python syntax and operators to call functions which we define.B): return A.__imul__ = lambda B: B.. The function will be given one argument.. which will be the object on the right side of the augmented assignment operator.. >>> c. 117 Function Operator __add__ __sub__ __mul__ __div__ __floordiv__ __mod__ __pow__ __and__ __or__ __xor__ __eq__ __ne__ __gt__ __lt__ A+B A-B A*B A/B A // B A%B A ** B A&B A|B A^B A == B A != B A>B A<B A >= B A <= B A << B A >> B A in B A not in B >>> ..n c = d = d. Binary Operators If a class has the __add__ function. and the return value will be the result of the addition. >>> >>> >>> >>> 12 class FakeNumber: n = 5 def __add__(A. This will call __add__ with the two instances of the class passed as parameters. The returned value of the function will then be assigned to the object on the left of the operator.6 >>> c *= d >>> c 1 It is important to note that the augmented assignment operators will also use the normal operator functions if the augmented operator function hasn't been set directly.. with "__add__" being called for "+=" and so on. Python Programming/Classes Item Operators It is also possible in Python to override the indexing and slicing operators. This allows us to use the class[i] and class[a:b] syntax on our own objects. The simplest form of item operator is __getitem__. This takes as a parameter the instance of the class, then the value of the index. 118 Function Operator __getitem__ __setitem__ __delitem__ __getslice__ C[i] C[i] = v del C[i] C[s:e] >>> class FakeList: ... def __getitem__(self,index): ... return index * 2 ... >>> f = FakeList() >>> f['a'] 'aa' We can also define a function for the syntax associated with assigning a value to an item. The parameters for this function include the value being assigned, in addition to the parameters from __getitem__ __setslice__ C[s:e] = v __delslice__ del C[s:e] >>> class FakeList: ... def __setitem__(self,index,value): ... self.string = index + " is now " + value ... >>> f = FakeList() >>> f['a'] = 'gone' >>> f.string 'a is now gone' We can do the same thing with slices. Once again, each syntax has a different parameter list associated with it. >>> class FakeList: ... def __getslice___(self,start,end): ... return str(start) + " to " + str(end) ... >>> f = FakeList() >>> f[1:4] '1 to 4' Keep in mind that one or both of the start and end parameters can be blank in slice syntax. Here, Python has default value for both the start and the end, as show below. >> f[:] '0 to 2147483647' Note that the default value for the end of the slice shown here is simply the largest possible signed integer on a 32-bit system, and may vary depending on your system and C compiler. • __setslice__ has the parameters (self,start,end,value) We also have operators for deleting items and slices. • • __delitem__ has the parameters (self,index) __delslice__ has the parameters (self,start,end) Note that these are the same as __getitem__ and __getslice__. Python Programming/Classes Other Overrides 119 Function __cmp__ __hash__ __nonzero__ __call__ __iter__ __reversed__ __divmod__ __int__ __long__ __float__ __complex__ __hex__ __oct__ __index__ __copy__ __deepcopy__ __sizeof__ Operator cmp(x, y) hash(x) bool(x) f(x) iter(x) reversed(x) (2.6+) divmod(x, y) int(x) long(x) float(x) complex(x) hex(x) oct(x) copy.copy(x) copy.deepcopy(x) sys.getsizeof(x) (2.6+) math.trunc(x) (2.6+) format(x, ...) (2.6+) __trunc__ __format__. Python Programming/Classes eggs = Spam() eggs.cook() This will output cooking 5 eggs #add the function to the class Spam #NOW create a new instance of Spam #and we are ready to cook! 120 cook = f eggs. instance. instance. But then we notice that we wanted to cook those eggs. myclass): f = types. Spam) 121 Note that in the function add_method we cannot write instance.Python Programming/Classes To an instance of a class It is a bit more tricky to add methods to an instance of a class that has already been created. Thus our function call might look like this: attach_method(cook. eggs.fxn = f since this would add a function called fxn to the instance. f) All we now need to do is call the attach_method with the arguments of the function we want to attach.cook() Now we can cook our eggs and the last statement will output: cooking 5 eggs Using a function We can also write a function that will make the process of adding methods to an instance of a class easier. but we do not want to create a new instance but rather use the already created one: class Spam: def __init__(self): self. def attach_method(fxn. sourceforge. Spam) eggs.__name__.MethodType(fxn. Lets assume again that we have a class called Spam and we have already created eggs.MethodType(cook. myclass) setattr(instance. fxn. eggs. Previous: Modules Index Next: MetaClasses References [1] http:/ / epydoc.myeggs import types f = types.myeggs = 5 eggs = Spam() def cook(self): print "cooking %s eggs" % self. net/ using. the instance we want to attach it to and the class the instance is derived from. html . 'length'. >>> DeAbbreviate(container_class) >>> wrapped_string. This concept makes use of the fact that class definitions in python are first-class objects..len) ..content_string = 'emu emissary' wrapped_string. Once again... using the same syntax one would normally use in declaring a class definition. classes themselves are instances of a metaclass. .Python Programming/MetaClasses 122 Python Programming/MetaClasses Previous: Classes Index Next: Standard Library In python. 'len') ... line 1.... >>> >>> . delattr(sequence_container.. >>> 12 def StringContainer(): # define a class class String: content_string = "" def len(self): return len(self.. First. Class Factories The simplest use of python metaclasses is a class factory..len() Traceback (most recent call last): File "<stdin>".content_string) # return the class definition return String # create the class definition container_class = StringContainer() # create an instance of the class wrapped_string = container_class() # take it for a test drive wrapped_string... >>> . Any modifications to attributes in a class definition will be seen in any instances of that definition. . . Just as other objects are instances of a particular class.. >>> def DeAbbreviate(sequence_container): .length() 12 >>> wrapped_string..len() Of course. just like any other data in python. so long as that instance hasn't overridden the attribute that you're modifying... Such a function can create or modify a class definition. it is useful to use the model of classes as dictionaries. in ? . sequence_container.... . >>> >>> .. .... let's look at a basic class factory: >>> ... classes are themselves objects.. . class definitions can also be modified. setattr(sequence_container. . and its subclass will be created using your custom metaclass. For example class CustomMetaclass(type): def __init__(cls. bases..length() 12 123 The type Metaclass The metaclass for all standard python types is the "type" object.. int and object.). dct) class BaseClass(object): __metaclass__ = CustomMetaclass class Subclass1(BaseClass): . {'attribute' : 42}) Metaclasses It is possible to create a class with a different metaclass than type by setting its __metaclass__ attribute when defining. line 1. it is in fact an instance of itself. but that will not affect instances of the class. and is itself an instance of a class. bases. When this is done. the class. >>> del container_class >>> wrapped_string2 = container_class() Traceback (most recent call last): File "<stdin>". cls). (BaseClass. >>> type(object) <type 'type'> >>> type(int) <type 'type'> >>> type(list) <type 'type'> Just like list. name. dct): print "Creating class %s using CustomMetaclass" % name super(CustomMetaclass. the base classes to inherit from. For instance. and a dictionary defining the namespace to use. >>> type(type) <type 'type'> It can be instantiated to create new class objects similarly to the class factory example above by passing the name of the new class.__init__(name. In this case.Python Programming/MetaClasses AttributeError: String instance has no attribute 'len' You can also delete class definitions. "type" is itself a normal python object. attribute = 42 Could also be written as: >>> MyClass = type("MyClass". the code: >>> class MyClass(BaseClass): . in ? NameError: name 'container_class' is not defined >>> wrapped_string. com/ pub/ a/ python/ 2003/ 04/ 17/ metaclasses. html [2] http:/ / www. 124 More resources • Wikipedia article on Aspect Oriented Programming • Unifying types and classes in Python 2. onlamp. python. Ira R. html .Python Programming/MetaClasses pass This will print Creating class BaseClass using CustomMetaclass Creating class Subclass1 using CustomMetaclass By creating a custom metaclass in this way. Danforth?) Previous: Classes Index Next: Standard Library References [1] http:/ / www. This allows you to add or remove attributes and methods. Forman. org/ 2. register creation of classes and subclasses creation and various other manipulations when the class is created.2 [1] • O'Reilly Article on Python Metaclasses [2] [Incomplete] (see Putting Metaclasses to Work. it is possible to change how the class is constructed. Scott H. 2/ descrintro. 125 Modules Python Programming/Standard Library Previous: MetaClasses Index Next: Regular Expression The Python Standard Library is a collection of script modules accessible to a Python program to simplify the programming process and removing the need to rewrite commonly used commands. you should create a pattern object. it is best to use the compile function to create a pattern object. then the string "bar". use the compile function. import re foo = re. This should normally be used when writing regexps. but Python does not have constants. For more information about writing regular expressions and syntax not specific to Python. They can be used by 'calling' them at the beginning of a script. storing the middle characters to a group.5})bar'. just import the "re" module: import re Pattern objects If you're going to be using the same regexp more than once in a program. The second. see the regular expressions wikibook.compile(r'foo(. Python's regular expression syntax is similar to Perl's To start using regular expressions in your Python scripts. re. followed by up to 5 of any character. if you need any of the flags. In other languages. Some of the regular expression functions do not support adding flags as a parameter when defining the pattern directly in the function. these would be constants. so that backslashes are interpreted literally rather than having to be escaped.{. Previous: MetaClasses Index Next: Regular Expression Python Programming/Regular Expression Previous: Standard Library Index Next: XML Tools Python includes a module for working with regular expressions on strings. and refer to it later when searching/replacing. argument is the flag or flags to modify the regexp's behavior.S) The first argument is the pattern. The different flags are: .I+re. The r preceding the expression string indicates that it should be treated as a raw string. To create a pattern object. which will be discussed later. optional. or if you just want to keep the regexps separated somehow. The flags themselves are simply variables referring to an integer used by the regular expression engine. which matches the string "foo". st1. re.UNICODE re. Not all of the re module functions support the flags argument and if the expression is used more than once. to search in a substring of the given string.S re. rather than just the beginning and end of the string Makes the . re.Python Programming/Regular Expression 126 Abbreviation re. \b. Baz' st2 = '2. while search will find a match anywhere in the string.M Full name re. . \D. foo is bar' search1 = foo. What if we want to search for multiple instances of the pattern? Then we have two options. because we tell it to start searching at character number 3 in the string. \s.VERBOSE Matching and searching One of the most common uses for regular expressions is extracting a part of a string or testing for the existence of a pattern in a string. We can use the start and end position parameters of the search and match function in a loop.search('oo.S) st1 = 'Foo. but if we do: >>> match3 = foo.IGNORECASE Makes the regexp case-insensitive re.match(st2.X re. 3) it works. The compiled pattern object functions also have parameters for starting and ending the search. The match and search functions do mostly the same thing. For most cases. \b. \S) dependant on the current locale Makes the ^ and $ characters match at the beginning and end of each line.U re.search(st2) match1 = foo.search(st1) search2 = foo. match2 returns no result because the pattern does not start at the beginning of the string. The other 3 results will be Match objects (see below). getting the position to start at from the previous match object (see below) or we can use the findall and finditer functions. useful for simple searching. \W. except that the match function will only return a result if the pattern matches at the beginning of the string being searched. character match every character including newlines.I re. rather than of the pattern object. Bar. In the first example in this section.*ba'. You can also match and search without compiling a regexp: >>> search3 = re.LOCALE re.compile(r'foo(. >>> >>> >>> >>> >>> >>> >>> >>> import re foo = re.DOTALL re.match(st1) match2 = foo. re. \B.5})bar'. \B.I+re. This allows for cleaner-looking regexps. its best to compile the expression first. The findall function returns a list of matching strings. the finditer function should be used. and ignores # (except when in a character class or preceded by an non-escaped backslash) and everything after it to the end of a line.MULTILINE Description Makes the behavior of some special sequences (\w. \d. compiling first is more efficient and leads to cleaner looking code. match2 will be None. so it can be used as a comment.{. \S dependent on Unicode character properties Ignores whitespace except when in a character class or preceded by an non-escaped backslash. because the string st2 does not start with the given pattern. \W. For anything slightly complex.L re.match(st2) In this example. Python offers several functions to do this. \s. Makes \w.I) Here we use the search function of the re module. For example: >>>>> search1.group('name').finditer(str3): . ' '. or if no group number is given.start(1) search1.end(1) This returns the start and end locations of the entire match. that when used in a loop. ' ': ' If you're going to be iterating over the results of the search. ': '] >>> for match in foo.Python Programming/Regular Expression This returns an iterator object. The group function returns a string corresponding to a capture group (part of a regexp wrapped in ()) of the expression. respectively. 127 Match objects Match objects are returned by the search and match functions. '. and the start and end of the first (and in this case only) capture group. For simple expressions this is unnecessary.findall(str3) ['.start() search1. the entire match. but for more complex expressions it can be very useful..group() 'Foo. ' Capture groups can also be given string names using a special syntax and referred to by matchobj. Using the search1 variable we defined above: >>> search1. . BAR FoO: bar' >>> foo. using the start and end functions: >>> 0 >>> 8 >>> 3 >>> 5 search1. '.end() search1.. using the finditer function is almost always a better choice.group(1) . and include information about the pattern match. ' .'. Third part' >>> re. mystring) [''.compile(r'(a[n]? )(\w) ') >>> newstring = pattern. and create a regular expression from it.sub(r"\1'\2' ".escape(r'This text (and this) must be escaped with a "\" to use in a regexp. >>> import re >>>>> pattern = re. and. mystring) >>> subresult ("This string has a 'q' in it". ' Second part '. ' Third part'] The escape function escapes all non-alphanumeric characters in a string. sub returns a string. Unlike the matching and searching functions. the text to replace in.') 'This\\ text\\ \\(and\\ this\\)\\ must\\ be\\ escaped\\ with\\ a\\ \\"\\\\\\"\\ to\\ use\\ in\\ a\\ regexp\\. >>> re. The \1 and \2 in the replacement string are backreferences to the 2 capture groups in the expression. The split function splits a string based on a given regular expression: >>> import re >>> mystring = '1. Using the string and expression from before: >>> subresult = pattern. ' First part '. except it returns a tuple. Second part 3. consisting of the result string and the number of replacements made.split(r'\d\. This is useful if you need to take an unknown string that may contain regexp metacharacters like ( and .Python Programming/Regular Expression 128 Replacing Another use for regular expressions is replacing text in a string. mystring) >>> newstring "This string has a 'q' in it" This takes any single alphanumeric character (\w in regular expression syntax) preceded by "a" or "an" and wraps in in single quotes. use the sub function. To do this in Python. 1) Other functions The re module has a few other functions in addition to those discussed above. sub takes up to 3 arguments: The text to replace with. consisting of the given text with the substitution(s) made.subn(r"\1'\2' ". The subn function is similar to sub. the maximum number of substitutions to make. First part 2. these would be group(1) and group(2) on a Match object from a search. optionally. X = 1 self. attrs): print 'Element:'.Y = 1 class MyCH(saxhandler.sax as saxparser class MyReport: def __init__(self): self. name. including pattern objects and match objects Previous: Standard Library Index Next: XML Tools References [1] http:/ / docs.handler as saxhandler import xml.sax. org/ library/ re. name report = MyReport() ch = MyCH(report) #for future use . html Python Programming/XML Tools Previous: Regular Expression Index Next: Email Introduction Python includes several modules for manipulating xml.handler Python Doc [1] import xml.ContentHandler): def __init__(self.Python Programming/Regular Expression 129 External links • Python re documentation [1] . xml.Full documentation for the re module.sax.report = report def startDocument(self): print 'startDocument' def startElement(self. python. report): self. urlopen(url) return ''.wholeText print t.join(a. l.minidom An example of doing RSS feed parsing with DOM from xml.Python Programming/XML Tools <writer>Neil Gaiman</writer> <penciller pages='1-9.getElementsByTagName('link')[0].org/Slashdot/slashdot") extract(page) XML document provided by pyxml documentation [2].readlines()) def extract(page): a = dom.18-24'>Glyn Dillon</penciller> <penciller pages="10-17">Charles Vess</penciller> </comic> </collection> """ print xml saxparser.hasChildNodes() == True: t = i.parseString(page) item = a.firstChild. d if __name__=='__main__': page = fetchPage("(xml.getElementsByTagName('description')[0].getElementsByTagName('item') for i in item: if i.dom import minidom as dom import urllib2 def fetchPage(url): a = urllib2.getElementsByTagName('title')[0].firstChild.firstChild.wholeText d = i. ch) 130 xml.wholeText l = i.slashdot. Previous: Regular Expression Index Next: Email .dom. handler.ehlo() These steps may not be necessary depending on the server you connect to. send the mail: msg = "\nHello!" # The /n separates the message from the headers (which we ignore for this example) server.starttls() server. for non-ESMTP servers.com". we need to do a few steps to set up the proper connection for sending mail. Other mail systems may not use this. or it may not be available.SMTP('smtp. the second is the port. Sending mail Sending mail is done with Python's smtplib using an SMTP (Simple Mail Transfer Protocol) server. 587) The first argument is the server's hostname. log in to the server: server.login("youremailusername". "password") Then.com". ehlo() is used for ESMTP servers. The port used varies depending on the server. the instructions here are based on sending email through Google's Gmail. python. See Wikipedia's article about the SMTP protocol for more information about this.Python Programming/XML Tools 131 References [1] http:/ / docs. For that. each object is used for connection with one server. The starttls() function starts Transport Layer Security mode. "target@example. . Actual usage varies depending on complexity of the email and settings of the email server. sax. one should use the email package.gmail. msg) Note that this is a rather crude example.sendmail("you@gmail. org/ lib/ module-xml.ehlo() server. Next. import smtplib server = smtplib. The first step is to create an SMTP object. html Python Programming/Email Previous: XML Tools Index Next: Threading Python includes several modules in the standard library for working with emails and email servers. it doesn't include a subject. or any other headers. sourceforge. Next. use helo() instead. server.com'. which is required by Gmail. html [2] http:/ / pyxml. net/ topics/ howto/ node12. Python Programming/Email 132 The email package Python's email package contains many classes and functions for composing and parsing email messages, this section only covers a small subset useful for sending emails. We start by only importing only the classes we need, this also saves us from having to use the full module name later. from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText: The full text of our example message >>> print text Content-Type: multipart/mixed; boundary="===============1893313573==" MIME-Version: 1.0 From: you@gmail.com To: target@example.com Subject: Python email --===============1893313573== Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Python test mail --===============1893313573==-- Python Programming/Email 133 Previous: XML Tools Index Next: Threading Python Programming/Threading Previous: Email Index Next: Sockets Threading in python is used to run multiple threads (tasks, function calls) at the same time. Note that this does not mean, that they are executed on different CPUs. Python threads will NOT make your program faster if it already uses 100 % CPU time, probably you then want to look into parallel programming. If you are interested in parallel progamming with python, please see here [1]., time def loop1_10(): for i in range(1,10): time.sleep(1) print i thread.start_new_thread(loop1_10, ()) A Minimal Example with Object #!() Python Programming/Threading time.sleep(.2) This should output: Thread-1 Thread-2 Thread-3 Thread-4 Thread-1 Thread-2 Thread-3 Thread-4 started! started! started! started! finished! finished! finished! finished! 134. Previous: Email Index Next: Sockets References [1] http:/ / wiki. python. org/ moin/ ParallelProcessing Python Programming/Sockets Previous: Threading Index Next: GUI Programming ntps ntpms ntpt picoseconds portion of time seconds portion of time milliseconds portion of time 64-bit ntp time, seconds in upper 32-bits, picoseconds in lower 32-bits import socket import sys ..args[0]) print "Goodbye. port)) except socket. 1 = blocking 2208988800L # Thanks to F.setblocking(mode) except socket. blocking) \n # opens a socket at ip address "servername" # \arg servername = ip address to open a socket to # \arg port = port number to use # ntp uses dgram sockets instead of stream def opensocket(ipaddr.error. mode) print "Error %s" % (e. mode): # create the socket skt = socket." sys. mode) print "Error %s" % (e.AF_INET. port." sys.exit() # set the blocking mode (0=nonblocking.error. e: print "Failed to connect to server %s %d %d" % (ipaddr. 1=blocking) try: skt.. socket.exit() return(skt) #*************************************************** ## # we should get 12 long words back in network order \n # the 10th word is the transmit time (seconds since UT 1900-Jan-01 \n . port.01 135 = = = = #*************************************************** ## opensocket(servername.SOCK_DGRAM) # open the socket try: skt.connect((ipaddr. port.socket(socket. port.. 1 = blocking # 0 = non blocking.com') = 2 = 0.args[0]) print "Goodbye. e: print "Failed to set socket blocking mode for %s %d %d" %(ipaddr.apple.Lundh 123 1024 ('time.Python Programming/Sockets import time BLOCKING = 1 NONBLOCKING = 0 TIME1970 NTPPORT MAXLEN NTPSERVER SKTRDRETRYCOUNT SKTRDRETRYDLY # 0 = non blocking. data)[10] ntpps = unpack('!12I'.exit() else: print "Error: NTP." sys.error. ntpms. server = %s" %(rtrycnt.exit() ntpms = ntpps/5000000L # 1ms/200ps. we want ms ntpt = (ntps << 32) + ntpps return (ntpsocket." sys. servername): ntpsocket.. ntpps. e: rtrycnt += 1 print "Error reading non-blocking socket. ntps. msg.send(msg) rtrycnt = 0 data = 0 while (data == 0) & (rtrycnt < SKTRDRETRYCOUNT): try: data = ntpsocket.. the message to send to the ntp server def getntptime(ntpsocket. goodbye. servername) time.recv(MAXLEN) except socket.Python Programming/Sockets # I = unsigned long integer \n # ! = network (big endian) ordering # \arg \c \b ntpsocket. the socket handle to connect to # \arg \c \b msg. invalid response. goodbye.sleep(SKTRDRETRYDLY) # don't retry too often # check and see if we got valid data back if data: ntps = unpack('!12I'. retries = %s.. no data returned. data)[11] if ntps == 0: print "Error: NTP.. ntpt) Previous: Threading Index Next: GUI Programming 136 . and can be used to write full featured GNOME applications. The bare GTK+ toolkit runs on Linux.mainloop() From an object-oriented perspective one can do the following: import Tkinter class App: def __init__(self. and Mac OS X (port in progress).Button(master. It is a relatively simple to learn yet powerful toolkit that provides what appears to be a modest set of widgets. To create a very simple Tkinter window frame one only needs the following lines of code: import Tkinter root = Tkinter.washington. scrolled panes).pack() if __name__ == '__main__': root = Tkinter. Home Page [1] .e.Python Programming/GUI Programming 137 Python Programming/GUI Programming Previous: Sockets Index Next: WSGI web programming There are various GUI toolkits to start with.edu/tcc/help/lang/python/tkinter. many compound widgets can be created rather easily (i.com/library/tkinter/introduction/ <.Tk() app = App(root) root. taking care of many of the boring details such as managing memory and type casting. a Python wrapper for Tcl/Tk.edu/owen/TkinterSummary.mainloop() To learn more about Tkinter visit the following links: •. Because of its maturity and extensive documentation Tkinter has been designated as the de facto GUI for Python. comes bundled with Python (at least on Win32 platform though it can be installed on Unix/Linux and Mac machines) and provides a cross-platform GUI. text="I'm a Button.nmt. However.html <. combo-box. master): button = Tkinter.A summary • tutorial •. but the more extensive features — when combined with PyORBit and gnome-python — require a GNOME [3] install.") button.html <. Tkinter Tkinter.A reference PyGTK See also book PyGTK For GUI Programming PyGTK [1] provides a convenient wrapper for the GTK+ [2] library for use in Python programs. because the Tkinter widgets are extensible.Tk() root.astro. Windows. argv): super(App.40).App. -1. -1. It has many widgets and support classes supporting SQL.MainLoop() • wxPython [8] [7] .Show() return True if __name__ == '__main__': app = test() app.frame = frame self. (20. self). import wx class test(wx.DEFAULT_FRAME_STYLE) button = wx.show() if __name__ == "__main__": import sys app = App(sys.50). [5] wxPython Bindings for the cross platform toolkit wxWidgets Unix/Linux.exec_) PyQt [6] is a set of bindings for the cross-platform Qt application framework. and . "Hello World!". OpenGL. WxWidgets is available on Windows. "Test". XML.__init__(self.msg. Macintosh. A PyQt hello world example: from PyQt4. redirect=False) def OnInit(self): frame = wx.Python Programming/GUI Programming 138 PyQt PyQt is a wrapper around the cross-platform Qt C++ toolkit [4]. size=(100.Button(frame.QtGui import * class App(QApplication): def __init__(self. SVG. style=wx.Frame(None. 20)) self.frame. and advanced graphics capabilities.msg = QLabel("Hello.__init__(argv) self.App): def __init__(self): wx.argv) sys. pos=(50.exit(app. World!") self. PyQt v4 supports Qt4 and PyQt v3 supports Qt3 and earlier.QtCore import * from PyQt4. ui. 200. halign="center".dApp() app.loadUI("wx") class TestForm(dabo.ui.dForm): def afterInit(self): self. 40) self. evt): dabo. OnHit=self.info("Hello World!") if __name__ == '__main__': app = dabo.MainFormClass = TestForm app.btn.end() window.append(self.run() .Sizer.onButtonClick) self. and greatly simplifies the syntax. 90) button = Fl_Button(9.Position = (50.show() Fl. The "Hello World" example in pyFltk looks like: from fltk import * window = Fl_Window(100.20.label("Hello World") window.start() • Dabo [9] pyFltk pyFltk [10] is a Python wrapper for the FLTK [11]. Its UI layer wraps wxPython. a lightweight cross-platform GUI toolkit. border=20) def onButtonClick(self.ui.50) button.ui.Caption = "Test" self.Size = (100. 100.ui. It is very simple to learn and allows for compact user interfaces.180. import dabo dabo. Caption="Hello World". 50) self.Python Programming/GUI Programming 139 Dabo Dabo is a full 3-tier application framework.dButton(self.btn = dabo. org/ en/ docs/ XUL [16] http:/ / developer. riverbankcomputing. org/ [12] http:/ / of the kdebindings package. • PyXPCOM [13] provides a wrapper around the Mozilla XPCOM [14] component architecture. pygtk. com/ [10] http:/ / pyfltk. com/ Docs/ PyQt4/ html/ classes. mozilla. gtk. sourceforge. html [6] http:/ / www. com/ products/ qt [5] http:/ / www. gnome. php [13] http:/ / developer. but with the advent of libxul and XULRunner [16] this should become more feasible. co. org/ en/ docs/ XPCOM [15] http:/ / developer. riverbankcomputing. riverbankcomputing. org/ [2] http:/ / www. uk/ pyqt/ [7] http:/ / www. org/ [8] http:/ / wxpython. uk/ pykde/ index. org/ en/ docs/ PyXPCOM [14] http:/ / developer. org [4] http:/ / www. org [3] http:/ / www. thereby enabling the use of standalone XUL [15] applications in Python. wxwidgets. net/ [11] http:/ / www. Previous: Sockets Index Next: WSGI web programming References [1] http:/ / www. mozilla. mozilla. The XUL toolkit has traditionally been wrapped up in various other parts of XPCOM. mozilla. org/ [9] http:/ / dabodev. it provides a python wrapper for the KDE libraries. co.org/library/wsgiref. fltk. org/ en/ docs/ XULRunner Python Programming/WSGI web programming Previous: GUI Programming Index Next: Web Page Harvesting WSGI Web Programming External Resources Previous: GUI Programming Index Next: Web Page Harvesting .Python Programming/GUI Programming 140 Other Toolkits • PyKDE [12] . trolltech.python. This is a minimal implementation of ODBC.execute(SQL): # cursors are iterable print row.[3] pyodbc An example using the pyodbc Python package with a Microsoft Access file (although this database connection could just as easily be a MySQL database): import pyodbc DBfile = '/data/MSAccess/Music_Library. row.Artist.' for row in cursor.cursor() SQL = 'SELECT Artist.0 of the Python Database API.0.DBQ='+DBfile) cursor = conn. There are three ODBC modules for Python: 1.[2] 2.egenix. such as PostgreSQL or Microsoft Access. pyodbc: an open-source Python package (' conn = pyodbc.google.com/products/python/mxODBC/). it will likely not be developed any further.AlbumName cursor. The present version supports the Python Database API Specification v2. and conforms to Version 1.close() . The strengths of using this interface is that a Python script or module can be used on different databases by only modifying the connection string.com/p/pyodbc). 3. mxODBC: a commercial Python package ()}.connect('DRIVER={Microsoft Access Driver (*.Python Programming/Web Page Harvesting 141 Python Programming/Web Page Harvesting Previous: WSGI web programming Index Next: Database Programming Previous: WSGI web programming Index Next: Database Programming Python Programming/Database Programming Previous: Web Page Harvesting Index Next: Game Programming in Python Generic Database Connectivity using ODBC The Open Database Connectivity (ODBC) API standard allows transparent connections with any database that supports the interface. PythonWin ODBC Module: provided by Mark Hammond with the PythonWin [1] package for Microsoft Windows (only). Although it is stable. This includes most popular databases. which uses only native Python data-types and uses prepared statements for increased performance.close() conn. which features handling of DateTime objects and prepared statements (using parameters). AlbumName FROM RecordCollection ORDER BY Year. org/ http:/ / www. net/ crew/ mhammond/ win32/ Hammond.-A. python.Python Database API Specification v2. Additionally. sqlobject. 142 Postgres connection in Python import psycopg2 conn = psycopg2.next(): print i conn. External links • • • • SQLAlchemy [4] SQLObject [5] PEP 249 [6] . it behaves very similarly to the ORM in Rails. org/ dev/ peps/ pep-0249/ ). A long.cursor() cursor. for i in cursor. A. a pretty good tutorial can be found there. org/ doc/ topics/ database/ . . Lemburg. ISBN 1-56592-621-8. python. Python Programming on Win32. Elixir.close() SQLAlchemy in Action SQLAlchemy has become the favorite choice for many large Python projects that use databases. (2000)..execute("select * from test"). M. Robinson. Python. sqlalchemy. O'Reilly. org/ http:/ / Programming/Database Programming Many more features and examples are provided on the pyodbc website.0 Database Topic Guide [7] on python. http:/ / Previous: Web Page Harvesting Index Next: Game Programming in Python References [1] [2] [3] [4] [5] [6] [7] http:/ / starship.connect("dbname=test") cursor = conn.. org/ dev/ peps/ pep-0249/ http:/ / www. "Python Database API Specification v2. python. (2007).0" (http:/ / www. ActiveRecord. Along with a thin database wrapper. python. M. as well. updated list of such projects is listed on the SQLAlchemy site. fog.The second approach allows you to write Crystal Space applications entirely in Python. It's a library written in C++ with Python bindings. without any C++ coding. Now there are many projects made with Panda3D. and interact with it via the SCF ‘iScript’ interface . realtime interactive 3D and game creation and playback with cross-platform compatibility. load the ‘cspython’ plugin as you would load any other Crystal Space plugin. This software is available for free download with source code under the BSD License. post-production. rendering. Soya is available under the GNU GPL license. (2) as a pure Python module named ‘cspace’ which one can ‘import’ from within Python programs. . Building Virtual World [13]. and in which Python code can call upon Crystal Space. Track motion. The 3D game engine uses an embedded python interpreter to make 3D games. ToonTown [12]. To use the first option. The development was started by [Disney]. such as Disney's Pirate's of the Caribbean Online [11]. Crystal Space is accessible from Python in two ways: (1) as a Crystal Space plugin module in which C++ code can call upon Python code. Render to texture. Panda3D is designed in order to support a short learning curve and rapid development. with particular focus on games. animation. Animated Texture. and many others. It's written in the Pyrex programming language and uses Cal3d for animation and ODE for physics. • CrystalSpace [5] is a free cross-platform software development kit for realtime 3D graphics. Panda3D supports several features: Procedural Geometry. CS Wiki [6] 3D Game Engines written for Python Engines designed for Python from scratch. Schell Games [14] and many others. particle system. • Panda3D [10] is a 3D game engine. • Soya [8] is a 3D game engine with an easy to understand design. • PySoy [9] primaly branched from Soya 3D.Python Programming/Game Programming in Python 143 Python Programming/Game Programming in Python Previous: Database Programming Index Next: PyQt4 3D Game Programming 3D Game Engine with a Python binding • Irrlicht Engine[1] (Python binding website: [2] ) • Ogre Engine [3] (Python binding website: [4] ) Both are very good free open source C++ 3D game Engine with a Python binding. • Blender [7] is an impressive 3D tool with a fully integrated 3D graphics creation suite allowing modeling. later rewritten. org/ pypi/ pyirrlicht [3] http:/ / www. sourceforge. pyglet. net/ [2] http:/ / pypi. draw in those windows with OpenGL. schellgames. document layout. org/ [9] http:/ / www. asp . toontown. • Phil's Pygame Utilities (PGU) [15] is a collection of tools and libraries that enhance Pygame. scaling. com [15] http:/ / www. Pyglet allows programs to open multiple windows on multiple screens. hexagonal).Python Programming/Game Programming in Python 144 2D Game Programming • Pygame is a cross platform Python library which wraps SDL. org/ [4] http:/ / www. rotation. org/ wiki/ Crystal_Space [7] http:/ / www. etc. imitationpickles.) [Update 27/02/08 Author indicates he is not currently actively developing this library and anyone that is willing to develop their own scrolling isometric library offering can use the existing code in PGU to get them started. pyglet has no external dependencies (such as SDL) and is written entirely in Python. python. and play back audio and video in most formats. and a high score system. org/ [5] http:/ / www. org/ pgu/ wiki/ index [16] http:/ / www. a state engine. The libraries include a sprite and tile engine (tile. and color simultaneously. • Rabbyt [17] A fast Sprite library for Python with game development in mind. org/ [11] http:/ / disney. isometric. net/ reference/ articles/ article2259. isometric. blender.] • Pyglet [16] is a cross-platform windowing and multimedia library for Python with no external dependencies or installation requirements. even old graphics cards can produce very fast animations of 2. Pyglet is avaible under a BSD-Style license. org/ [8] http:/ / or more sprites handling position. and text rendering. With Rabbyt Anims. See Also • 10 Lessons Learned [18]. (Beta with last update March. com/ pirates/ online/ [12] http:/ / www. org [6] http:/ / en. It also provides the programmer access to key and mouse events. html rendering. pysoy. panda3d.How To Build a Game In A Week From Scratch With No Budget Previous: Database Programming Index Next: PyQt4 References [1] http:/ / irrlicht. cmu. org/ [17] http:/ / matthewmarshall. Unlike similar libraries available. go. hexagonal). soya3d. APIs to be deprecated and isometric and hexagonal support is currently Alpha and subject to change. ogre3d. edu/ bvw [14] http:/ / www. It provides many features like Sprite groups and sound/image loading and easy changing of an objects position. gamedev. GUI enhancements include full featured gui. 2007. Pyglet provides an object-oriented programming interface for developing games and other visually-rich applications for Windows. crystalspace3d. a timer. Mac OS X and Linux. org/ [10] http:/ / www. Tools include a tile editor and a level editor (tile. wikipedia. org/ projects/ rabbyt/ [18] http:/ / www. python-ogre. com/ [13] http:/ / www. QApplication(sys. most of the stuff that is done is explained in the code. play around with them. . Hello. Since Our "hello" is the only thing we use (the # so-called "MainWidget". #!/usr/bin/env python import sys from PyQt4 import Qt # We instantiate a QApplication passing the arguments of the script to it: a = Qt. To test that. the second # one is the parent widget. however..exec_() About 7 lines of code. a. knowledge of Qt4.argv) # Add a basic widget to this application: # The first argument is the text we want this QWidget to show.show() # Now we can start it. To follow this tutorial. obviously.use with caution! This tutorial aims to provide a hands-on guide to learn the basics of building a small Qt4 application in python. you should be ready to roll. Use the examples and try to change things. showing useful ways to write and structure your program. The following small program will popup a window showing "Hello world!".Python Programming/PyQt4 145 Python Programming/PyQt4 Previous: Game Programming in Python Index Next: Dbus WARNING: The examples on this page are a mixture of PyQt3 and PyQt4 . and that's about as easy as it can get. I'm using Linux in these examples and am assuming you already have a working installation of python and pyqt4. it does not have a parent. is not necessary. Popping up a window and displaying something. hello = Qt. open a python shell by simply typing python in a console to start the interactive interpreter and type >>> import PyQt4 If this doesn't yield an error message..QLabel("Hello. you should have basic python knowledge. hello. The examples in this tutorial are kept as easy as possible. world! Let's start easy. and that it should be shown. World") # . It is important that you read the source code of the example files. This is the best way to get comfortable with it. connect(hellobutton. World!" # Instantiate the button hellobutton = Qt. sayHello) # The rest is known already.exec_() Urgh.argv) # Our function to call when the button is clicked def sayHello(): print "Hello.show() a. adding structure and actually using object-orientation in it. derived from a QApplication and put the customization of the application into its methods: One method to build up the widgets and a slot which contains the code that's executed when a signal is received. World!" with a button and assign an action to it.QPushButton("Say 'Hello world!'"..None) # And connect the action "sayHello" to the event "button has been clicked" a. This assignment is done by connecting a signal. that looks like a crappy approach You can imagine that coding this way is not scalable nor the way you'll want to continue working.QApplication(sys. #!/usr/bin/env python import sys from PyQt4 import Qt class HelloApplication(Qt. We create our own application class. #!/usr/bin/env python import sys from PyQt4 import Qt a = Qt. an event which is sent out when the button is pushed to a slot.QApplication): def __init__(self. #a. Qt. then adding our widgets and finally starting . which is basically constructing a basic QApplication by its __init__ method.setMainWidget(hellobutton) hellobutton. which is an action.SIGNAL("clicked()"). args): """ In the constructor we're doing everything to get our application started.. So let's make that stuff pythonic. normally a function that is run in the case of that event.Python Programming/PyQt4 146 A button Let's add some interaction! We'll replace the label saying "Hello. show() def slotSayHello(self): """ This is an example slot.ui -o testapp_ui. What we are going to do is We compile the . the so-called "slots" """ self.""" Qt.QApplication. we're adding widgets and connecting signals from these widgets to methods of our class. Qt.exec_() def addWidgets(self): """ In this method.hellobutton. without having it messing around in the code we added.argv) 147 gui coding sucks . The way our program works can be described like this: We fill in the lineedit Clicking the add button will be connected to a method that reads the text from the lineedit. self.addWidgets() self.. a method that gets called when a signal is emitted """ print "Hello. makes a listviewitem out of it and adds that to our listview.hellobutton. Here's the heavily commented code (only works in PyQt 3: #!/usr/bin/env python from testapp_ui import TestAppUI from qt import * .slotSayHello) self. with in green letters the names of the widgets.__init__(self. World!" # Only actually do something if this script is run standalone. you can see a simple GUI.Python Programming/PyQt4 the exec_loop. we're able to change the user interface afterwards from Qt designer..hellobutton = Qt.None) self.connect(self. but we're also able to import this program without actually running # any code. Clicking the deletebutton will delete the currently selected item from the listview. if __name__ == "__main__": app = HelloApplication(sys. so we can test our # application.SIGNAL("clicked()").py makes a python file from it which we can work with. pyuic testapp_ui. so we want to use Qt3 Designer for creating our GUI.QPushButton("Say 'Hello world!'". args) self. In the picture.ui file from Qt designer into a python class We subclass that class and use it as our mainWidget This way. SIGNAL("clicked()").setMainWidget(self. # we grey it out.maindialog = TestApp(None) self.__init__(self.parent) self. args): """ In the constructor we're doing everything to get our application started. then adding our widgets and finally starting the exec_loop.self.show() self. text = self.maindialog) self.parent): # Run the parent constructor and connect the slots to methods. 148 .deletebutton.text() # if the lineedit is not empty. TestAppUI. but this way it's easier to add more dialogs or widgets.lineedit._connectSlots() # The listview is initially empty._slotDeleteClicked) def _slotAddClicked(self): # Read the text from the lineedit. we could in fact leave # that one out.self. so the deletebutton will have no effect.args) # We pass None since it's the top-level widget.maindialog.deletebutton. self.__init__(self.connect(self.connect(self. self.Python Programming/PyQt4 import sys class HelloApplication(QApplication): def __init__(self.SIGNAL("clicked()").setEnabled(False) def _connectSlots(self): # Connect our two methods to SIGNALS the GUI emits. which is basically constructing a basic QApplication by its __init__ method.""" QApplication.addbutton.exec_loop() class TestApp(TestAppUI): def __init__(self. self._slotAddClicked) self. self.listview.ac. Note: The previous version of this page (aplicable to pyqt3) is/was available at. so after having trained a little. The first 3 examples in this tutorial have been created using PyQt4.50. but it's a great learning tool. "qt:qbutton directly takes you to the right API documentation page.lineedit.listview. we enable it.Python Programming/PyQt4 if len(text): # insert a new listviewitem . You can test how a widget looks like.setEnabled(False) if __name__ == "__main__": app = HelloApplication(sys.yu/~gospodar Previous: Game Programming in Python Index Next: Dbus . disable the deletebutton.setEnabled(True) def _slotDeleteClicked(self): # Remove the currently selected item from the listview. self.org/?id=pyqt This document is published under the GNU Free Documentation License. lvi = QListViewItem(self.takeItem(self. so [alt]+[F2].currentItem()) # Check if the list is empty ..clear() # The deletebutton might be disabled.listview) # with the text from the lineedit and .bg. 30 November 2006 (UTC) by Saša Tomić. konqueror's default shortcut is qt:[widgetname].deletebutton.if yes. see what's available in Qt and have a look at properties you might want to use..childCount() == 0: self.argv) 149 useful to know Creating the GUI in Qt designer does not only make it easier creating the GUI.161 10:40. the last one uses syntax that only works with PyQt3. too. The API is translated pretty straightforward.88..setText(0. --84. The C++ API documentation is also a very useful (read: necessary) tool when working with PyQt. self. lvi.etf. Trolltech's doc section has much more documentation which you might want to have a look at.listview. you'll find the developers API docs one of the tools you really need.text) # clear the lineedit..deletebutton. since we're sure that there's now # at least one item in it.. When working from KDE. if self. The object passed back is not a full object: it just refers to the service's copy of the object. For example.get_object('com. We do this by creating an interface object.mycorp.Python Programming/Dbus 150 Python Programming/Dbus Previous: PyQt4 Index Next: pyFormex Dbus is a way for processes to communicate with each other. Services attach themselves to these buses. Services on the system bus affect the whole system. It is called a proxy object. cell_a2 = dbus.mycorp. Another example is the network-manager [2] service that publishes which internet connection is active. programs like Pidgin [1] instant messenger allow other programs to find out or change the user's status (Available.SpreadsheetCell') Whatever methods are set up for this type of object can be called: cell_a2. etc). Away. the format is normally that of a reverse domain name: an example for a spreadsheet program called "CalcProgram" from "My Corp Inc. import dbus sys_bus = dbus. Services publish objects using slash-seperated paths (this is similar to webpages). like Pidgin." could be "com.CalcProgram. Someone on dbus can request an object if they know this path.CalcProgram'. '/spreadsheet1/cells/a2') Before the proxy object can be used.SystemBus() Objects and interfaces Services attached to a bus can be contacted using their well known name. Buses Messages are sent along buses. proxy_for_cell_a2 = sys_bus.Interface(proxy_for_cell_a2. There are two main buses.CalcProgram".getContents() . and allow clients to pass messages to and from them. 'com. we need to specify what type of object it is. While this could be any string. such as providing information about the network or disk drives.mycorp. Services on the session bus provide access to programs running on the desktop. Programs that sometimes connect to the internet can then pick the best time to download updates to the system. the system bus and session bus. SystemBus() hal_manager_object = bus. dbus.mycorp.get_object( 'org.freedesktop.Manager') # calling method upon interface print hal_manager_interface. 'org. '/org/freedesktop/Hal/Manager') hal_manager_interface = dbus. Older library versions may not have the same interface.get_dbus_method('GetAllDevices'.Manager') Introspecting an object import dbus bus = dbus. # service '/org/freedesktop/Hal/Manager' # published object ) introspection_interface = dbus.GetAllDevices() # accessing a method through 'get_dbus_method' through proxy object by specifying interface method = hal_manager_object.Hal. ) .CalcProgram.Hal.mycorp.Hal'.Hal'.Interface( hal_manager_object. 'org.freedesktop.0.get_object('org.freedesktop.freedesktop.SystemBus() hal_manager_object = bus.83. Calling an interface's methods / Listing HAL Devices import dbus bus = dbus.GetAllDevices(dbus_interface='org.SpreadsheetCell Identifies what type of object we expect Some examples These examples have been tested with dbus-python 0.Hal.INTROSPECTABLE_IFACE.Python Programming/Dbus 151 Name Example Description Identifies the application Identifies an object published by a service service well known name com.freedesktop.CalcProgram path of an object interface /spreadsheet1/cells/a2 com.Manager') print method() # calling method upon proxy object by specifying the interface to use print hal_manager_object.Interface(hal_manager_object. html # get an object called / in org.Interface(raw_server.Avahi object.freedesktop.freedesktop.org/doc/dbus-tutorial. get the org.Server') # The so-called documentation is at /usr/share/avahi/introspection/Server.freedesktop. wikipedia.pidgin.lisp.GetVersionString() print server.Avahi.html. server = dbus.org/display/45824 Previous: PyQt4 Index Next: pyFormex References [1] http:/ / en.ca/diary/2007/04/rough_notes_python_and_dbus.Server interface to our org.Avahi'.Avahi to talk to raw_server = sys_bus.Python Programming/Dbus # Introspectable interfaces define a property 'Introspect' that # will return an XML string that describes the object's interface interface = introspection_interface.freedesktop. org/ wiki/ NetworkManager .get_object('org.GetHostName() References • • • • print interface 152 Avahi import dbus sys_bus = dbus.im/wiki/DbusHowto. 'org. '/') # objects support interfaces. wikipedia.introspect print server print server.freedesktop. org/ wiki/ Pidgin_%28software%29 [2] http:/ / en.freedesktop. c) #include <Python. printf("Hello %s!\n".html A minimal example The minimal example we will create now is very similar in behaviour to the following python snippet: def say_hello(name): "Greet somebody. If you have any problems. on the dicussion page). which allows the generation. Linux is used for building (feel free to extend it for other Platforms).org/api/api.org/ext/ext.h> static PyObject* say_hello(PyObject* self." print "Hello %s!" % name The C source code (hellomodule. Its uses include automated 3D design and finite-element preprocessing. I will check back in a while and try to sort them out. Using the Python/C API •. Previous: Dbus Index Next: Extending with C References [1] http:/ / pyformex. "s".g. &name)) return NULL. de/ Python Programming/Extending with C Previous: pyFormex Index Next: Extending with C++ This gives a minimal Example on how to Extend Python with C. and operation of 3D geometric models using mathematical operations. berlios.python.Python Programming/pyFormex 153 Python Programming/pyFormex Previous: Dbus Index Next: Extending with C pyFormex [1] is a module for Python. manipulation.html •. .python. please report them (e. PyObject* args) { const char* name. if (!PyArg_ParseTuple(args. name). PyMODINIT_FUNC inithello(void) { (void) Py_InitModule("hello". say_hello."}.c -I/PythonXY/include gcc -shared hellomodule. 0.dll where XY represents the version of Python. type: gcc -c hellomodule. } Building the extension module with GCC for Linux To build our extension module we create the file setup. ext_modules = [module1]) Now we can build our module with python setup. Building the extension module with GCC for Microsoft Windows Microsoft Windows users can use MinGW to compile this from cmd. (This method does not need an extension module file). NULL} }. An alternate way of building the module in Windows is to build a DLL.py build -c mingw32 The module hello.o -L/PythonXY/libs -lpythonXY -o hello. .0'. as shown above.core import setup. sources = ['hellomodule.c']) setup (name = 'PackageName'. Extension module1 = Extension('hello'. such as "24" for version 2.win32-x.py build The module hello. {NULL.so will end up in build/lib. From cmd. type: python setup. NULL. HelloMethods).Python Programming/Extending with C 154 Py_RETURN_NONE.pyd will end up in build\lib.linux-i686-x. version = '1.y. which is a Python Dynamic Module (similar to a DLL). } static PyMethodDef HelloMethods[] = { {"say_hello". Assuming gcc is in the PATH environment variable. description = 'This is a demo package'.py like: from distutils.4.exe using a similar method to Linux user. METH_VARARGS.exe.y. "Greet somebody. h> int _fib(int n) { if (n < 2) return n.dll 155 Using the extension module Change to the subdirectory where the file `hello. "Calculate the Fibonacci numbers. {NULL. int n.c) #include <Python. METH_VARARGS.c /Ic:\Python24\include c:\Python24\libs\python24. } . NULL. 0. We will use cl.exe from a command prompt instead: cl /LD hellomodule. PyObject* args) { const char *command. >>> import hello >>> hello. fib. } static PyObject* fib(PyObject* self. return Py_BuildValue("i".lib /link/out:hello.so` resides. "i". &n)) return NULL. else return _fib(n-1) + _fib(n-2).Python Programming/Extending with C Building the extension module using Microsoft Visual C++ With VC8 distutils is broken. if (!PyArg_ParseTuple(args. NULL} }. In an interactive python session you can use the module as follows.say_hello("World") Hello World! A module for calculating fibonacci numbers The C source code (fibmodule. } static PyMethodDef FibMethods[] = { {"fib". PyMODINIT_FUNC initfib(void) { (void) Py_InitModule("fib". _fib(n))."}. FibMethods). gluing it all together. description = 'This is a demo package'.h> void say_hello(const char* name) { printf("Hello %s!\n". sources = ['fibmodule.c*/ #include <stdio. name).Python Programming/Extending with C The build script (setup.c']) setup (name = 'PackageName'.c`.core import setup.c hello_wrap. swig -python hello. To follow this path you need to get SWIG [1] up and running first. } /*hello.c -I/usr/include/python2. Extension module1 = Extension('fib'.4/ Now linking and we are done! gcc -shared hellomodule. >>> import hello >>> hello.i This gives us the files `hello. ext_modules = [module1]) How to use it? >>> import fib >>> fib. The next step is compiling (substitute /usr/include/python2. /*hellomodule.i*/ %module hello extern void say_hello(const char* name). After that create two files. gcc -fpic -c hellomodule.say_hello("World") Hello World! .fib(10) 55 156 Using SWIG Creating the previous example using SWIG is much more straight forward.o hello_wrap. version = '1.4/ with the correct path for your setup!). Now comes the more difficult part.0'.py) from distutils. First we need to let SWIG do its work.py` and `hello_wrap.so The module is used in the following way.o -o _hello. Python comes bundled with the Boost C++ Libraries [2]. } #include <boost/python/module. libraries = ["boost_python"]) ]) Now we can build our module with . void say_hello(const char* name) { cout << "Hello " << name << "!\n". The C++ source code (hellomodule. Boost. swig. } setup.Python Programming/Extending with C 157 Previous: pyFormex Index Next: Extending with C++ References [1] http:/ / #!/usr/bin/env python from distutils.cpp"].cpp) #include <iostream> using namespace std.extension import Extension setup(name="blah". say_hello). BOOST_PYTHON_MODULE(hello) { def("say_hello".Python [1] is the de facto standard for writing C++ extension modules. ext_modules=[ Extension("hello". org/ Python Programming/Extending with C++ Previous: Extending with C Index Next: Extending with Pyrex Boost.hpp> using namespace boost::python.core import setup from distutils. ["hellomodule.hpp> #include <boost/python/def. org/ libs/ python/ doc/ [2] http:/ /` will end up in e. org/ Python Programming/Extending with Pyrex Previous: Extending with C++ Index Next: Extending with ctypes Previous: Extending with C++ Index Next: Extending with ctypes .py build The module `hello. 158 Using the extension module Change to the subdirectory where the file `hello.say_hello("World") Hello World! Previous: Extending with C Index Next: Extending with Pyrex References [1] http:/ / www. In an interactive python session you can use the module as follows.4`. boost. boost. >>> import hello >>> hello.g `build/lib.Python Programming/Extending with C++ python setup.linux-i686-2.so` resides. Getting Return Values ctypes assumes. If all goes well. but it serves one of the primary reasons for extending Python: to interface with external C code. This is not technically extending Python. printf.so' # If you're on a UNIX-based system libName = 'msvcrt. the functions inside the library are already usable as regular Python calls. Every ctypes function has an attribute called restype. which allows you to load in dynamic libraries and call C functions. For example. it automatically casts the function's return value to that type. that any given function's return type is a signed integer of native size. and delete the other. Sometimes you don't want the function to return anything. by default. Common Types ctypes name None c_bool c_byte c_char c_char_p c_double c_float c_int c_long c_longlong c_short c_ubyte c_uint void C99 _Bool signed char signed char char * double float signed int signed long signed long long signed short unsigned char unsigned int C type Python type None bool int str str float float int long long long int int length of one Notes the None object . you would use this: from ctypes import * libName = 'libc. World!\n") Of course.CDLL function. you must use the libName line that matches your operating system. After you load the library. and other times.5 and above).Python Programming/Extending with ctypes 159 Python Programming/Extending with ctypes Previous: Extending with Pyrex Index ctypes[1] is a foreign function interface module for Python (included with Python 2.dll' # If you're on Windows libc = CDLL(libName) libc. you should see the infamous Hello World string at your console. you want the function to return other types.printf("Hello. When you assign a ctypes class to restype. if we wanted to forego the standard Python print statement and use the standard C library function. Basics A library is loaded using the ctypes. Python Programming/Extending with ctypes 160 unsigned long long c_ulong c_ulonglong unsigned long long long c_ushort c_void_p c_wchar c_wchar_p unsigned short void * wchar_t wchar_t * int int unicode unicode length of one Previous: Extending with Pyrex Index References [1] http:/ / python. net/ crew/ theller/ ctypes/ . org/w/index. Darklama. 9 anonymous edits Python Programming/Data types Source:. Jesdisciple. Webaware. Rdnk.org/w/index.Z-man.Z-man.Z-man. Withinfocus. Alexdong. LDiracDelta. Mr. Sigma 7. Fef. Thunderbolt16. 3 anonymous edits Python Programming/Tips and Tricks Source:. Mr. Dobau. Withinfocus. Monobi. Hypergeek14.wikibooks. Darklama.wikibooks. Dragonecc. The djinn.wikibooks. CWii. Monobi.wikibooks.org/w/index. Ponstic. Hypergeek14. Darklama.php?oldid=1796615 Contributors: Beland. Sigma 7. Hawk-McKain. Hypergeek14. Sigma 7.org/w/index.wikibooks. Flarelocke.php?oldid=1893189 Contributors: AdriMartin. Jonnymbarnes. Mr.php?oldid=1811180 Contributors: Alexforcefive. CWii.Z-man. DavidRoss. Mr. IO. Jesdisciple. 3 anonymous edits Python Programming/Creating Python programs Source:. Mshonle. Thunderbolt16. Yath. Rdnk. Darklama. BobGibson.org/w/index. 1 anonymous edits Python Programming/Errors Source:. Sigma 7.org/w/index. Darklama.php?oldid=1647561 Contributors: Adeelq. The djinn. 10 anonymous edits Python Programming/Databases Source:. Hypergeek14.wikibooks.org/w/index.wikibooks. Dlrohrer2003. Webaware. Wesley Gray. Withinfocus.Z-man. Irvin. Webaware.Z-man. Rabidgoldfish. Mr.php?oldid=1738642 Contributors: Artevelde. Hannes Röst. Thunderbolt16.php?oldid=1893212 Contributors: I-20. DavidRoss.Z-man.org/w/index.Z-man. CWii.php?oldid=1511185 Contributors: Artevelde. Mr. Webaware. Richard001. CWii. Mithrill2002. Rancid. 15 anonymous edits Python Programming/Basic Math Source:. 27 anonymous edits Python Programming/Tuples Source:. Pjerrot. Yath.php?oldid=1808711 Contributors: Hannes Röst. Jomegat. Hakusa.Z-man. Artevelde. JackPotte. 10 anonymous edits Python Programming/Flow control Source:. Hannes Röst. 30 anonymous edits .php?oldid=1410921 Contributors: Hypergeek14. Chenhsi. Thunderbolt16. Gvdraconatur.wikibooks. ElieDeBrauwer. Capi. Darklama.sha.Z-man. The djinn. ElieDeBrauwer.org/w/index. ElieDeBrauwer. Jguk. Jguk. Mr. Dbolton. 2 anonymous edits Python Programming/Operators Source:. Jguk. NithinBekal. Mr.org/w/index. Mr. The Kid. DavidRoss. DavidRoss. Thunderbolt16. Sigma 7. Dragonecc. Greyweather. 4 anonymous edits Python Programming/Networks Source:. Jguk.php?oldid=1639579 Contributors: Adamnelson. Irvin.wikibooks. 8 anonymous edits Python Programming/Basic syntax Source:. 9 anonymous edits Python Programming/Numbers Source:. Hypergeek14. Artevelde.org/w/index. Webaware.wikibooks.org/w/index. Sigma 7. 4 anonymous edits Python Programming/Self Help Source:. Sigma 7. Brian McErlean. Chuckhoffmann.php?oldid=1886374 Contributors: Dragonecc. Cat1205123. Legoktm.org/w/index. Withinfocus. Fishpi. Jguk. DavidRoss. Yath. Hypergeek14.org/w/index. Darklama. Mr.php?oldid=1796653 Contributors: Beland. Remote. GeorgePatterson.php?oldid=1428307 Contributors: Kuzux. Microdot. FerranJorba. Gzorg. Robm351.wikibooks. ElieDeBrauwer. LDiracDelta. Webaware. The Kid.php?oldid=1758135 Contributors: Albmont. Remi0o. Remote. Marjoe.php?oldid=1721616 Contributors: Mr. Member. Hrandiac. Jguk. ManuelGR.wikibooks.org/w/index. Flarelocke. Webaware. Mattzazami. Mr. Jguk. Jguk.php?oldid=1875314 Contributors: CWii. The Kid.wikibooks. Withinfocus. Piperrob.wikibooks. Withinfocus. MarceloAraujo. Sigma 7.wikibooks. Gvdraconatur. Jesdisciple. Horaceabenga. IO.php?oldid=1799118 Contributors: CWii. Wenhaosparty. Richard001. Mithrill2002. Mr. Richard001.wikibooks. Artevelde.Z-man. Webaware.wikibooks. Webaware. Remote. Bluecanary. Chesemonkyloma. Mr.Z-man. Jguk.php?oldid=1796630 Contributors: Amrik. Quartz25.php?oldid=1872500 Contributors: Artevelde. Thunderbolt16. Jguk.org/w/index. Svenstaro. DavidRoss. Sigma 7.wikibooks. Hannes Röst. Mr. 13 anonymous edits Python Programming/Sets Source:. Webaware. Darklama. Webaware.org/w/index. 2 anonymous edits Python Programming/Modules and how to use them Source: Contributors: Alexander256. Leopold augustsson. Webaware. Hypergeek14. Offpath. Irvin. Artevelde.php?oldid=1410932 Contributors: Hypergeek14.org/w/index. Pazabo.org/w/index. Withinfocus. 35 anonymous edits Python Programming/Loops Source:. Withinfocus. 8 anonymous edits Python Programming/Dictionaries Source:. Flarelocke. Icewedge.org/w/index. 9 anonymous edits Python Programming/Interactive mode Source:. Flarelocke.Z-man. Dragonecc. Jguk. Jguk. 2 anonymous edits Python Programming/Namespace Source:. Mediocretes.php?oldid=1410936 Contributors: Adriatikus.wikibooks. Beland. CWii. Withinfocus. Sigma 7. Niflhiem.php?oldid=1667221 Contributors: Artevelde.wikibooks. ElieDeBrauwer. Beland. Mr. Silroquen. The Kid. Yath. Jguk.wikibooks. Jguk.php?oldid=1430705 Contributors: CWii. Keplerspeed. BobGibson.Z-man. Panic2k4. Jesdisciple. Webaware. Mr. 11 anonymous edits Python Programming/Text Source:. Webaware. Fry-kun. CWii. Darklama. CWii.sha.Z-man. Withinfocus. Withinfocus. Darklama. Mr. Webaware. Daemonax.php?oldid=1402487 Contributors: ArrowStomper. Pereirai. Jesdisciple. Monobi.php?oldid=1810270 Contributors: Artevelde. Mr. Withinfocus.org/w/index. Deep shobhit. Gabrielmagno. Sigma 7. MMJ. Mr. Webaware. Mr.php?oldid=1786943 Contributors: Artevelde.sha.wikibooks. Thunderbolt16. Sigma 7. Thunderbolt16.org/w/index.Z-man.php?oldid=1841460 Contributors: Artevelde. 13 anonymous edits Python Programming/Getting Python Source:. Beland. Leopold augustsson. 1 anonymous edits Python Programming/Object-oriented programming Source:. Sigma 7.Z-man. Cspurrier. Piperrob. Remote.wikibooks.org/w/index. ElieDeBrauwer. Thunderbolt16.org/w/index. Gasto5. 9 anonymous edits Python Programming/User Interaction Source:. 17 anonymous edits Python Programming/Conditional Statements Source:. 9 anonymous edits Python Programming/Source Documentation and Comments Source:. 88 anonymous edits Python Programming/Lists Source:. Thunderbolt16.Article Sources and Contributors 161 Article Sources and Contributors Python Programming/Overview Source:. Artevelde. Jguk. Withinfocus.org/w/index. Flarelocke. LDiracDelta. Webaware. IO. Singingwolfboy. Benrolfe. Remote.org/w/index. Mithrill2002. Monobi. Jguk. 7 anonymous edits Python Programming/Strings Source:. 5 anonymous edits Python Programming/Files Source:. Moralist. Sigma 7.org/w/index. The djinn.php?oldid=1891782 Contributors: CWii. Remote.Z-man. Singingwolfboy.wikibooks. Withinfocus. Dragonecc. Jguk. BobGibson. QuiteUnusual. BobGibson. 11 anonymous edits Python Programming/Sequences Source:. Richard001. Mr.Z-man. MyOwnLittlWorld.php?oldid=1738665 Contributors: Artevelde.org/w/index. Nikai.wikibooks.wikibooks. Dbolton.wikibooks. Remote. Flarelocke. Tecky2. Mr.org/w/index. Piperrob. Jguk.org/w/index. Singingwolfboy. Withinfocus.wikibooks. Darklama. Hypergeek14. Leopold augustsson.org/w/index. 3 anonymous edits Python Programming/Internet Source:. Monobi.php?oldid=1753061 Contributors: BoomShaka.wikibooks. Yath. Quartz25.php?oldid=1867990 Contributors: Artevelde. Monobi. Leopold augustsson.php?oldid=1741352 Contributors: Chelseafan528. 10 anonymous edits Python Programming/Decision Control Source:. Capi. Mr.Z-man.wikibooks. 40 anonymous edits Python Programming/Setting it up Source:. Nikai. php?oldid=1559332 Contributors: CaffeinatedPonderer.wikibooks.php?oldid=1661792 Contributors: Artevelde.org/w/index. Cburnett. Darklama. 15 anonymous edits Python Programming/Dbus Source:. Darklama. Nikai. Pingveno. Withinfocus. Mr. Withinfocus. Sol. N313t3.Z-man. Flarelocke. Withinfocus. Hagindaz. Mr.wikibooks. 40 anonymous edits Python Programming/PyQt4 Source:. Behnam. LDiracDelta. Darklama.php?oldid=1691989 Contributors: Danh. Suchenwi.php?oldid=1804360 Contributors: Artevelde.php?oldid=1800239 Contributors: Darklama.php?oldid=1420988 Contributors: CWii. Webaware. Microdot. Withinfocus.harvey.org/w/index. Auk. 5 anonymous edits Python Programming/pyFormex Source:. Myururdurmaz.wikibooks. Edleafe. Webaware. Webaware.php?oldid=1758086 Contributors: Albmont.php?oldid=1410956 Contributors: Hypergeek14. Herbythyme.Z-man Python Programming/Extending with ctypes Source:. N313t3.php?oldid=1618744 Contributors: Artevelde. Withinfocus. Quartz25. Darklama. Guanaco. Withinfocus.wikibooks. Quartz25.php?oldid=1873695 Contributors: Adrignola. Webaware.org/w/index.Z-man. Artevelde. Jguk. Withinfocus.php?oldid=1484385 Contributors: Beland. 30 anonymous edits Python Programming/Extending with C++ Source:. Betalpha. Thunderbolt16. Jguk.php?oldid=1410942 Contributors: Artevelde.php?oldid=1410971 Contributors: CaffeinatedPonderer.wikibooks.org/w/index.wikibooks. Jguk. MarceloAraujo.org/w/index. Mr.org/w/index. CWii. CWii. Jguk.wikibooks. Webaware. Albmont. The Kid. Withinfocus. Webaware. The Kid. Mr.Z-man.org/w/index.Z-man Python Programming/Database Programming Source:. 2 anonymous edits Python Programming/Extending with Pyrex Source:. Betalpha. Jguk.wikibooks. Webaware.Z-man. Derbeth. The djinn.org/w/index.php?oldid=1854836 Contributors: Hannes Röst. Mr. Darklama. Withinfocus.wikibooks. Mr. Jguk.wikibooks. Darklama.Z-man. Mr. Quartz25. Howipepper.php?oldid=1629564 Contributors: Adrignola.wikibooks. NithinBekal. The Kid.Z-man Python Programming/Extending with C Source:. Eric Silva. 4 anonymous edits Python Programming/Decorators Source:. 5 anonymous edits Python Programming/XML Tools Source:. Perey.Z-man.wikibooks. Hypergeek14.org/w/index. Withinfocus. Mr. Jonathan Webley.org/w/index.Z-man.Z-man.org/w/index. Jerf.wikibooks. Hypergeek14. Jguk. Webaware. Jguk. Monobi. The djinn.org/w/index.org/w/index. Flarelocke.Z-man.org/w/index. Sasa. Artevelde.php?oldid=1410967 Contributors: CWii.php?oldid=1752675 Contributors: Codesmith111. Webaware. Flarelocke. Kernigh. Pavlix. Mr.php?oldid=1810615 Contributors: Ahornedal.Z-man.php?oldid=1410945 Contributors: Artevelde. Flarelocke.org/w/index. Pdilley.php?oldid=1420990 Contributors: Mr.php?oldid=1410968 Contributors: CWii. H2g2bob.wikibooks. Mr. Qwertyus. Howipepper. Jguk. Hypergeek14. The djinn. 39 anonymous edits Python Programming/MetaClasses Source:. Apeigne. 28 anonymous edits Python Programming/WSGI web programming Source:. CWii. Webaware. Hagindaz.wikibooks.wikibooks.org/w/index. Mr.org/w/index.org/w/index. Mr. 3 anonymous edits Python Programming/Exceptions Source:. Hypergeek14. MarceloAraujo. Darklama. Withinfocus. Flarelocke.Z-man. Jguk. 20 anonymous edits Python Programming/Modules Source:. Hypergeek14. Hypergeek14.php?oldid=1681118 Contributors: Albmont. Mr. Mr. Driscoll. 18 anonymous edits Python Programming/Input and output Source:. DavidCary. Jguk. Withinfocus. Mr.Z-man. Webaware.php?oldid=1410963 Contributors: CaffeinatedPonderer.wikibooks. Webaware 162 .Z-man.org/w/index.Z-man. Gutworth. JackPotte. Wilbur.Z-man Python Programming/Web Page Harvesting Source:. Flarelocke. Tobych. Dragonecc. Qwertyus.org/w/index.wikibooks.Z-man. Mwtoews. Withinfocus.wikibooks. 6 anonymous edits Python Programming/Classes Source:. Withinfocus. Webaware.php?oldid=1853171 Contributors: CWii. 2 anonymous edits Python Programming/GUI Programming Source:. Mr. Mr. Darklama. Darklama.wikibooks. Jguk. WikiNazi. 2 anonymous edits Python Programming/Regular Expression Source:. Mwtoews. Maxim kolosov. Hypergeek14.wikibooks. Microdot. 2 anonymous edits Python Programming/Scoping Source: Python Programming/Threading Source: Contributors: Dangets. Mr.Z-man. Mwtoews. Convex. Hypergeek14.org/w/index.org/w/index. Panic2k4. Az1568. Mr. 3 anonymous edits Python Programming/Game Programming in Python Source:. Baijum81.php?oldid=1759216 Contributors: Albmont. Tedzzz1. Mr. Withinfocus. Mr. Jguk.org/w/index. 11 anonymous edits Python Programming/Sockets Source:. Jguk.Z-man. Jguk. The djinn. Webaware. Darklama. Webaware. Hannes Röst. Jguk.Article Sources and Contributors Python Programming/Functions Source:. Jerf. Hannes Röst. 7 anonymous edits Python Programming/Standard Library Source:. Wilsondavidc Python Programming/Email Source:. EDUCA33E.png License: unknown Contributors: Abu badali. Actam.org/w/index. Airon90.wikibooks.svg Source:. CyberSkull. Licenses and Contributors 163 Image Sources.svg License: unknown Contributors: El T .png Source:. Juiced lemon.wikibooks. Rocket000.org/w/index. It Is Me Here.php?title=File:Crystal_Clear_action_bookmark. Tiptoety.php?title=File:Information_icon. Anime Addict AA. 2 anonymous edits Image:Information icon. Licenses and Contributors Image:Crystal_Clear_action_bookmark.Image Sources. 0 Unported http:/ / creativecommons.License 164 License Creative Commons Attribution-Share Alike 3. 0/ . org/ licenses/ by-sa/ 3.
https://www.scribd.com/doc/60725528/Python-Programming
CC-MAIN-2017-26
en
refinedweb
Code Style¶ Python imports¶ isort enforces the following Python global import order: from __future__ import ... - Python standard library - Third party modules - Local project imports (absolutely specified) - Local project imports (relative path, eg: from .models import Credentials) In addition: Each group should be separated by a blank line. Within each group, all import ...statements should be before from ... import .... After that, sort alphabetically by module name. When importing multiple items from one module, use this style: from django.db import (models, transaction) The quickest way to correct import style locally is to let isort make the changes for you - see running the tests. Note: It’s not possible to disable isort wrapping style checking, so for now we’ve chosen the most deterministic wrapping mode to reduce the line length guess-work when adding imports, even though it’s not the most concise.
http://treeherder.readthedocs.io/code_style.html
CC-MAIN-2017-26
en
refinedweb
This extension allows you to use a standard interface for GeoCoding APIs. As well as to auto generate a Yahoo or Google map of the GeoCoded location. Currently supported APIs are Google, GeoCoder.us, and Yahoo. protected/extensions Register for an API Key Google key: Yahoo key: See the following code examples: Standalone Yii::import('application.extensions.geocoder.GeoCoder'); $geocode = new GeoCoder; $geocode->init(); $geocode->setApiKey('<your API key>'); // As of 1.0.2 $geocode->setDriver('<your driver>'); // 'google' or 'yahoo' $result = $geocode->query('Las Vegas, NV 89103'); Application Component 'components' => array( ... 'geocoder' => array( 'class' => 'application.extensions.geocoder.GeoCoder', 'api_key' => '<your API key>', 'api_driver' => '<your driver>', // 'google' or 'yahoo' ), ... ) $result = Yii::app()->geocoder->query('Las Vegas, NV 89103'); Summary The map rendering is handled by the GeoCode_Result class. It uses its own render functions to generate the maps. It also requires javascript to be enabled. Map Types The map types that are rendered need to be passed to the view. These are constants as defined by the map supplier. Only include the constant name, do NOT include namespaces, etc. Caveats It is possible to change the map provider that is used for rendering a specific GeoCode_Result by passing an optional 3rd parameter to the renderMap function with the name of the provider. However, because some map APIs (eg. Yahoo) require an API key to validate access, these maps can only be rendered from a Result derived from their respective driver. Because this is using v3 of the Google Maps API, it does not require an API key to access the javascript. Therefore, a google map can be rendered from any Result object. The same can not be said for the other map providers. Usage Create an empty div in your HTML with the id of "map_canvas", then use the following code: Yahoo Map Example // $result is a GeoCode_Result object from a Yahoo Driver $result->renderMap('map_canvas', array( 'mapType' => 'YAHOO_MAP_REG' )); Google Map Example // $result is a GeoCode_Result object from a Google Driver $result->renderMap('map_canvas', array( 'mapTypeId' => 'ROADMAP', 'zoom' => 13 )); Note: Some browsers will not render the contents of the canvas and the maps will appear to be hidden. To fix this, add a new CSS entry to main.css that will force the browser to give the canvas a width and height. #map_canvas { width: 500px; height: 300px; } As of version 1.0.4 it is now possible to render multiple points to the same map. This can be accomplished in two ways: 1) by rendering multiple results to the same container, 2) by manually specifying the lat/lon where the marker is to be placed. Example // $result is an array of GeoCode_Result objects from a Google Driver $result[0]->renderMap('map_canvas', array( 'mapTypeId' => 'ROADMAP', 'zoom' => 13 )); // Render the second result to the same map // Any options passed to the function will be ignored // since this canvas has already been initialized $result[1]->renderMap('map_canvas'); // Render a point manually to that same canvas // Arguments are in this order because if no canvas is // specified, it defaults to using the last one created $result[0]->renderPoint($my_lat, $my_lon, 'map_canvas'); Total 3 comments when i use the GeoCoder extension with the google driver on the accordion effect of the pogostick extension it crach the browser I think that there is a style coflict This is a good extension. It does what it should. But maybe some suggestions: I have never used the google api before. It was quite annoying to figure out what constants are valid and where they are documented. Maybe you could point your users to it (in your documentation:). I also added some "nice to have" things into the code. First I added a event in the point-view to center my map on a click of the marker:You have all these information alrdy inside the view and I found it quite useful ;) I also added a options-variable to the renderPointer-function (maybe not everyone wants the pointer to be clickable or whatever). Also a good addition might be the ability to add a InfoWindow into the map. I just copied the renderPoint-function into a new one (the option-array must contain a content-field, which is used for the window):and the view (I found it quite dirty to use "gmap" and "marker" as predefined elements, but you did the same in the point-view (only gmap in there ;) ) and I don't wanted it more complicated just for me ^^): maybe you or someone else find these things also useful. Thanks for share! is so good! Please login to leave your comment.
http://www.yiiframework.com/extension/geocoder/
CC-MAIN-2017-26
en
refinedweb
#include <TeamBalancer.h> Automatically handles transmission and resolution of team selection, including team switching and balancing. Usage: TODO If ID_TEAM_BALANCER_REQUESTED_TEAM_CHANGE_PENDING is returned after a call to RequestSpecificTeam(), the request will stay in memory on the host and execute when available, or until the teams become locked. You can cancel the request by calling CancelRequestSpecificTeam(), in which case you will stay on your existing team. If you called RequestSpecificTeam() or RequestAnyTeam() with a value for memberId that Has since been deleted, call DeleteMember(). to notify this plugin of that event. Not necessary with only one team member per system Returns your team. As your team changes, you are notified through the ID_TEAM_BALANCER_TEAM_ASSIGNED packet in byte 1. Returns UNASSIGNED_TEAM_ID initially Called when a connection is dropped because the user called RakPeer::CloseConnection() for a particular system Reimplemented from RakNet::PluginInterface2. OnReceive is called for every packet. Reimplemented from RakNet::PluginInterface2. Allow host to pick your team, based on whatever algorithm it uses for default team assignments. This only has an effect if you are not currently on a team (GetMyTeam() returns UNASSIGNED_TEAM_ID) Set your requested team. UNASSIGNED_TEAM_ID means no team. After enough time for network communication, ID_TEAM_BALANCER_SET_TEAM will be returned with your current team, or If team switch is not possible, ID_TEAM_BALANCER_REQUESTED_TEAM_CHANGE_PENDING or ID_TEAM_BALANCER_TEAMS_LOCKED will be returned. In the case of ID_TEAM_BALANCER_REQUESTED_TEAM_CHANGE_PENDING the request will stay in memory. ID_TEAM_BALANCER_SET_TEAM will be returned when someone on the desired team leaves or wants to switch to your team. If SetLockTeams(true) is called while you have a request pending, you will get ID_TEAM_BALANCER_TEAMS_LOCKED Determine how players' teams will be set when they call RequestAnyTeam(). Based on the specified enumeration, a player will join a team automatically Defaults to SMALLEST_TEAM This function is only used by the host By default, teams can be unbalanced up to the team size limit defined by SetTeamSizeLimits(). If SetForceEvenTeams(true) is called on the host, then teams cannot be unbalanced by more than 1 player If teams are uneven at the time that SetForceEvenTeams(true) is called, players at randomly will be switched, and will be notified of ID_TEAM_BALANCER_TEAM_ASSIGNED If players disconnect from the host such that teams would not be even, and teams are not locked, then a player from the largest team is randomly moved to even the teams. Defaults to false If set, calls to RequestSpecificTeam() and RequestAnyTeam() will return the team you are currently on. However, if those functions are called and you do not have a team, then you will be assigned to a default team according to SetDefaultAssignmentAlgorithm() and possibly SetForceEvenTeams(true) If lock is false, and SetForceEvenTeams() was called with force as true, and teams are currently uneven, they will be made even, and those players randomly moved will get ID_TEAM_BALANCER_TEAM_ASSIGNED Defaults to false Set the limit to the number of players on the specified team. SetTeamSizeLimit() must be called on the host, so the host can enforce the maximum number of players on each team. SetTeamSizeLimit() can be called on all systems if desired - for example, in a P2P environment you may wish to call it on all systems in advanced in case you become host.
http://www.jenkinssoftware.com/raknet/manual/Doxygen/classRakNet_1_1TeamBalancer.html
CC-MAIN-2020-05
en
refinedweb
A string that represents the current object. object.ToString is the major formatting method in the .NET Framework. It converts an object to its string representation so that it is suitable for display. (For information about formatting support in the .NET Framework, see Formatting Types.) The default implementation of the object.ToString method returns the fully qualified name of the type of the object, as the following example shows. code reference: System.Object.ToString#1 Because object is the base class of all reference types in the .NET Framework, this behavior is inherited by reference types that do not override the object.ToString method. The following example illustrates this. It defines a class named Object1 that accepts the default implementation of all object members. Its object.ToString method returns the object's fully qualified type name. code reference: System.Object.ToString#2 Types commonly override the object.ToString method to return a string that represents the object instance. For example, the base types such as char, int, and string provide object.ToString implementations that return the string form of the value that the object represents. The following example defines a class, Object2, that overrides the object.ToString method to return the type name along with its value. code reference: System.Object.ToString#3 When you call the object.ToString method on a class in the wrt, it provides the default behavior for classes that don’t override object.ToString. This is part of the support that the .NET Framework provides for the wrt (see .NET Framework Support for Windows Store Apps and Windows Runtime). Classes in the wrt don’t inherit object, and don’t always implement a object.ToString. However, they always appear to have object.ToString, object.Equals(object), and object.GetHashCode methods when you use them in your C# or Visual Basic code, and the .NET Framework provides a default behavior for these methods. Starting with the net_v451, the common language runtime will use tp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.tostring.aspx on a wrt object before falling back to the default implementation of object.ToString. wrt classes that are written in C# or Visual Basic can override the object.ToString method. Starting with win81, the wrt includes an tp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.aspx interface whose single method, tp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.tostring.aspx, provides basic formatting support comparable to that provided by object.ToString. To prevent ambiguity, you should not implement tp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.aspx on managed types. When managed objects are called by native code or by code written in languages such as JavaScript or C++/CX, they appear to implement tp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.aspx. The common language runtime will automatically route calls from tp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.tostring.aspx to object.ToString in the event tp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.aspx is not implemented on the managed object. Because the common language runtime auto-implements tp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.aspx for all managed types in win8_appstore_long apps, we recommend that you do not provide your own tp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.aspx implementation. Implementing tp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.aspx may result in unintended behavior when calling ToString from the wrt, C++/CX, or JavaScript. If you do choose to implement tp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.aspx in a public managed type that is exported in a wrt component, the following restrictions apply: You can define the tp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.aspx interface only in a "class implements" relationship, such as in C#, or in Visual Basic. You cannot implement tp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.aspx on an interface. You cannot declare a parameter to be of type tp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.aspx. tp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.aspx cannot be the return type of a method, property, or field. You cannot hide your tp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.aspx implementation from base classes by using a method definition such as the following: Instead, the tp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.tostring.aspx implementation must always override the base class implementation. You can hide a ToString implementation only by invoking it on a strongly typed class instance. Note that under a variety of conditions, calls from native code to a managed type that implements tp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.aspx or hides its tp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.tostring.aspx implementation can produce unexpected behavior. The following example outputs the textual description of the value of an object of type object to the console. C# Example using System; class MyClass { static void Main() { object o = new object(); Console.WriteLine (o.ToString()); } } The output is System.Object
http://docs.go-mono.com/monodoc.ashx?link=M%3ASystem.Object.ToString
CC-MAIN-2020-05
en
refinedweb
Add Tilo example Change-Id: Idc3b0311891363630aa8ffc3667b2b8889f1ef36 This repository contains recipes for Fuchsia. A recipe is a Python script that runs a series of commands, using the recipe engine framework from the LUCI project. We use recipes to automatically check out, build, and test Fuchsia in continuous integration jobs. The commands the recipes use are very similar to the ones you would use as a developer to check out, build, and test Fuchsia in your local environment. A recipe will not run without vpython and cipd. Prebuilt versions of vpython and cipd are downloaded into the //buildtools subtree of a Fuchsia checkout, though they live in different directories. Where $FUCHSIA is the root of a Fuchsia checkout and $OSTYPE is linux or mac, add to your PATH: $FUCHSIA/buildtools(for cipd) $FUCHSIA/buildtools/$OSTYPE-x64(for vpython) depot_tools Chrome's depot_tools repository provides these binaries, along with other tools necessary for interacting with the Chrome source and infrastructure. See the depot_tools Tutorial for installation instructions. Recipes are parameterized using properties. The values for these properties can be set in the Buildbucket configuration. In the recipe code itself, they are specified in a global dictionary named PROPERTIES and passed as arguments to a function named RunSteps. The recipes engine automatically looks for these two objects at the top level of the Python file containing the recipe. When writing a recipe, you can make your properties whatever you want, but if you plan to run your recipe on the Gerrit commit queue, there will be some standard ones starting with patch_, which give information about the commit being tested, and which you can see in the existing recipe code. When a recipe executes, it interacts with the underlying machine by running steps. A step is basically just a command, represented as a Python list of the arguments. You give the step a name, specify the arguments, and the recipe engine will run it in a subprocess, capture its output, and mark the job as as failed if the command fails. Here's an example: api.step('list temporary files', ['ls', '/tmp']) This will execute the command ls /tmp on the machine where the recipe is running, and it will cause a failure if, for example, there is no /tmp directory. When the recipe gets run on Swarming (which is the scheduling system we use to run Fuchsia continuous integration jobs) this step will show up with the label “list temporary files” in a list of all the steps that ran. Code is reused across recipes in the form of modules, which live either in the recipe_modules directory of this repo, or in the same directory of the recipe engine repo. The recipe engine's modules provide general functionality, and we have some modules specific to Fuchsia in this repo, such as wrappers for QEMU and Jiri. The recipe engine looks for a list named DEPS at the top level of the Python file containing the recipe, where you can specify the modules you want to use. Each item in DEPS is a string in the form “repo_name/module_name”, where the repo name is “recipe_engine” to get the dependency from the recipe engine repo, or “infra” to get it from this repo. The reason it's important to only interact with the underlying machine via steps is for testing. The recipes framework provides a way to fake the results of the steps when testing the recipe, instead of actually running the commands. It produces an “expected” JSON file, which shows exactly what commands would have run, along with context such as working directory and environment variables. You write tests using the GenTests function. Inside GenTests, you can use the yield statement to declare individual test cases. GenTests takes an API object, which has functions on it allowing you to specify the properties to pass to the recipe, as well as mock results for individual steps. Here's an example test case for a recipe that accepts input properties “manifest”, “remote”, “target”, and “tests”: yield api.test('failed_tests') + api.properties( manifest='fuchsia', remote='', target='x64', tests='tests.json', ) + api.step_data('run tests', retcode=1) In this example: api.testsimply gives the test case a name, which will be used to name the generated JSON “expected” file. api.propertiesspecifies the properties that will be passed to RunSteps. api.step_datatakes the name of one of the steps in the recipe, in this case “run tests”, and specifies how it should behave. This is where you can make the fake commands produce your choice of fake output. Or, as in this example, you can specify a return code, in order to cover error-handling code branches in the recipe. To run the unit tests and generate the “expected” data, run the following command from the root of this repo: python recipes.py test train # Optionally specify a configuration file with --package # (default is infra/config/recipes.cfg) python recipes.py --package infra/config/recipes.cfg test train The name of the recipe is simply the name of the recipe's Python file minus the .py extension. So, for example, the recipe in recipes/fuchsia.py is called “fuchsia”. After you run the test train command, the JSON files with expectations will be either generated or updated. Look at diff in Git, and make sure you didn't make any breaking changes. To just run the tests without updating the expectation files: python recipes.py test run --filter [recipe_name] To debug a single test, you can do this, which limits the test run to a single test and runs it in pdb: python recipes.py test debug --filter [recipe_name].[test_name] When you write new recipes or change existing recipes, your basic goal with unit testing should be to cover all of your code and to check the expected output to see if it makes sense. So if you create a new conditional, you should add a new test case. For example, let‘s say you’re adding a feature to a simple recipe: PROPERTIES = { 'word': Property(kind=str, default=None), } def RunSteps(api, word): api.step('say the word', ['echo', word]) def GenTests(api): yield api.test('hello', word='hello') And let's say you want to add a feature where it refuses to say “goodbye”. So you change it to look like this: def RunSteps(api, word): if word == 'goodbye': word = 'farewell' api.step('say the word', ['echo', word]) To make sure everything works as expected, you should add a new test case for your new conditional: def GenTests(api): yield api.test('hello', word='hello') yield api.test('no_goodbye', word='goodbye') There will now be two generated files when you run test train: one called hello.json and one called no_goodbye.json, each showing what commands the recipe would have run depending on how the word property is set. Unit tests should be the first thing you try to verify that your code runs. But when writing a new recipe or making major changes, you'll also want to make sure the recipe works when you actually run it. To run the recipe locally, you need to be authorized to access LUCI services. If you've never logged in to any LUCI service (cipd, isolated, etc), login with: cipd auth-login Now you can run the recipe with: python recipes.py run --properties-file test.json [recipe_name] For this command to work, you need to create a temporary file called test.json specifying what properties you want to run the recipe with. Here's an example of what that file might look like, for the fuchsia.py recipe: { "project": "garnet", "manifest": "manifest/garnet", "remote": "", "packages": ["garnet/packages/default"], "target": "x64", "build_type": "debug", "run_tests": true, "runtests_args": "/system/test", "snapshot_gcs_bucket": "", "tryjob": true, "$recipe_engine/source_manifest": {"debug_dir": null} } The last line helps prevent an error during local execution. It explicitly nullifies a debug directory set by the environment on actual bots. If something strange is happening between re-runs, consider deleting the local work directory as is done on bots ( rm -rf .recipe_deps). To run a test under PDB (the Python DeBugger), run: python recipes.py test debug --filter [recipe_name] We format python code according to the Chrome team's style, using yapf. After committing your changes you can format the files in your commit by running this in your recipes project root: (Make sure yapf is in your PATH) git diff --name-only HEAD^ | grep -E '.py$' | xargs yapf -i --name-onlytells git to list file paths instead of contents. HEAD^specifies only files that have changed in the latest commit. -Eenables regular expressions for grep. -iinstructs yapf to format files in-place instead of writing to stdout. Occasionally you‘ll be confronted with the task of naming a step. It’s important that this name is informative as it will appear within the UI. Other than that, there are only two rules: See the generated documentation for our existing recipes and modules for more information on what they do and how to use them.
https://fuchsia.googlesource.com/infra/recipes/+/refs/heads/sandbox/kjharland/tilo
CC-MAIN-2020-05
en
refinedweb
uuid_type 1.0.1-beta UUID type for Dart 2 # This package provides implementation of Universally Unique Identifier (UUID) for Dart, and supports generation, parsing and formatting of UUIDs. Features: - [x] Creates UUID from string and byte-array, as well as GUID and URN strings - [x] Provides access to variant, version and byte data of UUID - [x] Generates RFC4122 time-based v1, random-based v4, and name & namespace based v5 UUIDs - [x] Implements Comparablefor UUID comparison and lexicographical sorting - [x] Runs on Dart VM and in browser RFC 4122 Version support: - [x] v1, based on timestamp and MAC address (RFC 4122) - [ ] v2, based on timestamp, MAC address and POSIX UID/GID (DCE 1.1) Not planned - [ ] v3, based on MD5 hashing (RFC 4122) Not planned - [x] v4, based on random numbers (RFC 4122) - [x] v'; 1.0.0-beta # - More tests and documentation 0.9.0-beta # - Time-based generator is refactored to use Stopwatchinstead of DateTimecalls. Parameter clockSequenceis now deprecated in TimeBasedUuidGeneratorconstructor - Comparison is refactored to treat v1 UUIDs differently - Abstract Uuidclass now has compareTomethod implemented 0.8.0-beta # - Refactored string parsing (does not affect API) - Added comparison operators > >= < <= 0.7.0-dev # - Dart 2.0 is a minimum required version 0.6.0-dev # toBytes()method was renamed to bytesgetter 0.5.2-dev # - Initial package documentation 0.5.1-dev # - Initial relase, and tests Use this package as a library 1. Depend on it Add this to your package's pubspec.yaml file: dependencies: uuid_type: ^1.0.1-beta:uuid_type/uuid_type.dart'; We analyzed this package on Jan 16, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using: - Dart: 2.7.0 - pana: 0.13.4 Health suggestions Fix lib/src/uuid.dart. (-11.78 points) Analysis of lib/src/uuid.dart reported 25 hints, including: line 27 col 30: Unnecessary new keyword. line 31 col 26: Unnecessary new keyword. line 31 col 45: Unnecessary new keyword. line 39 col 13: Unnecessary new keyword. line 46 col 12: Unnecessary new keyword. Fix lib/src/generators.dart. (-6.31 points) Analysis of lib/src/generators.dart reported 13 hints, including: line 20 col 23: Unnecessary new keyword. line 23 col 32: Unnecessary new keyword. line 38 col 7: Unnecessary new keyword. line 51 col 33: Unnecessary new keyword. line 60 col 16: Unnecessary new keyword. Maintenance suggestions Package is pre-release. (-5 points) Pre-release versions should be used with caution; their API can change in breaking ways. Maintain an example. None of the files in the package's example/ directory matches known example patterns. Common filename patterns include main.dart, example.dart, and uuid_type.dart. Packages with multiple examples should provide example/README.md. For more information see the pub package layout conventions.
https://pub.dev/packages/uuid_type
CC-MAIN-2020-05
en
refinedweb
bus_stop 0.0.2 Bus Stop 🚍🚏 # A simple Flutter widget that listens to Event Buses. Learn more about event buses. Getting Started 🚀 # Install # dependencies: bus_stop: "^0.0.2" Import # import 'package:bus_stop/bus_stop.dart'; Usage 🕹 # Bus Stop can show a SnackBar and/or change the child Widget based whether the event fires. If doShowSnackBar is set to true, snackBarContext and snackBar must not be null where snackBarContext is a BuildContext that contains a Scaffold. import 'package:flutter/material.dart'; import 'package:bus_stop/bus_stop.dart'; import 'package:event_bus/event_bus.dart'; void main() => runApp(MyApp()); EventBus bus = EventBus(); /// Event type. class Event {} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( title: Text("Bus Stop Demo"), ), body: DemoWidget(), ), ); } } class DemoWidget extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ RaisedButton( child: Text("Fire Event"), onPressed: () { bus.fire(Event()); }, ), BusStop<Event>( eventBus: bus, builder: (BuildContext context, bool didEventFire) { // Uncomment below code to only use SnackBar // return SizedBox(); if (didEventFire) return Text("Fired"); else return Text("Not Fired"); }, doShowSnackBar: true, snackBarContext: context, snackBar: SnackBar(content: Text("Event Fired")), ), ], ), ); } } [0.0.2] - 3/19/19 - Updates description. [0.0.1] - 3/19/19 - Implementation of a widget that listens to an event bus and acts on those events.: bus_stop: :bus_stop/bus_stop.dart'; We analyzed this package on Jan 16, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using: - Dart: 2.7.0 - pana: 0.13.4 - Flutter: 1.12.13+hotfix.5 Maintenance suggestions Package is pre-v0.1 release. (-10 points) While nothing is inherently wrong with versions of 0.0.*, it might mean that the author is still experimenting with the general direction of the API.
https://pub.dev/packages/bus_stop
CC-MAIN-2020-05
en
refinedweb
trace Percentile Interactive Tracing and Debugging of Calls to a Function or Method A. - Keywords - programming, debugging Usage trace(what, tracer, exit, at, print, signature, where = topenv(parent.frame()), edit = FALSE) untrace(what, signature = NULL, where = topenv(parent.frame())) tracingState(on = NULL) .doTrace(expr, msg) returnValue(default = NULL) Arguments - what the name, possibly quote()d, of a function to be traced or untraced. For untraceor for tracewith more than one argument, more than one name can be given in the quoted form, and the same action will be applied to each one. For “hidden” functions such as S3 methods in a namespace, where = *typically needs to be specified as well. - tracer either a function or an unevaluated expression. The function will be called or the expression will be evaluated either at the beginning of the call, or before those steps in the call specified by the argument at. See the details section. - exit either a functionor an unevaluated expression. The function will be called or the expression will be evaluated on exiting the function. See the details section. - at optional numeric vector or list. If supplied, tracerwill be called just before the corresponding step in the body of the function. See the details section. If TRUE(as per default), a descriptive line is printed before any trace expression is evaluated. - signature If this argument is supplied, it should be a signature for a method for function what. In this case, the method, and not the function itself, is traced. - edit For complicated tracing, such as tracing within a loop inside the function, you will need to insert the desired calls by editing the body of the function. If so, supply the editargument either as TRUE, or as the name of the editor you want to use. Then trace()will call editand use the version of the function after you edit it. See the details section for additional information. - where where to look for the function to be traced; by default, the top-level environment of the call to trace. An important use of this argument is to trace functions from a package which are “hidden” or called from another package. The namespace mechanism imports the functions to be called (with the exception of functions in the base package). The functions being called are not the same objects seen from the top-level (in general, the imported packages may not even be attached). Therefore, you must ensure that the correct versions are being traced. The way to do this is to set argument whereto a function in the namespace (or that namespace). The tracing computations will then start looking in the environment of that function (which will be the namespace of the corresponding package). (Yes, it's subtle, but the semantics here are central to how namespaces work in R.) - on logical; a call to the support function tracingStatereturns TRUEif tracing is globally turned on, FALSEotherwise. An argument of one or the other of those values sets the state. If the tracing state is FALSE, none of the trace actions will actually occur (used, for example, by debugging functions to shut off tracing during debugging). - expr, msg arguments to the support function .doTrace, calls to which are inserted into the modified function or method: expris the tracing action (such as a call to browser()), and msgis a string identifying the place where the trace action occurs. - default If returnValuefinds no return value (e.g. a function exited because of an error, restart or as a result of evaluating a return from a caller function), it will return defaultinstead. Details an S4.) Value. Note. References Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole. See Also browser and recover, the likeliest tracing functions; also, quote and substitute for constructing general expressions. Aliases - trace - untrace - tracingState - .doTrace - returnValue Examples library(base) # NOT RUN {) # } # NOT RUN { <!-- %% methods is loaded when needed --> # } # NOT RUN { <!-- %% if(.isMethodsDispatchOn()) { # non-simple use needs 'methods' package --> # } # NOT RUN { untrace(f) # (as it has changed f's body !) as.list(body(f)) as.list(body(f)[[3]]) # -> stop(..) is [[4]] ## Now call the browser there trace("f", quote(browser(skipCalls = 4)), at = list(c(3,4))) # } # NOT RUN { f(-1,2) # --> enters browser just before stop(..) # } # NOT RUN { ## trace a utility function, with recover so we ## can browse in the calling functions as well. trace("as.matrix", recover) ## turn off the tracing (that happened above) untrace(c("f", "as.matrix")) # } # NOT RUN { ## Useful to find how system2() is called in a higher-up function: trace(base::system2, quote(print(ls.str()))) # } # NOT RUN { ##-------- Tracing hidden functions : need 'where = *' ## ## 'where' can be a function whose environment is meant: trace(quote(ar.yw.default), where = ar) a <- ar(rnorm(100)) # "Tracing ..." untrace(quote(ar.yw.default), where = ar) ## trace() more than one function simultaneously: ## expression(E1, E2, ...) here is equivalent to ## c(quote(E1), quote(E2), quote(.*), ..) trace(expression(ar.yw, ar.yw.default), where = ar) a <- ar(rnorm(100)) # --> 2 x "Tracing ..." # and turn it off: untrace(expression(ar.yw, ar.yw.default), where = ar) # } #")) # } # NOT RUN { <!-- %%}% only if 'methods' --> # }
https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/trace
CC-MAIN-2020-05
en
refinedweb
User Defined Functions¶ Ibis provides a mechanism for writing custom scalar and aggregate functions, with varying levels of support for different backends. UDFs/UDAFs are a complex topic. This section of the documentation will discuss some of the backend specific details of user defined functions. Warning The UDF API is provisional and subject to change. Pandas¶ Ibis supports defining three kinds of user-defined functions for operations on expressions targeting the pandas backend: element-wise, reduction, and analytic. Element-wise Functions¶ An element-wise function is a function that takes N rows as input and produces N rows of output. log, exp, and floor are examples of element-wise functions. Here’s how to define an element-wise function: import ibis.expr.datatypes as dt from ibis.pandas import udf @udf.elementwise(input_type=[dt.int64], output_type=dt.double) def add_one(x): return x + 1.0 Reduction Functions¶ A reduction is a function that takes N rows as input and produces 1 row as output. sum, mean and count are examples of reductions. In the context of a GROUP BY, reductions produce 1 row of output per group. Here’s how to define a reduction function: import ibis.expr.datatypes as dt from ibis.pandas import udf @udf.reduction(input_type=[dt.double], output_type=dt.double) def double_mean(series): return 2 * series.mean() Analytic Functions¶ An analytic function is like an element-wise function in that it takes N rows as input and produces N rows of output. The key difference is that analytic functions can be applied per group using window functions. Z-score is an example of an analytic function. Here’s how to define an analytic function: import ibis.expr.datatypes as dt from ibis.pandas import udf @udf.analytic(input_type=[dt.double], output_type=dt.double) def zscore(series): return (series - series.mean()) / series.std() Details of Pandas UDFs¶ Element-wise functions automatically provide support for applying your UDF to any combination of scalar values and columns. Reduction functions automatically provide support for whole column aggregations, grouped aggregations, and application of your function over a window. Analytic functions work in both grouped and non-grouped settings The objects you receive as input arguments are either pandas.Seriesor Python/NumPy scalars. Note Any keyword arguments must be given a default value or the function will not work. A common Python convention is to set the default value to None and handle setting it to something not None in the body of the function. Using add_one from above as an example, the following call will receive a pandas.Series for the x argument: import ibis import pandas as pd df = pd.DataFrame({'a': [1, 2, 3]}) con = ibis.pandas.connect({'df': df}) t = con.table('df') expr = add_one(t.a) expr And this will receive the int 1: expr = add_one(1) expr Since the pandas backend passes around **kwargs you can accept **kwargs in your function: import ibis.expr.datatypes as dt from ibis.pandas import udf @udf.elementwise([dt.int64], dt.double) def add_two(x, **kwargs): # do stuff with kwargs return x + 2.0 Or you can leave them out as we did in the example above. You can also optionally accept specific keyword arguments. For example: import ibis.expr.datatypes as dt from ibis.pandas import udf @udf.elementwise([dt.int64], dt.double) def add_two_with_none(x, y=None): if y is None: y = 2.0 return x + y BigQuery¶ Note BigQuery only supports element-wise UDFs at this time. BigQuery supports UDFs through JavaScript. Ibis provides support for this by turning Python code into JavaScript. The interface is very similar to the pandas UDF API: import ibis.expr.datatypes as dt from ibis.bigquery import udf @udf([dt.double], dt.double) def my_bigquery_add_one(x): return x + 1.0 Ibis will parse the source of the function and turn the resulting Python AST into JavaScript source code (technically, ECMAScript 2015). Most of the Python language is supported including classes, functions and generators. When you want to use this function you call it like any other Python function–only it must be called on an ibis expression: t = ibis.table([('a', 'double')]) expr = my_bigquery_add_one(t.a) print(ibis.bigquery.compile(expr))
https://docs.ibis-project.org/udf.html
CC-MAIN-2020-05
en
refinedweb
Adding for summing an array, which may be surprising if you haven’t thought about this before. This post will look at Kahan’s algorithm, one of the first non-obvious algorithms for summing a list of floating point numbers. We will sum a list of numbers a couple ways using C’s float type, a 32-bit integer. Some might object that this is artificial. Does anyone use floats any more? Didn’t moving from float to double get rid of all our precision problems? No and no. In fact, the use of 32-bit float types is on the rise. Moving data in an out of memory is now the bottleneck, not arithmetic operations per se, and float lets you pack more data into a giving volume of memory. Not only that, there is growing interest in floating point types even smaller than 32-bit floats. See the following posts for examples: And while sometimes you need less precision than 32 bits, sometimes you need more precision than 64 bits. See, for example, this post. Now for some code. Here is the obvious way to sum an array in C: float naive(float x[], int N) { float s = 0.0; for (int i = 0; i < N; i++) { s += x[i]; } return s; } Kahan’s algorithm is not much more complicated, but it looks a little mysterious and provides more accuracy. float kahan(float x[], int N) { float s = x[0]; float c = 0.0; for (int i = 1; i < N; i++) { float y = x[i] - c; float t = s + y; c = (t - s) - y; s = t; } return s; } Now to compare the accuracy of these two methods, we’ll use a third method that uses a 64-bit accumulator. We will assume its value is accurate to at least 32 bits and use it as our exact result. double dsum(float x[], int N) { double s = 0.0; for (int i = 0; i < N; i++) { s += x[i]; } return s; } For our test problem, we’ll use the reciprocals of the first 100,000 positive integers rounded to 32 bits as our input. This problem was taken from [2]. #include <stdio.h>: int main() { int N = 100000; float x[N]; for (int i = 1; i <= N; i++) x[i-1] = 1.0/i; printf("%.15g\n", naive(x, N)); printf("%.15g\n", kahan(x, N)); printf("%.15g\n", dsum(x, N)); } This produces the following output. 12.0908508300781 12.0901460647583 12.0901461953972 The naive method is correct to 6 significant figures while Kahan’s method is correct to 9 significant figures. The error in the former is 5394 times larger. In this example, Kahan’s method is as accurate as possible using 32-bit numbers. Note that in our example we were not exactly trying to find the Nth harmonic number, the sum of the reciprocals of the first N positive numbers. Instead, we were using these integer reciprocals rounded to 32 bits as our input. Think of them as just data. The data happened to be produced by computing reciprocals and rounding the result to 32-bit floating point accuracy. But what if we did want to compute the 100,000th harmonic number? There are methods for computing harmonic numbers directly, as described here. Related posts - Anatomy of a floating point number - Why IEEE floating point numbers have +0 and -0 - IEEE floating point exceptions in C++ [1] The condition number of a problem is basically a measure of how much floating point errors are multiplied in the process of computing a result. A well-conditioned problem has a small condition number, and a ill-conditioned problem has a large condition number. With ill-conditioned problems, you may have to use extra precision in your intermediate calculations to get a result that’s accurate to ordinary precision. [2] Handbook of Floating-Point Arithmetic by Jen-Michel Muller et al. 6 thoughts on “Summing an array of floating point numbers” Either my C is very rusty or function kahan does not return a result… I reformatted the code when I pasted it into the blog post. Maybe that’s when the return got lost. Anyway, thanks. I just fixed it. My first thought was to sort the data from smallest to largest and that gave 12.0901527404785, 12.0901460647583, and 12.0901461953972. XML character entity error in the test listing (include statement). More importantly, the naive method is accurate to five digits (not six), and Kahan’s method is accurate to seven (not nine). Which is reassuring, since floats have at most seven decimal digits of precision. How does kahan compare to dsum in terms of run time? Naively I would expect 4 operations on 16-bit numbers to take longer than 1 operation on 32-bit numbers, but perhaps the conversion itself is more expensive? Or does it depend on the specific language and/or hardware implementation? @Nathan: Kahan’s algorithm would normally be used to get more accuracy out of the available precision. I wrote my example as if only floats were available, then cheated to get a gold standard value to compare to. If you have doubles, you’d likely use dsum, and if that’s not accurate enough, you could use Kahan’s algorithm using doubles.
https://www.johndcook.com/blog/2019/11/05/kahan/
CC-MAIN-2020-05
en
refinedweb
to print the argument values in case of an exception (which is most of the time the only case where you want the values to be traced...) import inspect def fn(x): try: print(1/0) except: frames = inspect.trace() argvalues = inspect.getargvalues(frames[0][0]) print("Argvalues: ", inspect.formatargvalues(*argvalues)) raise fn(12) ('Argvalues: ', '(x=12)') It works like magic! I love Python.... if only it was Java, I would love it even more... let's say if Java was more Pythonic it would be a perfect world... well also if USA stopped invading and destroying countries it would not hurt...
http://www.javamonamour.org/2015/03/
CC-MAIN-2020-05
en
refinedweb
What the Singleton Pattern Costs You What the Singleton Pattern Costs You Singletons increase coupling, lower testability, and reduce your ability to reason about the code. All of this works towards creating unbreakable assumptions about it. Join the DZone community and get the full member experience.Join For Free Do you use the singleton pattern? If not, I’m assuming that you either don’t know what it is or that you deliberately avoid it. If you do use it, you’re probably sick of people judging you for it. The pattern is something of a lightning rod in the world of object-oriented programming. You can always use Stack Overflow as a litmus test for programming controversy. Someone asked “what was so bad” about singletons, and voting, responding, and commenting went off the charts. Most of those responses fell into the negative category. Outside of Stack Overflow, people call singletons evil, pathological liars, and anti-patterns. People really seem to hate this design pattern — at least some of them do, anyway. NDepend takes a stance on the singleton pattern as well, both in its rules and on the blog. Specifically, it encourages you to avoid it. But I’m not going to take a stance today, exactly. I understand the cathartic temptation to call something evil in the world of programming. If some (anti) pattern, framework, or language approach has caused you monumental pain in the past, you come to view it as the tool of the devil. I’ve experienced this and turned it into a blog post, myself. Instead of going that route here, however, I’m going to speak instead about what it can cost you when you decide to use the singleton pattern — what it can cost the future you, that is. I have a consulting practice assessing third-party codebases, so I’ve learned to view patterns and practices through a dispassionate lens. Everything is just trade-offs. What Is the Singleton Pattern, Anyway? Before I go any further, I should probably explain briefly what this thing is, in case you aren’t familiar. I won’t belabor the point, but here’s a quick example. (I’m keeping this to a bare minimum and not worrying about non-core concepts like thread safety.) public class ASingleton { private static ASingleton _instance; private ASingleton() { } public static ASingleton Instance { get { if (_instance == null) _instance = new ASingleton(); return _instance; } } } Alright, so why do this? Well, the pattern authors define its charter as serving two principal purposes: - Ensure that only one instance of the class ever exists. - Provide global access to that single instance. So let’s consider implications and usage. When you use this pattern, you define an object that will exist across all application scope and that you can easily access from anywhere in the code at any time. A logger is, perhaps, the most iconic example of a singleton use case. You need to manage access to a resource (file), you only want one to exist, and you’ll need to use it in a lot of places. A marriage made in heaven, right? Well, in principle, yes, I suppose so. But in practice, things tend to get a lot messier. Let’s take a look at what can happen when you introduce the singleton pattern into your codebase. Let’s look at what it can cost you. Side Effects Hurt the Ability to Reason About Your Code Think for a moment about how you would invoke an instance method on a singleton class. For instance, let’s say that you’d implemented your own logger. Using it might look something like this: public Order BuildSimpleOrder(int orderId) { var order = new Order() { Id = orderId }; Logger.Instance.Log($"Built order {orderId}"); return order; } The method constructs an order in memory based on the order’s ID and then returns that order, stopping along the way to log. It seems simple enough, but the invocation of the logging presents a simple conundrum. If I’m looking at just the signature of BuildSimpleOrder, say, via IntelliSense, the logging is utterly opaque to me. It’s a hidden side effect. When I instantiate the class containing BuildSimpleOrder, I don’t inject a reference of a logger into a constructor. I don’t pass the logger in via a setter, and I don’t give it to this method as a parameter. Instead, the method quietly reaches out into the ether and invokes the logger which, in turn, triggers file I/O (presumably). When you have singletons in your codebase, you lose any insight into what methods are doing. You can take nothing for granted, and you must inspect each and every line of your code to understand its behavior, making it generally harder to reason about. This was why Misko Hevery called singletons “liars.” BuildSimpleOrder now does something completely unrelated to building a simple order — it writes to a file. You Give Up Testability Consuming singletons doesn’t just make your code harder to reason about. It also makes your code harder to unit test. Think of writing unit tests for the method above. Without the logger instance, that would be a piece of cake. It’d look like this: [TestMethod] public void BuildSimpleOrder_Sets_OrderId_To_Passed_In_Value() { const int id = 8; var processor = new OrderProcessor(); var order = processor.BuildSimpleOrder(id); Assert.AreEqual<int>(id, order.Id); } Then, if building the order demanded a bit more complexity, you could easily add more tests. This is an imminently testable method…without the call to the logger. With the call to the logger, however, things get ugly. That call starts to trigger file I/O, which will give the test runner fits. Depending on the runner and machine in question, it might throw exceptions because it lacks permissions to write the file. It may actually write the file and just take a while. It may throw exceptions because the file already exists. Who knows? And worst of all, it may behave entirely different on your machine, on Bob in the next cubicle’s machine, and on the build. Normally when you have external dependencies like this, you can use dependency injection and mock them. But singletons don’t work that way. They’re inline calls that you, as a consumer, are powerless to interpose on. You Incur Incredible Fan-In and Promote Hidden Coupling Singletons tend to invite use and to invite abuse. You’d be surprised how handy it can be to have a deus ex machina at your disposal when you suddenly need two objects at the complete opposite ends of your object graph to collaborate. Man, we could solve this really quickly and with little rework if the login screen could just talk directly to the admin screen. Hey, I know! They both have access to the logger. We could just add a flag on the logger. It’d only be temporary, of course… Yeah, we both know that flag will NOT be temporary. And this sort of thing happens in codebases that rely on the singleton pattern. More and more classes take direct dependencies on the singletons, creating a high degree of fan-in (afferent coupling) for the singleton types. This makes them simultaneously the riskiest types to change, the hardest types to test, and the most likely types to change, all of which adds up to maintenance headaches. But it even gets worse. Singletons don’t just invite types to couple themselves to the singleton. They also invite types to couple their own logic through the singleton. Think of the login and admin screens communicating through the singleton. It acts as a vessel for facilitating hidden couplings as well. And while I will concede that use of the pattern does not automatically constitute abuse, I will say that inviting it is problematic. This holds doubly true when your only method of preventing abuse is vigilant, manual oversight of the entire codebase. You Lose the Ability to Revisit Your Assumptions I’ll close by offering a more philosophical cost of the singleton pattern that builds on the last three. You have code with side effects that you have a hard time reasoning about. Likewise, you can’t easily test it, and you create an outsize dependency on the singleton pattern instances. What does all of that wind-up mean? It means that changing your assumptions about the singleton itself becomes nearly impossible. These things cast themselves in iron in your codebase and insert tentacles into every area of your code. Imagine the horror if a business analyst came along and said something like, “Why can’t we just have two simultaneous log files?” or, “Why can’t we have sessions that stop and then restart later?” In answer to these seemingly reasonable requests, the architect will turn red and splutter, “Are you CRAZY?! Do you know how much rework that would mean?” When you use singletons, you had better make sure that there could really only ever be one log file, print spooler, session, etc. and that your instance of that will last the same length as the program. Because if that assumption ever needs to change, you’ll find yourself in a world of pain, to the tune of a total rewrite. I won’t call the singleton pattern evil or rail against it. But I will tell you that it extracts a pretty high toll from you in the long run. Published at DZone with permission of Erik Dietrich , DZone MVB. See the original article here. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/what-the-singleton-pattern-costs-you
CC-MAIN-2020-05
en
refinedweb
#include <stdlib.h>size_t mbstowcs(wchar_t *out, const char *in, size_t size); The mbstowcs( ) function converts the multibyte string pointed to by in into a wide-character string and puts that result in the array pointed to by out. Only size number of bytes will be stored in out. In C99, out and in are qualified by restrict. The mbstowcs( ) function returns the number of multibyte characters that are converted. If an error occurs, the function returns –1. Related functions are wcstombs( ) and mbtowc( ).
https://flylib.com/books/en/3.13.1.328/1/
CC-MAIN-2020-05
en
refinedweb
Reason The .NET Framework doesn’t correctly determine the ISO 8601 compliant number of a week within a year, as outlined in. This is a problem when working within the EU especially, as most countries here use ISO 8601 week numbers. Although there are a lot of code samples to be found on e.g. Stack Overflow solving the problem, I found most of them to involve too many magic numbers to be acceptable for production code. Code The following functionality was inspired by the concept of week dates and is comprised of a Week and WeekDate class. Source code and tests can also be found on GitHub. Week using System; using System.Collections.Generic; using System.Globalization; using System.Linq; public class Week : IComparable<Week>, IEquatable<Week> { private const DayOfWeek FirstDayOfWeek = DayOfWeek.Monday; private const DayOfWeek LastDayOfWeek = DayOfWeek.Sunday; private const DayOfWeek PivotDayOfWeek = DayOfWeek.Thursday; private static readonly Calendar Calendar = CultureInfo.InvariantCulture.Calendar; public Week(DateTime date) { StartOfWeek = GetStartOfWeek(date); EndOfWeek = GetEndOfWeek(date); DateTime pivotDayOfWeek = GetPivotDayOfWeek(StartOfWeek); WeekNumber = Calendar.GetWeekOfYear(pivotDayOfWeek, CalendarWeekRule.FirstFourDayWeek, FirstDayOfWeek); WeekYear = pivotDayOfWeek.Year; } public DateTime StartOfWeek { get; private set; } public DateTime EndOfWeek { get; private set; } public int WeekNumber { get; private set; } public int WeekYear { get; private set; } private DateTime GetStartOfWeek(DateTime date) { while (date.DayOfWeek != FirstDayOfWeek) { date = date.AddDays(-1); } return date; } private DateTime GetEndOfWeek(DateTime date) { while (date.DayOfWeek != LastDayOfWeek) { date = date.AddDays(1); } return date; } private DateTime GetPivotDayOfWeek(DateTime startOfWeek) { while (startOfWeek.DayOfWeek != PivotDayOfWeek) { startOfWeek = startOfWeek.AddDays(1); } return startOfWeek; } /// <summary> /// Returns a sortable ISO week string (e.g. "2009-W53"). /// </summary> public override string ToString() { return string.Format("{0}-W{1:00}", WeekYear, WeekNumber); } public int CompareTo(Week other) { return other == null ? -1 : string.Compare(ToString(), other.ToString(), StringComparison.Ordinal); } public bool Equals(Week other) { return other != null && string.Equals(ToString(), other.ToString(), StringComparison.Ordinal); } public override bool Equals(object obj) { return Equals(obj as Week); } public override int GetHashCode() { return ToString().GetHashCode(); } public static IList<Week> GetWeeks(DateTime from, DateTime to) { List<Week> weeks = new List<Week>(); weeks.Add(new Week(from)); while (weeks.Last().EndOfWeek.Date < to.Date) { DateTime startOfNextWeek = weeks.Last().EndOfWeek.AddDays(1); weeks.Add(new Week(startOfNextWeek)); } return weeks; } } WeekDate using System; using System.Collections.Generic; using System.Linq; public class WeekDate : Week { private readonly DateTime _date; public WeekDate(DateTime date) : base(date) { _date = date; DayNumber = GetDayNumber(date.DayOfWeek); } public int DayNumber { get; private set; } /// <summary> /// Returns a sortable ISO week date string (e.g. "2009-W53-2"). /// </summary> public override string ToString() { return string.Format("{0}-W{1:00}-{2}", WeekYear, WeekNumber, DayNumber); } private int GetDayNumber(DayOfWeek dayOfWeek) { switch (dayOfWeek) { case DayOfWeek.Monday: return 1; case DayOfWeek.Tuesday: return 2; case DayOfWeek.Wednesday: return 3; case DayOfWeek.Thursday: return 4; case DayOfWeek.Friday: return 5; case DayOfWeek.Saturday: return 6; case DayOfWeek.Sunday: return 7; default: throw new ArgumentOutOfRangeException("dayOfWeek", dayOfWeek, "Unknown day of week."); } } public static IList<WeekDate> GetWeekDates(DateTime from, DateTime to) { List<WeekDate> weekDates = new List<WeekDate>(); weekDates.Add(new WeekDate(from)); while (weekDates.Last()._date < to.Date) { DateTime nextDay = weekDates.Last()._date.AddDays(1); weekDates.Add(new WeekDate(nextDay)); } return weekDates; } } Example A screenshot of unit testing the Week class: A screenshot of unit testing the WeekDate class:
https://reasoncodeexample.com/2013/12/08/iso-8601-compliant-week-numbers/
CC-MAIN-2020-05
en
refinedweb
Now that we have a data source and a service to interact with this data source, it's time to start working on the routes and components that will consume this data. Add a routes.ts file to the app folder with the following configuration: import { Routes } from '@angular/router';import { HomeComponent } from './home/home.component';import { PostComponent } from './post/post.component';export const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'post/:id', component: PostComponent }] The second route that points to post has a :id placeholder. This is used to define a dynamic route, which means that the value passed in as ID can be used to control the behavior of the mounted component. Create the two components ...
https://www.oreilly.com/library/view/typescript-2x-for/9781786460554/f6dfcd6e-1586-4388-bdcd-51cd52c2caf4.xhtml
CC-MAIN-2020-05
en
refinedweb
HTML export: icons are exported with an absolute path to zim ressource directory instead of being copied when exporting a single page Bug Description Hello, I run a local version of Zim. By "local", I mean that I did not installed Zim through a distribution package but instead I start zim.py directly from the sources directory. I use Zim version from Bazar (revision number is the 450). When exporting a single page to HTML, icons are not copied in the same directory as the page. Instead, the HTML code points to the location of the icons in my installation directory. For example, the wiki text: [*] test Would translate into the following HTML code: <p> <ul> <li style=" </ul> </p> I had a quick look at the code, it seems that the icons are copied only when exporting the complete notebook and are not for a single page export. The proper behavior would be to have the icons copied on both type of export. Thank you for your hard work! Regards, Tony I have the same issue with latest bzr source. HTML export can be usefull to show your work on a web server. If you make little changes to one page, you export this single page and upload it. In this usecase, you notice the bug. Regards, I agree with the stated use case; At work, I use one large notebook. I often need to share a single page with colleagues and I prefer to avoid static methods like email attachments and prefer to use more dynamic methods like exporting html to a web server or network share. If this is accepted as a bug then I think the fix is a change to exporter.py. Currently when exporting a single page the linker.target_dir is not set. Attached is a possible solution, the only difference is the addition of line 194: "self.linker. Above I posted a possible solution to the specific bug but another option is a plugin. Two advantages of the plugin: 1) it does not require changing exporter.py 2) it meets my additional requirement for a one button export method (if you typically use the same export settings then the current export wizard has a lot of extra dialogs and clicks). Attached is the Quick Export plugin. The plugin is very similar to the print to browser plugin but instead of using the template class it uses the exporter class. This allows for user preferences to configure: * Format * Template * Export Directory * Resolved Prefix * Resolve resource links * Use namespace directory structure I think this should be fixed directly in exporter. Will have to take a look at your changes to judge if I can merge them as is. Put it on my list. Regards, Jaap Fixed in zim 0.61 I think I agree. Though I am interested in the use case for single page export -- I myself only use it for printing pages, in which case the absolute link is fine - so I'm interested to hear how others use it. Regards, Jaap
https://bugs.launchpad.net/zim/+bug/893633
CC-MAIN-2017-43
en
refinedweb
cliar 1.1.6 Cliar lets you create powerful commandline interfaces from regular Python classes. Using type hints, you can add validation and on-the-fly parsing. Create CLIs from Python classes. Make them powerful with type hints. Cliar is a Python tool that helps you create commandline interfaces: from cliar import CLI class Git(CLI): '''Git clone created with Cliar''' def clone(self, repo, dir='.'): '''Clone a git repo from REPO to DIR.''' print('Cloning from %s to %s' % (repo, dir)) if __name__ == '__main__': Git().parse() Run the script: $ python git.py clone -d baz Cloning from to baz Requirements Cliar runs with Python 3.5+ on Windows, Linux, and Mac. There are no external dependencies. Install Install Cliar from PyPI with pip: $ pip install cliar You can install Cliar on CentOS 6 with yum from Gleb Goncharov’s public repo: $ yum install -y python-cliar Hello World from cliar import CLI class Hello(CLI): def hello(self, name='world'): print('Hello ' + name + '!') if __name__ == '__main__': Hello().parse() python hello.py hello --name Bob Hello Bob! Limitations Cliar is designed to help you create CLIs quickly. For the sake of simplicity, some features are unavailable: - You can’t add help text for individual arguments. You can add help text for individual commands with docstrings though. - You can’t have 3rd-level commands. Contribute - Author: Konstantin Molchanov - License: MIT - Categories - Package Index Owner: moigagoo - DOAP record: cliar-1.1.6.xml
https://pypi.python.org/pypi/cliar/
CC-MAIN-2017-43
en
refinedweb